Add -fcross-module-specialise flag
[ghc.git] / compiler / main / DynFlags.hs
1 {-# LANGUAGE CPP #-}
2
3 -------------------------------------------------------------------------------
4 --
5 -- | Dynamic flags
6 --
7 -- Most flags are dynamic flags, which means they can change from compilation
8 -- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each
9 -- session can be using different dynamic flags. Dynamic flags can also be set
10 -- at the prompt in GHCi.
11 --
12 -- (c) The University of Glasgow 2005
13 --
14 -------------------------------------------------------------------------------
15
16 {-# OPTIONS_GHC -fno-cse #-}
17 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
18
19 module DynFlags (
20 -- * Dynamic flags and associated configuration types
21 DumpFlag(..),
22 GeneralFlag(..),
23 WarningFlag(..),
24 ExtensionFlag(..),
25 Language(..),
26 PlatformConstants(..),
27 FatalMessager, LogAction, FlushOut(..), FlushErr(..),
28 ProfAuto(..),
29 glasgowExtsFlags,
30 dopt, dopt_set, dopt_unset,
31 gopt, gopt_set, gopt_unset,
32 wopt, wopt_set, wopt_unset,
33 xopt, xopt_set, xopt_unset,
34 lang_set,
35 useUnicodeSyntax,
36 whenGeneratingDynamicToo, ifGeneratingDynamicToo,
37 whenCannotGenerateDynamicToo,
38 dynamicTooMkDynamicDynFlags,
39 DynFlags(..),
40 FlagSpec(..),
41 HasDynFlags(..), ContainsDynFlags(..),
42 RtsOptsEnabled(..),
43 HscTarget(..), isObjectTarget, defaultObjectTarget,
44 targetRetainsAllBindings,
45 GhcMode(..), isOneShot,
46 GhcLink(..), isNoLink,
47 PackageFlag(..), PackageArg(..), ModRenaming(..),
48 PkgConfRef(..),
49 Option(..), showOpt,
50 DynLibLoader(..),
51 fFlags, fWarningFlags, fLangFlags, xFlags,
52 dynFlagDependencies,
53 tablesNextToCode, mkTablesNextToCode,
54 SigOf, getSigOf,
55 checkOptLevel,
56
57 Way(..), mkBuildTag, wayRTSOnly, addWay', updateWays,
58 wayGeneralFlags, wayUnsetGeneralFlags,
59
60 -- ** Safe Haskell
61 SafeHaskellMode(..),
62 safeHaskellOn, safeImportsOn, safeLanguageOn, safeInferOn,
63 packageTrustOn,
64 safeDirectImpsReq, safeImplicitImpsReq,
65 unsafeFlags, unsafeFlagsForInfer,
66
67 -- ** System tool settings and locations
68 Settings(..),
69 targetPlatform, programName, projectVersion,
70 ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings,
71 versionedAppDir,
72 extraGccViaCFlags, systemPackageConfig,
73 pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T,
74 pgm_sysman, pgm_windres, pgm_libtool, pgm_lo, pgm_lc,
75 opt_L, opt_P, opt_F, opt_c, opt_a, opt_l,
76 opt_windres, opt_lo, opt_lc,
77
78
79 -- ** Manipulating DynFlags
80 defaultDynFlags, -- Settings -> DynFlags
81 defaultWays,
82 interpWays,
83 initDynFlags, -- DynFlags -> IO DynFlags
84 defaultFatalMessager,
85 defaultLogAction,
86 defaultLogActionHPrintDoc,
87 defaultLogActionHPutStrDoc,
88 defaultFlushOut,
89 defaultFlushErr,
90
91 getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a]
92 getVerbFlags,
93 updOptLevel,
94 setTmpDir,
95 setPackageKey,
96 interpretPackageEnv,
97
98 -- ** Parsing DynFlags
99 parseDynamicFlagsCmdLine,
100 parseDynamicFilePragma,
101 parseDynamicFlagsFull,
102
103 -- ** Available DynFlags
104 allFlags,
105 flagsAll,
106 flagsDynamic,
107 flagsPackage,
108 flagsForCompletion,
109
110 supportedLanguagesAndExtensions,
111 languageExtensions,
112
113 -- ** DynFlags C compiler options
114 picCCOpts, picPOpts,
115
116 -- * Configuration of the stg-to-stg passes
117 StgToDo(..),
118 getStgToDo,
119
120 -- * Compiler configuration suitable for display to the user
121 compilerInfo,
122
123 #ifdef GHCI
124 rtsIsProfiled,
125 #endif
126 dynamicGhc,
127
128 #include "../includes/dist-derivedconstants/header/GHCConstantsHaskellExports.hs"
129 bLOCK_SIZE_W,
130 wORD_SIZE_IN_BITS,
131 tAG_MASK,
132 mAX_PTR_TAG,
133 tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD,
134
135 unsafeGlobalDynFlags, setUnsafeGlobalDynFlags,
136
137 -- * SSE and AVX
138 isSseEnabled,
139 isSse2Enabled,
140 isSse4_2Enabled,
141 isAvxEnabled,
142 isAvx2Enabled,
143 isAvx512cdEnabled,
144 isAvx512erEnabled,
145 isAvx512fEnabled,
146 isAvx512pfEnabled,
147
148 -- * Linker/compiler information
149 LinkerInfo(..),
150 CompilerInfo(..),
151 ) where
152
153 #include "HsVersions.h"
154
155 import Platform
156 import PlatformConstants
157 import Module
158 import PackageConfig
159 import {-# SOURCE #-} Hooks
160 import {-# SOURCE #-} PrelNames ( mAIN )
161 import {-# SOURCE #-} Packages (PackageState, emptyPackageState)
162 import DriverPhases ( Phase(..), phaseInputExt )
163 import Config
164 import CmdLineParser
165 import Constants
166 import Panic
167 import Util
168 import Maybes
169 import MonadUtils
170 import qualified Pretty
171 import SrcLoc
172 import BasicTypes ( IntWithInf, treatZeroAsInf )
173 import FastString
174 import Outputable
175 #ifdef GHCI
176 import Foreign.C ( CInt(..) )
177 import System.IO.Unsafe ( unsafeDupablePerformIO )
178 #endif
179 import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessage )
180
181 import System.IO.Unsafe ( unsafePerformIO )
182 import Data.IORef
183 import Control.Arrow ((&&&))
184 import Control.Monad
185 import Control.Exception (throwIO)
186
187 import Data.Bits
188 import Data.Char
189 import Data.Int
190 import Data.List
191 import Data.Map (Map)
192 import qualified Data.Map as Map
193 import Data.Set (Set)
194 import qualified Data.Set as Set
195 import Data.Word
196 import System.FilePath
197 import System.Directory
198 import System.Environment (getEnv)
199 import System.IO
200 import System.IO.Error
201 import Text.ParserCombinators.ReadP hiding (char)
202 import Text.ParserCombinators.ReadP as R
203
204 import Data.IntSet (IntSet)
205 import qualified Data.IntSet as IntSet
206
207 import GHC.Foreign (withCString, peekCString)
208
209 -- Note [Updating flag description in the User's Guide]
210 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
211 --
212 -- If you modify anything in this file please make sure that your changes are
213 -- described in the User's Guide. Usually at least two sections need to be
214 -- updated:
215 --
216 -- * Flag Reference section in docs/users-guide/flags.xml lists all available
217 -- flags together with a short description
218 --
219 -- * Flag description in docs/users_guide/using.xml provides a detailed
220 -- explanation of flags' usage.
221
222 -- Note [Supporting CLI completion]
223 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
224 --
225 -- The command line interface completion (in for example bash) is an easy way
226 -- for the developer to learn what flags are available from GHC.
227 -- GHC helps by separating which flags are available when compiling with GHC,
228 -- and which flags are available when using GHCi.
229 -- A flag is assumed to either work in both these modes, or only in one of them.
230 -- When adding or changing a flag, please consider for which mode the flag will
231 -- have effect, and annotate it accordingly. For Flags use defFlag, defGhcFlag,
232 -- defGhciFlag, and for FlagSpec use flagSpec or flagGhciSpec.
233
234 -- -----------------------------------------------------------------------------
235 -- DynFlags
236
237 data DumpFlag
238 -- See Note [Updating flag description in the User's Guide]
239
240 -- debugging flags
241 = Opt_D_dump_cmm
242 | Opt_D_dump_cmm_raw
243 -- All of the cmm subflags (there are a lot!) Automatically
244 -- enabled if you run -ddump-cmm
245 | Opt_D_dump_cmm_cfg
246 | Opt_D_dump_cmm_cbe
247 | Opt_D_dump_cmm_switch
248 | Opt_D_dump_cmm_proc
249 | Opt_D_dump_cmm_sink
250 | Opt_D_dump_cmm_sp
251 | Opt_D_dump_cmm_procmap
252 | Opt_D_dump_cmm_split
253 | Opt_D_dump_cmm_info
254 | Opt_D_dump_cmm_cps
255 -- end cmm subflags
256 | Opt_D_dump_asm
257 | Opt_D_dump_asm_native
258 | Opt_D_dump_asm_liveness
259 | Opt_D_dump_asm_regalloc
260 | Opt_D_dump_asm_regalloc_stages
261 | Opt_D_dump_asm_conflicts
262 | Opt_D_dump_asm_stats
263 | Opt_D_dump_asm_expanded
264 | Opt_D_dump_llvm
265 | Opt_D_dump_core_stats
266 | Opt_D_dump_deriv
267 | Opt_D_dump_ds
268 | Opt_D_dump_foreign
269 | Opt_D_dump_inlinings
270 | Opt_D_dump_rule_firings
271 | Opt_D_dump_rule_rewrites
272 | Opt_D_dump_simpl_trace
273 | Opt_D_dump_occur_anal
274 | Opt_D_dump_parsed
275 | Opt_D_dump_rn
276 | Opt_D_dump_simpl
277 | Opt_D_dump_simpl_iterations
278 | Opt_D_dump_spec
279 | Opt_D_dump_prep
280 | Opt_D_dump_stg
281 | Opt_D_dump_call_arity
282 | Opt_D_dump_stranal
283 | Opt_D_dump_strsigs
284 | Opt_D_dump_tc
285 | Opt_D_dump_types
286 | Opt_D_dump_rules
287 | Opt_D_dump_cse
288 | Opt_D_dump_worker_wrapper
289 | Opt_D_dump_rn_trace
290 | Opt_D_dump_rn_stats
291 | Opt_D_dump_opt_cmm
292 | Opt_D_dump_simpl_stats
293 | Opt_D_dump_cs_trace -- Constraint solver in type checker
294 | Opt_D_dump_tc_trace
295 | Opt_D_dump_if_trace
296 | Opt_D_dump_vt_trace
297 | Opt_D_dump_splices
298 | Opt_D_th_dec_file
299 | Opt_D_dump_BCOs
300 | Opt_D_dump_vect
301 | Opt_D_dump_ticked
302 | Opt_D_dump_rtti
303 | Opt_D_source_stats
304 | Opt_D_verbose_stg2stg
305 | Opt_D_dump_hi
306 | Opt_D_dump_hi_diffs
307 | Opt_D_dump_mod_cycles
308 | Opt_D_dump_mod_map
309 | Opt_D_dump_view_pattern_commoning
310 | Opt_D_verbose_core2core
311 | Opt_D_dump_debug
312
313 deriving (Eq, Show, Enum)
314
315 -- | Enumerates the simple on-or-off dynamic flags
316 data GeneralFlag
317 -- See Note [Updating flag description in the User's Guide]
318
319 = Opt_DumpToFile -- ^ Append dump output to files instead of stdout.
320 | Opt_D_faststring_stats
321 | Opt_D_dump_minimal_imports
322 | Opt_DoCoreLinting
323 | Opt_DoStgLinting
324 | Opt_DoCmmLinting
325 | Opt_DoAsmLinting
326 | Opt_DoAnnotationLinting
327 | Opt_NoLlvmMangler -- hidden flag
328
329 | Opt_WarnIsError -- -Werror; makes warnings fatal
330
331 | Opt_PrintExplicitForalls
332 | Opt_PrintExplicitKinds
333 | Opt_PrintUnicodeSyntax
334
335 -- optimisation opts
336 | Opt_CallArity
337 | Opt_Strictness
338 | Opt_LateDmdAnal
339 | Opt_KillAbsence
340 | Opt_KillOneShot
341 | Opt_FullLaziness
342 | Opt_FloatIn
343 | Opt_Specialise
344 | Opt_SpecialiseAggressively
345 | Opt_CrossModuleSpecialise
346 | Opt_StaticArgumentTransformation
347 | Opt_CSE
348 | Opt_LiberateCase
349 | Opt_SpecConstr
350 | Opt_DoLambdaEtaExpansion
351 | Opt_IgnoreAsserts
352 | Opt_DoEtaReduction
353 | Opt_CaseMerge
354 | Opt_UnboxStrictFields
355 | Opt_UnboxSmallStrictFields
356 | Opt_DictsCheap
357 | Opt_EnableRewriteRules -- Apply rewrite rules during simplification
358 | Opt_Vectorise
359 | Opt_VectorisationAvoidance
360 | Opt_RegsGraph -- do graph coloring register allocation
361 | Opt_RegsIterative -- do iterative coalescing graph coloring register allocation
362 | Opt_PedanticBottoms -- Be picky about how we treat bottom
363 | Opt_LlvmTBAA -- Use LLVM TBAA infastructure for improving AA (hidden flag)
364 | Opt_LlvmPassVectorsInRegisters -- Pass SIMD vectors in registers (requires a patched LLVM) (hidden flag)
365 | Opt_IrrefutableTuples
366 | Opt_CmmSink
367 | Opt_CmmElimCommonBlocks
368 | Opt_OmitYields
369 | Opt_SimpleListLiterals
370 | Opt_FunToThunk -- allow WwLib.mkWorkerArgs to remove all value lambdas
371 | Opt_DictsStrict -- be strict in argument dictionaries
372 | Opt_DmdTxDictSel -- use a special demand transformer for dictionary selectors
373 | Opt_Loopification -- See Note [Self-recursive tail calls]
374
375 -- Interface files
376 | Opt_IgnoreInterfacePragmas
377 | Opt_OmitInterfacePragmas
378 | Opt_ExposeAllUnfoldings
379 | Opt_WriteInterface -- forces .hi files to be written even with -fno-code
380
381 -- profiling opts
382 | Opt_AutoSccsOnIndividualCafs
383 | Opt_ProfCountEntries
384
385 -- misc opts
386 | Opt_Pp
387 | Opt_ForceRecomp
388 | Opt_ExcessPrecision
389 | Opt_EagerBlackHoling
390 | Opt_NoHsMain
391 | Opt_SplitObjs
392 | Opt_StgStats
393 | Opt_HideAllPackages
394 | Opt_PrintBindResult
395 | Opt_Haddock
396 | Opt_HaddockOptions
397 | Opt_BreakOnException
398 | Opt_BreakOnError
399 | Opt_PrintEvldWithShow
400 | Opt_PrintBindContents
401 | Opt_GenManifest
402 | Opt_EmbedManifest
403 | Opt_SharedImplib
404 | Opt_BuildingCabalPackage
405 | Opt_IgnoreDotGhci
406 | Opt_GhciSandbox
407 | Opt_GhciHistory
408 | Opt_HelpfulErrors
409 | Opt_DeferTypeErrors
410 | Opt_DeferTypedHoles
411 | Opt_Parallel
412 | Opt_PIC
413 | Opt_SccProfilingOn
414 | Opt_Ticky
415 | Opt_Ticky_Allocd
416 | Opt_Ticky_LNE
417 | Opt_Ticky_Dyn_Thunk
418 | Opt_Static
419 | Opt_RPath
420 | Opt_RelativeDynlibPaths
421 | Opt_Hpc
422 | Opt_FlatCache
423
424 -- PreInlining is on by default. The option is there just to see how
425 -- bad things get if you turn it off!
426 | Opt_SimplPreInlining
427
428 -- output style opts
429 | Opt_ErrorSpans -- Include full span info in error messages,
430 -- instead of just the start position.
431 | Opt_PprCaseAsLet
432 | Opt_PprShowTicks
433
434 -- Suppress all coercions, them replacing with '...'
435 | Opt_SuppressCoercions
436 | Opt_SuppressVarKinds
437 -- Suppress module id prefixes on variables.
438 | Opt_SuppressModulePrefixes
439 -- Suppress type applications.
440 | Opt_SuppressTypeApplications
441 -- Suppress info such as arity and unfoldings on identifiers.
442 | Opt_SuppressIdInfo
443 -- Suppress separate type signatures in core, but leave types on
444 -- lambda bound vars
445 | Opt_SuppressTypeSignatures
446 -- Suppress unique ids on variables.
447 -- Except for uniques, as some simplifier phases introduce new
448 -- variables that have otherwise identical names.
449 | Opt_SuppressUniques
450
451 -- temporary flags
452 | Opt_AutoLinkPackages
453 | Opt_ImplicitImportQualified
454
455 -- keeping stuff
456 | Opt_KeepHiDiffs
457 | Opt_KeepHcFiles
458 | Opt_KeepSFiles
459 | Opt_KeepTmpFiles
460 | Opt_KeepRawTokenStream
461 | Opt_KeepLlvmFiles
462
463 | Opt_BuildDynamicToo
464
465 -- safe haskell flags
466 | Opt_DistrustAllPackages
467 | Opt_PackageTrust
468
469 -- debugging flags
470 | Opt_Debug
471
472 deriving (Eq, Show, Enum)
473
474 data WarningFlag =
475 -- See Note [Updating flag description in the User's Guide]
476 Opt_WarnDuplicateExports
477 | Opt_WarnDuplicateConstraints
478 | Opt_WarnRedundantConstraints
479 | Opt_WarnHiShadows
480 | Opt_WarnImplicitPrelude
481 | Opt_WarnIncompletePatterns
482 | Opt_WarnIncompleteUniPatterns
483 | Opt_WarnIncompletePatternsRecUpd
484 | Opt_WarnOverflowedLiterals
485 | Opt_WarnEmptyEnumerations
486 | Opt_WarnMissingFields
487 | Opt_WarnMissingImportList
488 | Opt_WarnMissingMethods
489 | Opt_WarnMissingSigs
490 | Opt_WarnMissingLocalSigs
491 | Opt_WarnNameShadowing
492 | Opt_WarnOverlappingPatterns
493 | Opt_WarnTypeDefaults
494 | Opt_WarnMonomorphism
495 | Opt_WarnUnusedTopBinds
496 | Opt_WarnUnusedLocalBinds
497 | Opt_WarnUnusedPatternBinds
498 | Opt_WarnUnusedImports
499 | Opt_WarnUnusedMatches
500 | Opt_WarnContextQuantification
501 | Opt_WarnWarningsDeprecations
502 | Opt_WarnDeprecatedFlags
503 | Opt_WarnAMP
504 | Opt_WarnDodgyExports
505 | Opt_WarnDodgyImports
506 | Opt_WarnOrphans
507 | Opt_WarnAutoOrphans
508 | Opt_WarnIdentities
509 | Opt_WarnTabs
510 | Opt_WarnUnrecognisedPragmas
511 | Opt_WarnDodgyForeignImports
512 | Opt_WarnUnusedDoBind
513 | Opt_WarnWrongDoBind
514 | Opt_WarnAlternativeLayoutRuleTransitional
515 | Opt_WarnUnsafe
516 | Opt_WarnSafe
517 | Opt_WarnTrustworthySafe
518 | Opt_WarnPointlessPragmas
519 | Opt_WarnUnsupportedCallingConventions
520 | Opt_WarnUnsupportedLlvmVersion
521 | Opt_WarnInlineRuleShadowing
522 | Opt_WarnTypedHoles
523 | Opt_WarnPartialTypeSignatures
524 | Opt_WarnMissingExportedSigs
525 | Opt_WarnUntickedPromotedConstructors
526 | Opt_WarnDerivingTypeable
527 deriving (Eq, Show, Enum)
528
529 data Language = Haskell98 | Haskell2010
530 deriving Enum
531
532 -- | The various Safe Haskell modes
533 data SafeHaskellMode
534 = Sf_None
535 | Sf_Unsafe
536 | Sf_Trustworthy
537 | Sf_Safe
538 deriving (Eq)
539
540 instance Show SafeHaskellMode where
541 show Sf_None = "None"
542 show Sf_Unsafe = "Unsafe"
543 show Sf_Trustworthy = "Trustworthy"
544 show Sf_Safe = "Safe"
545
546 instance Outputable SafeHaskellMode where
547 ppr = text . show
548
549 data ExtensionFlag
550 -- See Note [Updating flag description in the User's Guide]
551 = Opt_Cpp
552 | Opt_OverlappingInstances
553 | Opt_UndecidableInstances
554 | Opt_IncoherentInstances
555 | Opt_MonomorphismRestriction
556 | Opt_MonoPatBinds
557 | Opt_MonoLocalBinds
558 | Opt_RelaxedPolyRec -- Deprecated
559 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
560 | Opt_ForeignFunctionInterface
561 | Opt_UnliftedFFITypes
562 | Opt_InterruptibleFFI
563 | Opt_CApiFFI
564 | Opt_GHCForeignImportPrim
565 | Opt_JavaScriptFFI
566 | Opt_ParallelArrays -- Syntactic support for parallel arrays
567 | Opt_Arrows -- Arrow-notation syntax
568 | Opt_TemplateHaskell
569 | Opt_QuasiQuotes
570 | Opt_ImplicitParams
571 | Opt_ImplicitPrelude
572 | Opt_ScopedTypeVariables
573 | Opt_AllowAmbiguousTypes
574 | Opt_UnboxedTuples
575 | Opt_BangPatterns
576 | Opt_TypeFamilies
577 | Opt_OverloadedStrings
578 | Opt_OverloadedLists
579 | Opt_NumDecimals
580 | Opt_DisambiguateRecordFields
581 | Opt_RecordWildCards
582 | Opt_RecordPuns
583 | Opt_ViewPatterns
584 | Opt_GADTs
585 | Opt_GADTSyntax
586 | Opt_NPlusKPatterns
587 | Opt_DoAndIfThenElse
588 | Opt_RebindableSyntax
589 | Opt_ConstraintKinds
590 | Opt_PolyKinds -- Kind polymorphism
591 | Opt_DataKinds -- Datatype promotion
592 | Opt_InstanceSigs
593
594 | Opt_StandaloneDeriving
595 | Opt_DeriveDataTypeable
596 | Opt_AutoDeriveTypeable -- Automatic derivation of Typeable
597 | Opt_DeriveFunctor
598 | Opt_DeriveTraversable
599 | Opt_DeriveFoldable
600 | Opt_DeriveGeneric -- Allow deriving Generic/1
601 | Opt_DefaultSignatures -- Allow extra signatures for defmeths
602 | Opt_DeriveAnyClass -- Allow deriving any class
603
604 | Opt_TypeSynonymInstances
605 | Opt_FlexibleContexts
606 | Opt_FlexibleInstances
607 | Opt_ConstrainedClassMethods
608 | Opt_MultiParamTypeClasses
609 | Opt_NullaryTypeClasses
610 | Opt_FunctionalDependencies
611 | Opt_UnicodeSyntax
612 | Opt_ExistentialQuantification
613 | Opt_MagicHash
614 | Opt_EmptyDataDecls
615 | Opt_KindSignatures
616 | Opt_RoleAnnotations
617 | Opt_ParallelListComp
618 | Opt_TransformListComp
619 | Opt_MonadComprehensions
620 | Opt_GeneralizedNewtypeDeriving
621 | Opt_RecursiveDo
622 | Opt_PostfixOperators
623 | Opt_TupleSections
624 | Opt_PatternGuards
625 | Opt_LiberalTypeSynonyms
626 | Opt_RankNTypes
627 | Opt_ImpredicativeTypes
628 | Opt_TypeOperators
629 | Opt_ExplicitNamespaces
630 | Opt_PackageImports
631 | Opt_ExplicitForAll
632 | Opt_AlternativeLayoutRule
633 | Opt_AlternativeLayoutRuleTransitional
634 | Opt_DatatypeContexts
635 | Opt_NondecreasingIndentation
636 | Opt_RelaxedLayout
637 | Opt_TraditionalRecordSyntax
638 | Opt_LambdaCase
639 | Opt_MultiWayIf
640 | Opt_BinaryLiterals
641 | Opt_NegativeLiterals
642 | Opt_EmptyCase
643 | Opt_PatternSynonyms
644 | Opt_PartialTypeSignatures
645 | Opt_NamedWildCards
646 | Opt_StaticPointers
647 deriving (Eq, Enum, Show)
648
649 type SigOf = Map ModuleName Module
650
651 getSigOf :: DynFlags -> ModuleName -> Maybe Module
652 getSigOf dflags n = Map.lookup n (sigOf dflags)
653
654 -- | Contains not only a collection of 'GeneralFlag's but also a plethora of
655 -- information relating to the compilation of a single file or GHC session
656 data DynFlags = DynFlags {
657 ghcMode :: GhcMode,
658 ghcLink :: GhcLink,
659 hscTarget :: HscTarget,
660 settings :: Settings,
661 -- See Note [Signature parameters in TcGblEnv and DynFlags]
662 sigOf :: SigOf, -- ^ Compiling an hs-boot against impl.
663 verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels]
664 optLevel :: Int, -- ^ Optimisation level
665 simplPhases :: Int, -- ^ Number of simplifier phases
666 maxSimplIterations :: Int, -- ^ Max simplifier iterations
667 ruleCheck :: Maybe String,
668 strictnessBefore :: [Int], -- ^ Additional demand analysis
669
670 parMakeCount :: Maybe Int, -- ^ The number of modules to compile in parallel
671 -- in --make mode, where Nothing ==> compile as
672 -- many in parallel as there are CPUs.
673
674 enableTimeStats :: Bool, -- ^ Enable RTS timing statistics?
675 ghcHeapSize :: Maybe Int, -- ^ The heap size to set.
676
677 maxRelevantBinds :: Maybe Int, -- ^ Maximum number of bindings from the type envt
678 -- to show in type error messages
679 simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks
680 specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr
681 specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function
682 specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types
683 -- Not optional; otherwise ForceSpecConstr can diverge.
684 liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase
685 floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating
686 -- See CoreMonad.FloatOutSwitches
687
688 historySize :: Int,
689
690 cmdlineHcIncludes :: [String], -- ^ @\-\#includes@
691 importPaths :: [FilePath],
692 mainModIs :: Module,
693 mainFunIs :: Maybe String,
694 reductionDepth :: IntWithInf, -- ^ Typechecker maximum stack depth
695 solverIterations :: IntWithInf, -- ^ Number of iterations in the constraints solver
696 -- Typically only 1 is needed
697
698 thisPackage :: PackageKey, -- ^ name of package currently being compiled
699
700 -- ways
701 ways :: [Way], -- ^ Way flags from the command line
702 buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof)
703 rtsBuildTag :: String, -- ^ The RTS \"way\"
704
705 -- For object splitting
706 splitInfo :: Maybe (String,Int),
707
708 -- paths etc.
709 objectDir :: Maybe String,
710 dylibInstallName :: Maybe String,
711 hiDir :: Maybe String,
712 stubDir :: Maybe String,
713 dumpDir :: Maybe String,
714
715 objectSuf :: String,
716 hcSuf :: String,
717 hiSuf :: String,
718
719 canGenerateDynamicToo :: IORef Bool,
720 dynObjectSuf :: String,
721 dynHiSuf :: String,
722
723 -- Packages.isDllName needs to know whether a call is within a
724 -- single DLL or not. Normally it does this by seeing if the call
725 -- is to the same package, but for the ghc package, we split the
726 -- package between 2 DLLs. The dllSplit tells us which sets of
727 -- modules are in which package.
728 dllSplitFile :: Maybe FilePath,
729 dllSplit :: Maybe [Set String],
730
731 outputFile :: Maybe String,
732 dynOutputFile :: Maybe String,
733 outputHi :: Maybe String,
734 dynLibLoader :: DynLibLoader,
735
736 -- | This is set by 'DriverPipeline.runPipeline' based on where
737 -- its output is going.
738 dumpPrefix :: Maybe FilePath,
739
740 -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
741 -- Set by @-ddump-file-prefix@
742 dumpPrefixForce :: Maybe FilePath,
743
744 ldInputs :: [Option],
745
746 includePaths :: [String],
747 libraryPaths :: [String],
748 frameworkPaths :: [String], -- used on darwin only
749 cmdlineFrameworks :: [String], -- ditto
750
751 rtsOpts :: Maybe String,
752 rtsOptsEnabled :: RtsOptsEnabled,
753 rtsOptsSuggestions :: Bool,
754
755 hpcDir :: String, -- ^ Path to store the .mix files
756
757 -- Plugins
758 pluginModNames :: [ModuleName],
759 pluginModNameOpts :: [(ModuleName,String)],
760
761 -- GHC API hooks
762 hooks :: Hooks,
763
764 -- For ghc -M
765 depMakefile :: FilePath,
766 depIncludePkgDeps :: Bool,
767 depExcludeMods :: [ModuleName],
768 depSuffixes :: [String],
769
770 -- Package flags
771 extraPkgConfs :: [PkgConfRef] -> [PkgConfRef],
772 -- ^ The @-package-db@ flags given on the command line, in the order
773 -- they appeared.
774
775 packageFlags :: [PackageFlag],
776 -- ^ The @-package@ and @-hide-package@ flags from the command-line
777 packageEnv :: Maybe FilePath,
778 -- ^ Filepath to the package environment file (if overriding default)
779
780 -- Package state
781 -- NB. do not modify this field, it is calculated by
782 -- Packages.initPackages
783 pkgDatabase :: Maybe [PackageConfig],
784 pkgState :: PackageState,
785
786 -- Temporary files
787 -- These have to be IORefs, because the defaultCleanupHandler needs to
788 -- know what to clean when an exception happens
789 filesToClean :: IORef [FilePath],
790 dirsToClean :: IORef (Map FilePath FilePath),
791 filesToNotIntermediateClean :: IORef [FilePath],
792 -- The next available suffix to uniquely name a temp file, updated atomically
793 nextTempSuffix :: IORef Int,
794
795 -- Names of files which were generated from -ddump-to-file; used to
796 -- track which ones we need to truncate because it's our first run
797 -- through
798 generatedDumps :: IORef (Set FilePath),
799
800 -- hsc dynamic flags
801 dumpFlags :: IntSet,
802 generalFlags :: IntSet,
803 warningFlags :: IntSet,
804 -- Don't change this without updating extensionFlags:
805 language :: Maybe Language,
806 -- | Safe Haskell mode
807 safeHaskell :: SafeHaskellMode,
808 safeInfer :: Bool,
809 safeInferred :: Bool,
810 -- We store the location of where some extension and flags were turned on so
811 -- we can produce accurate error messages when Safe Haskell fails due to
812 -- them.
813 thOnLoc :: SrcSpan,
814 newDerivOnLoc :: SrcSpan,
815 overlapInstLoc :: SrcSpan,
816 incoherentOnLoc :: SrcSpan,
817 pkgTrustOnLoc :: SrcSpan,
818 warnSafeOnLoc :: SrcSpan,
819 warnUnsafeOnLoc :: SrcSpan,
820 trustworthyOnLoc :: SrcSpan,
821 -- Don't change this without updating extensionFlags:
822 extensions :: [OnOff ExtensionFlag],
823 -- extensionFlags should always be equal to
824 -- flattenExtensionFlags language extensions
825 extensionFlags :: IntSet,
826
827 -- Unfolding control
828 -- See Note [Discounts and thresholds] in CoreUnfold
829 ufCreationThreshold :: Int,
830 ufUseThreshold :: Int,
831 ufFunAppDiscount :: Int,
832 ufDictDiscount :: Int,
833 ufKeenessFactor :: Float,
834 ufDearOp :: Int,
835
836 maxWorkerArgs :: Int,
837
838 ghciHistSize :: Int,
839
840 -- | MsgDoc output action: use "ErrUtils" instead of this if you can
841 log_action :: LogAction,
842 flushOut :: FlushOut,
843 flushErr :: FlushErr,
844
845 haddockOptions :: Maybe String,
846
847 -- | GHCi scripts specified by -ghci-script, in reverse order
848 ghciScripts :: [String],
849
850 -- Output style options
851 pprUserLength :: Int,
852 pprCols :: Int,
853 traceLevel :: Int, -- Standard level is 1. Less verbose is 0.
854
855 useUnicode :: Bool,
856
857 -- | what kind of {-# SCC #-} to add automatically
858 profAuto :: ProfAuto,
859
860 interactivePrint :: Maybe String,
861
862 llvmVersion :: IORef Int,
863
864 nextWrapperNum :: IORef (ModuleEnv Int),
865
866 -- | Machine dependant flags (-m<blah> stuff)
867 sseVersion :: Maybe SseVersion,
868 avx :: Bool,
869 avx2 :: Bool,
870 avx512cd :: Bool, -- Enable AVX-512 Conflict Detection Instructions.
871 avx512er :: Bool, -- Enable AVX-512 Exponential and Reciprocal Instructions.
872 avx512f :: Bool, -- Enable AVX-512 instructions.
873 avx512pf :: Bool, -- Enable AVX-512 PreFetch Instructions.
874
875 -- | Run-time linker information (what options we need, etc.)
876 rtldInfo :: IORef (Maybe LinkerInfo),
877
878 -- | Run-time compiler information
879 rtccInfo :: IORef (Maybe CompilerInfo),
880
881 -- Constants used to control the amount of optimization done.
882
883 -- | Max size, in bytes, of inline array allocations.
884 maxInlineAllocSize :: Int,
885
886 -- | Only inline memcpy if it generates no more than this many
887 -- pseudo (roughly: Cmm) instructions.
888 maxInlineMemcpyInsns :: Int,
889
890 -- | Only inline memset if it generates no more than this many
891 -- pseudo (roughly: Cmm) instructions.
892 maxInlineMemsetInsns :: Int
893 }
894
895 class HasDynFlags m where
896 getDynFlags :: m DynFlags
897
898 class ContainsDynFlags t where
899 extractDynFlags :: t -> DynFlags
900 replaceDynFlags :: t -> DynFlags -> t
901
902 data ProfAuto
903 = NoProfAuto -- ^ no SCC annotations added
904 | ProfAutoAll -- ^ top-level and nested functions are annotated
905 | ProfAutoTop -- ^ top-level functions annotated only
906 | ProfAutoExports -- ^ exported functions annotated only
907 | ProfAutoCalls -- ^ annotate call-sites
908 deriving (Eq,Enum)
909
910 data Settings = Settings {
911 sTargetPlatform :: Platform, -- Filled in by SysTools
912 sGhcUsagePath :: FilePath, -- Filled in by SysTools
913 sGhciUsagePath :: FilePath, -- ditto
914 sTopDir :: FilePath,
915 sTmpDir :: String, -- no trailing '/'
916 sProgramName :: String,
917 sProjectVersion :: String,
918 -- You shouldn't need to look things up in rawSettings directly.
919 -- They should have their own fields instead.
920 sRawSettings :: [(String, String)],
921 sExtraGccViaCFlags :: [String],
922 sSystemPackageConfig :: FilePath,
923 sLdSupportsCompactUnwind :: Bool,
924 sLdSupportsBuildId :: Bool,
925 sLdSupportsFilelist :: Bool,
926 sLdIsGnuLd :: Bool,
927 -- commands for particular phases
928 sPgm_L :: String,
929 sPgm_P :: (String,[Option]),
930 sPgm_F :: String,
931 sPgm_c :: (String,[Option]),
932 sPgm_s :: (String,[Option]),
933 sPgm_a :: (String,[Option]),
934 sPgm_l :: (String,[Option]),
935 sPgm_dll :: (String,[Option]),
936 sPgm_T :: String,
937 sPgm_sysman :: String,
938 sPgm_windres :: String,
939 sPgm_libtool :: String,
940 sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser
941 sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler
942 -- options for particular phases
943 sOpt_L :: [String],
944 sOpt_P :: [String],
945 sOpt_F :: [String],
946 sOpt_c :: [String],
947 sOpt_a :: [String],
948 sOpt_l :: [String],
949 sOpt_windres :: [String],
950 sOpt_lo :: [String], -- LLVM: llvm optimiser
951 sOpt_lc :: [String], -- LLVM: llc static compiler
952
953 sPlatformConstants :: PlatformConstants
954 }
955
956 targetPlatform :: DynFlags -> Platform
957 targetPlatform dflags = sTargetPlatform (settings dflags)
958 programName :: DynFlags -> String
959 programName dflags = sProgramName (settings dflags)
960 projectVersion :: DynFlags -> String
961 projectVersion dflags = sProjectVersion (settings dflags)
962 ghcUsagePath :: DynFlags -> FilePath
963 ghcUsagePath dflags = sGhcUsagePath (settings dflags)
964 ghciUsagePath :: DynFlags -> FilePath
965 ghciUsagePath dflags = sGhciUsagePath (settings dflags)
966 topDir :: DynFlags -> FilePath
967 topDir dflags = sTopDir (settings dflags)
968 tmpDir :: DynFlags -> String
969 tmpDir dflags = sTmpDir (settings dflags)
970 rawSettings :: DynFlags -> [(String, String)]
971 rawSettings dflags = sRawSettings (settings dflags)
972 extraGccViaCFlags :: DynFlags -> [String]
973 extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags)
974 systemPackageConfig :: DynFlags -> FilePath
975 systemPackageConfig dflags = sSystemPackageConfig (settings dflags)
976 pgm_L :: DynFlags -> String
977 pgm_L dflags = sPgm_L (settings dflags)
978 pgm_P :: DynFlags -> (String,[Option])
979 pgm_P dflags = sPgm_P (settings dflags)
980 pgm_F :: DynFlags -> String
981 pgm_F dflags = sPgm_F (settings dflags)
982 pgm_c :: DynFlags -> (String,[Option])
983 pgm_c dflags = sPgm_c (settings dflags)
984 pgm_s :: DynFlags -> (String,[Option])
985 pgm_s dflags = sPgm_s (settings dflags)
986 pgm_a :: DynFlags -> (String,[Option])
987 pgm_a dflags = sPgm_a (settings dflags)
988 pgm_l :: DynFlags -> (String,[Option])
989 pgm_l dflags = sPgm_l (settings dflags)
990 pgm_dll :: DynFlags -> (String,[Option])
991 pgm_dll dflags = sPgm_dll (settings dflags)
992 pgm_T :: DynFlags -> String
993 pgm_T dflags = sPgm_T (settings dflags)
994 pgm_sysman :: DynFlags -> String
995 pgm_sysman dflags = sPgm_sysman (settings dflags)
996 pgm_windres :: DynFlags -> String
997 pgm_windres dflags = sPgm_windres (settings dflags)
998 pgm_libtool :: DynFlags -> String
999 pgm_libtool dflags = sPgm_libtool (settings dflags)
1000 pgm_lo :: DynFlags -> (String,[Option])
1001 pgm_lo dflags = sPgm_lo (settings dflags)
1002 pgm_lc :: DynFlags -> (String,[Option])
1003 pgm_lc dflags = sPgm_lc (settings dflags)
1004 opt_L :: DynFlags -> [String]
1005 opt_L dflags = sOpt_L (settings dflags)
1006 opt_P :: DynFlags -> [String]
1007 opt_P dflags = concatMap (wayOptP (targetPlatform dflags)) (ways dflags)
1008 ++ sOpt_P (settings dflags)
1009 opt_F :: DynFlags -> [String]
1010 opt_F dflags = sOpt_F (settings dflags)
1011 opt_c :: DynFlags -> [String]
1012 opt_c dflags = concatMap (wayOptc (targetPlatform dflags)) (ways dflags)
1013 ++ sOpt_c (settings dflags)
1014 opt_a :: DynFlags -> [String]
1015 opt_a dflags = sOpt_a (settings dflags)
1016 opt_l :: DynFlags -> [String]
1017 opt_l dflags = concatMap (wayOptl (targetPlatform dflags)) (ways dflags)
1018 ++ sOpt_l (settings dflags)
1019 opt_windres :: DynFlags -> [String]
1020 opt_windres dflags = sOpt_windres (settings dflags)
1021 opt_lo :: DynFlags -> [String]
1022 opt_lo dflags = sOpt_lo (settings dflags)
1023 opt_lc :: DynFlags -> [String]
1024 opt_lc dflags = sOpt_lc (settings dflags)
1025
1026 -- | The directory for this version of ghc in the user's app directory
1027 -- (typically something like @~/.ghc/x86_64-linux-7.6.3@)
1028 --
1029 versionedAppDir :: DynFlags -> IO FilePath
1030 versionedAppDir dflags = do
1031 appdir <- getAppUserDataDirectory (programName dflags)
1032 return $ appdir </> (TARGET_ARCH ++ '-':TARGET_OS ++ '-':projectVersion dflags)
1033
1034 -- | The target code type of the compilation (if any).
1035 --
1036 -- Whenever you change the target, also make sure to set 'ghcLink' to
1037 -- something sensible.
1038 --
1039 -- 'HscNothing' can be used to avoid generating any output, however, note
1040 -- that:
1041 --
1042 -- * If a program uses Template Haskell the typechecker may try to run code
1043 -- from an imported module. This will fail if no code has been generated
1044 -- for this module. You can use 'GHC.needsTemplateHaskell' to detect
1045 -- whether this might be the case and choose to either switch to a
1046 -- different target or avoid typechecking such modules. (The latter may be
1047 -- preferable for security reasons.)
1048 --
1049 data HscTarget
1050 = HscC -- ^ Generate C code.
1051 | HscAsm -- ^ Generate assembly using the native code generator.
1052 | HscLlvm -- ^ Generate assembly using the llvm code generator.
1053 | HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory')
1054 | HscNothing -- ^ Don't generate any code. See notes above.
1055 deriving (Eq, Show)
1056
1057 -- | Will this target result in an object file on the disk?
1058 isObjectTarget :: HscTarget -> Bool
1059 isObjectTarget HscC = True
1060 isObjectTarget HscAsm = True
1061 isObjectTarget HscLlvm = True
1062 isObjectTarget _ = False
1063
1064 -- | Does this target retain *all* top-level bindings for a module,
1065 -- rather than just the exported bindings, in the TypeEnv and compiled
1066 -- code (if any)? In interpreted mode we do this, so that GHCi can
1067 -- call functions inside a module. In HscNothing mode we also do it,
1068 -- so that Haddock can get access to the GlobalRdrEnv for a module
1069 -- after typechecking it.
1070 targetRetainsAllBindings :: HscTarget -> Bool
1071 targetRetainsAllBindings HscInterpreted = True
1072 targetRetainsAllBindings HscNothing = True
1073 targetRetainsAllBindings _ = False
1074
1075 -- | The 'GhcMode' tells us whether we're doing multi-module
1076 -- compilation (controlled via the "GHC" API) or one-shot
1077 -- (single-module) compilation. This makes a difference primarily to
1078 -- the "Finder": in one-shot mode we look for interface files for
1079 -- imported modules, but in multi-module mode we look for source files
1080 -- in order to check whether they need to be recompiled.
1081 data GhcMode
1082 = CompManager -- ^ @\-\-make@, GHCi, etc.
1083 | OneShot -- ^ @ghc -c Foo.hs@
1084 | MkDepend -- ^ @ghc -M@, see "Finder" for why we need this
1085 deriving Eq
1086
1087 instance Outputable GhcMode where
1088 ppr CompManager = ptext (sLit "CompManager")
1089 ppr OneShot = ptext (sLit "OneShot")
1090 ppr MkDepend = ptext (sLit "MkDepend")
1091
1092 isOneShot :: GhcMode -> Bool
1093 isOneShot OneShot = True
1094 isOneShot _other = False
1095
1096 -- | What to do in the link step, if there is one.
1097 data GhcLink
1098 = NoLink -- ^ Don't link at all
1099 | LinkBinary -- ^ Link object code into a binary
1100 | LinkInMemory -- ^ Use the in-memory dynamic linker (works for both
1101 -- bytecode and object code).
1102 | LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
1103 | LinkStaticLib -- ^ Link objects into a static lib
1104 deriving (Eq, Show)
1105
1106 isNoLink :: GhcLink -> Bool
1107 isNoLink NoLink = True
1108 isNoLink _ = False
1109
1110 -- | We accept flags which make packages visible, but how they select
1111 -- the package varies; this data type reflects what selection criterion
1112 -- is used.
1113 data PackageArg =
1114 PackageArg String -- ^ @-package@, by 'PackageName'
1115 | PackageIdArg String -- ^ @-package-id@, by 'SourcePackageId'
1116 | PackageKeyArg String -- ^ @-package-key@, by 'InstalledPackageId'
1117 deriving (Eq, Show)
1118
1119 -- | Represents the renaming that may be associated with an exposed
1120 -- package, e.g. the @rns@ part of @-package "foo (rns)"@.
1121 --
1122 -- Here are some example parsings of the package flags (where
1123 -- a string literal is punned to be a 'ModuleName':
1124 --
1125 -- * @-package foo@ is @ModRenaming True []@
1126 -- * @-package foo ()@ is @ModRenaming False []@
1127 -- * @-package foo (A)@ is @ModRenaming False [("A", "A")]@
1128 -- * @-package foo (A as B)@ is @ModRenaming False [("A", "B")]@
1129 -- * @-package foo with (A as B)@ is @ModRenaming True [("A", "B")]@
1130 data ModRenaming = ModRenaming {
1131 modRenamingWithImplicit :: Bool, -- ^ Bring all exposed modules into scope?
1132 modRenamings :: [(ModuleName, ModuleName)] -- ^ Bring module @m@ into scope
1133 -- under name @n@.
1134 } deriving (Eq)
1135
1136 -- | Flags for manipulating packages.
1137 data PackageFlag
1138 = ExposePackage PackageArg ModRenaming -- ^ @-package@, @-package-id@
1139 -- and @-package-key@
1140 | HidePackage String -- ^ @-hide-package@
1141 | IgnorePackage String -- ^ @-ignore-package@
1142 | TrustPackage String -- ^ @-trust-package@
1143 | DistrustPackage String -- ^ @-distrust-package@
1144 deriving (Eq)
1145
1146 defaultHscTarget :: Platform -> HscTarget
1147 defaultHscTarget = defaultObjectTarget
1148
1149 -- | The 'HscTarget' value corresponding to the default way to create
1150 -- object files on the current platform.
1151 defaultObjectTarget :: Platform -> HscTarget
1152 defaultObjectTarget platform
1153 | platformUnregisterised platform = HscC
1154 | cGhcWithNativeCodeGen == "YES" = HscAsm
1155 | otherwise = HscLlvm
1156
1157 tablesNextToCode :: DynFlags -> Bool
1158 tablesNextToCode dflags
1159 = mkTablesNextToCode (platformUnregisterised (targetPlatform dflags))
1160
1161 -- Determines whether we will be compiling
1162 -- info tables that reside just before the entry code, or with an
1163 -- indirection to the entry code. See TABLES_NEXT_TO_CODE in
1164 -- includes/rts/storage/InfoTables.h.
1165 mkTablesNextToCode :: Bool -> Bool
1166 mkTablesNextToCode unregisterised
1167 = not unregisterised && cGhcEnableTablesNextToCode == "YES"
1168
1169 data DynLibLoader
1170 = Deployable
1171 | SystemDependent
1172 deriving Eq
1173
1174 data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll
1175 deriving (Show)
1176
1177 -----------------------------------------------------------------------------
1178 -- Ways
1179
1180 -- The central concept of a "way" is that all objects in a given
1181 -- program must be compiled in the same "way". Certain options change
1182 -- parameters of the virtual machine, eg. profiling adds an extra word
1183 -- to the object header, so profiling objects cannot be linked with
1184 -- non-profiling objects.
1185
1186 -- After parsing the command-line options, we determine which "way" we
1187 -- are building - this might be a combination way, eg. profiling+threaded.
1188
1189 -- We then find the "build-tag" associated with this way, and this
1190 -- becomes the suffix used to find .hi files and libraries used in
1191 -- this compilation.
1192
1193 data Way
1194 = WayCustom String -- for GHC API clients building custom variants
1195 | WayThreaded
1196 | WayDebug
1197 | WayProf
1198 | WayEventLog
1199 | WayPar
1200 | WayDyn
1201 deriving (Eq, Ord, Show)
1202
1203 allowed_combination :: [Way] -> Bool
1204 allowed_combination way = and [ x `allowedWith` y
1205 | x <- way, y <- way, x < y ]
1206 where
1207 -- Note ordering in these tests: the left argument is
1208 -- <= the right argument, according to the Ord instance
1209 -- on Way above.
1210
1211 -- dyn is allowed with everything
1212 _ `allowedWith` WayDyn = True
1213 WayDyn `allowedWith` _ = True
1214
1215 -- debug is allowed with everything
1216 _ `allowedWith` WayDebug = True
1217 WayDebug `allowedWith` _ = True
1218
1219 (WayCustom {}) `allowedWith` _ = True
1220 WayThreaded `allowedWith` WayProf = True
1221 WayThreaded `allowedWith` WayEventLog = True
1222 _ `allowedWith` _ = False
1223
1224 mkBuildTag :: [Way] -> String
1225 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
1226
1227 wayTag :: Way -> String
1228 wayTag (WayCustom xs) = xs
1229 wayTag WayThreaded = "thr"
1230 wayTag WayDebug = "debug"
1231 wayTag WayDyn = "dyn"
1232 wayTag WayProf = "p"
1233 wayTag WayEventLog = "l"
1234 wayTag WayPar = "mp"
1235
1236 wayRTSOnly :: Way -> Bool
1237 wayRTSOnly (WayCustom {}) = False
1238 wayRTSOnly WayThreaded = True
1239 wayRTSOnly WayDebug = True
1240 wayRTSOnly WayDyn = False
1241 wayRTSOnly WayProf = False
1242 wayRTSOnly WayEventLog = True
1243 wayRTSOnly WayPar = False
1244
1245 wayDesc :: Way -> String
1246 wayDesc (WayCustom xs) = xs
1247 wayDesc WayThreaded = "Threaded"
1248 wayDesc WayDebug = "Debug"
1249 wayDesc WayDyn = "Dynamic"
1250 wayDesc WayProf = "Profiling"
1251 wayDesc WayEventLog = "RTS Event Logging"
1252 wayDesc WayPar = "Parallel"
1253
1254 -- Turn these flags on when enabling this way
1255 wayGeneralFlags :: Platform -> Way -> [GeneralFlag]
1256 wayGeneralFlags _ (WayCustom {}) = []
1257 wayGeneralFlags _ WayThreaded = []
1258 wayGeneralFlags _ WayDebug = []
1259 wayGeneralFlags _ WayDyn = [Opt_PIC]
1260 -- We could get away without adding -fPIC when compiling the
1261 -- modules of a program that is to be linked with -dynamic; the
1262 -- program itself does not need to be position-independent, only
1263 -- the libraries need to be. HOWEVER, GHCi links objects into a
1264 -- .so before loading the .so using the system linker. Since only
1265 -- PIC objects can be linked into a .so, we have to compile even
1266 -- modules of the main program with -fPIC when using -dynamic.
1267 wayGeneralFlags _ WayProf = [Opt_SccProfilingOn]
1268 wayGeneralFlags _ WayEventLog = []
1269 wayGeneralFlags _ WayPar = [Opt_Parallel]
1270
1271 -- Turn these flags off when enabling this way
1272 wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag]
1273 wayUnsetGeneralFlags _ (WayCustom {}) = []
1274 wayUnsetGeneralFlags _ WayThreaded = []
1275 wayUnsetGeneralFlags _ WayDebug = []
1276 wayUnsetGeneralFlags _ WayDyn = [-- There's no point splitting objects
1277 -- when we're going to be dynamically
1278 -- linking. Plus it breaks compilation
1279 -- on OSX x86.
1280 Opt_SplitObjs]
1281 wayUnsetGeneralFlags _ WayProf = []
1282 wayUnsetGeneralFlags _ WayEventLog = []
1283 wayUnsetGeneralFlags _ WayPar = []
1284
1285 wayExtras :: Platform -> Way -> DynFlags -> DynFlags
1286 wayExtras _ (WayCustom {}) dflags = dflags
1287 wayExtras _ WayThreaded dflags = dflags
1288 wayExtras _ WayDebug dflags = dflags
1289 wayExtras _ WayDyn dflags = dflags
1290 wayExtras _ WayProf dflags = dflags
1291 wayExtras _ WayEventLog dflags = dflags
1292 wayExtras _ WayPar dflags = exposePackage' "concurrent" dflags
1293
1294 wayOptc :: Platform -> Way -> [String]
1295 wayOptc _ (WayCustom {}) = []
1296 wayOptc platform WayThreaded = case platformOS platform of
1297 OSOpenBSD -> ["-pthread"]
1298 OSNetBSD -> ["-pthread"]
1299 _ -> []
1300 wayOptc _ WayDebug = []
1301 wayOptc _ WayDyn = []
1302 wayOptc _ WayProf = ["-DPROFILING"]
1303 wayOptc _ WayEventLog = ["-DTRACING"]
1304 wayOptc _ WayPar = ["-DPAR", "-w"]
1305
1306 wayOptl :: Platform -> Way -> [String]
1307 wayOptl _ (WayCustom {}) = []
1308 wayOptl platform WayThreaded =
1309 case platformOS platform of
1310 -- FreeBSD's default threading library is the KSE-based M:N libpthread,
1311 -- which GHC has some problems with. It's currently not clear whether
1312 -- the problems are our fault or theirs, but it seems that using the
1313 -- alternative 1:1 threading library libthr works around it:
1314 OSFreeBSD -> ["-lthr"]
1315 OSOpenBSD -> ["-pthread"]
1316 OSNetBSD -> ["-pthread"]
1317 _ -> []
1318 wayOptl _ WayDebug = []
1319 wayOptl _ WayDyn = []
1320 wayOptl _ WayProf = []
1321 wayOptl _ WayEventLog = []
1322 wayOptl _ WayPar = ["-L${PVM_ROOT}/lib/${PVM_ARCH}",
1323 "-lpvm3",
1324 "-lgpvm3"]
1325
1326 wayOptP :: Platform -> Way -> [String]
1327 wayOptP _ (WayCustom {}) = []
1328 wayOptP _ WayThreaded = []
1329 wayOptP _ WayDebug = []
1330 wayOptP _ WayDyn = []
1331 wayOptP _ WayProf = ["-DPROFILING"]
1332 wayOptP _ WayEventLog = ["-DTRACING"]
1333 wayOptP _ WayPar = ["-D__PARALLEL_HASKELL__"]
1334
1335 whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1336 whenGeneratingDynamicToo dflags f = ifGeneratingDynamicToo dflags f (return ())
1337
1338 ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1339 ifGeneratingDynamicToo dflags f g = generateDynamicTooConditional dflags f g g
1340
1341 whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1342 whenCannotGenerateDynamicToo dflags f
1343 = ifCannotGenerateDynamicToo dflags f (return ())
1344
1345 ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1346 ifCannotGenerateDynamicToo dflags f g
1347 = generateDynamicTooConditional dflags g f g
1348
1349 generateDynamicTooConditional :: MonadIO m
1350 => DynFlags -> m a -> m a -> m a -> m a
1351 generateDynamicTooConditional dflags canGen cannotGen notTryingToGen
1352 = if gopt Opt_BuildDynamicToo dflags
1353 then do let ref = canGenerateDynamicToo dflags
1354 b <- liftIO $ readIORef ref
1355 if b then canGen else cannotGen
1356 else notTryingToGen
1357
1358 dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags
1359 dynamicTooMkDynamicDynFlags dflags0
1360 = let dflags1 = addWay' WayDyn dflags0
1361 dflags2 = dflags1 {
1362 outputFile = dynOutputFile dflags1,
1363 hiSuf = dynHiSuf dflags1,
1364 objectSuf = dynObjectSuf dflags1
1365 }
1366 dflags3 = updateWays dflags2
1367 dflags4 = gopt_unset dflags3 Opt_BuildDynamicToo
1368 in dflags4
1369
1370 -----------------------------------------------------------------------------
1371
1372 -- | Used by 'GHC.runGhc' to partially initialize a new 'DynFlags' value
1373 initDynFlags :: DynFlags -> IO DynFlags
1374 initDynFlags dflags = do
1375 let -- We can't build with dynamic-too on Windows, as labels before
1376 -- the fork point are different depending on whether we are
1377 -- building dynamically or not.
1378 platformCanGenerateDynamicToo
1379 = platformOS (targetPlatform dflags) /= OSMinGW32
1380 refCanGenerateDynamicToo <- newIORef platformCanGenerateDynamicToo
1381 refNextTempSuffix <- newIORef 0
1382 refFilesToClean <- newIORef []
1383 refDirsToClean <- newIORef Map.empty
1384 refFilesToNotIntermediateClean <- newIORef []
1385 refGeneratedDumps <- newIORef Set.empty
1386 refLlvmVersion <- newIORef 28
1387 refRtldInfo <- newIORef Nothing
1388 refRtccInfo <- newIORef Nothing
1389 wrapperNum <- newIORef emptyModuleEnv
1390 canUseUnicode <- do let enc = localeEncoding
1391 str = "‘’"
1392 (withCString enc str $ \cstr ->
1393 do str' <- peekCString enc cstr
1394 return (str == str'))
1395 `catchIOError` \_ -> return False
1396 return dflags{
1397 canGenerateDynamicToo = refCanGenerateDynamicToo,
1398 nextTempSuffix = refNextTempSuffix,
1399 filesToClean = refFilesToClean,
1400 dirsToClean = refDirsToClean,
1401 filesToNotIntermediateClean = refFilesToNotIntermediateClean,
1402 generatedDumps = refGeneratedDumps,
1403 llvmVersion = refLlvmVersion,
1404 nextWrapperNum = wrapperNum,
1405 useUnicode = canUseUnicode,
1406 rtldInfo = refRtldInfo,
1407 rtccInfo = refRtccInfo
1408 }
1409
1410 -- | The normal 'DynFlags'. Note that they are not suitable for use in this form
1411 -- and must be fully initialized by 'GHC.runGhc' first.
1412 defaultDynFlags :: Settings -> DynFlags
1413 defaultDynFlags mySettings =
1414 -- See Note [Updating flag description in the User's Guide]
1415 DynFlags {
1416 ghcMode = CompManager,
1417 ghcLink = LinkBinary,
1418 hscTarget = defaultHscTarget (sTargetPlatform mySettings),
1419 sigOf = Map.empty,
1420 verbosity = 0,
1421 optLevel = 0,
1422 simplPhases = 2,
1423 maxSimplIterations = 4,
1424 ruleCheck = Nothing,
1425 maxRelevantBinds = Just 6,
1426 simplTickFactor = 100,
1427 specConstrThreshold = Just 2000,
1428 specConstrCount = Just 3,
1429 specConstrRecursive = 3,
1430 liberateCaseThreshold = Just 2000,
1431 floatLamArgs = Just 0, -- Default: float only if no fvs
1432
1433 historySize = 20,
1434 strictnessBefore = [],
1435
1436 parMakeCount = Just 1,
1437
1438 enableTimeStats = False,
1439 ghcHeapSize = Nothing,
1440
1441 cmdlineHcIncludes = [],
1442 importPaths = ["."],
1443 mainModIs = mAIN,
1444 mainFunIs = Nothing,
1445 reductionDepth = treatZeroAsInf mAX_REDUCTION_DEPTH,
1446 solverIterations = treatZeroAsInf mAX_SOLVER_ITERATIONS,
1447
1448 thisPackage = mainPackageKey,
1449
1450 objectDir = Nothing,
1451 dylibInstallName = Nothing,
1452 hiDir = Nothing,
1453 stubDir = Nothing,
1454 dumpDir = Nothing,
1455
1456 objectSuf = phaseInputExt StopLn,
1457 hcSuf = phaseInputExt HCc,
1458 hiSuf = "hi",
1459
1460 canGenerateDynamicToo = panic "defaultDynFlags: No canGenerateDynamicToo",
1461 dynObjectSuf = "dyn_" ++ phaseInputExt StopLn,
1462 dynHiSuf = "dyn_hi",
1463
1464 dllSplitFile = Nothing,
1465 dllSplit = Nothing,
1466
1467 pluginModNames = [],
1468 pluginModNameOpts = [],
1469 hooks = emptyHooks,
1470
1471 outputFile = Nothing,
1472 dynOutputFile = Nothing,
1473 outputHi = Nothing,
1474 dynLibLoader = SystemDependent,
1475 dumpPrefix = Nothing,
1476 dumpPrefixForce = Nothing,
1477 ldInputs = [],
1478 includePaths = [],
1479 libraryPaths = [],
1480 frameworkPaths = [],
1481 cmdlineFrameworks = [],
1482 rtsOpts = Nothing,
1483 rtsOptsEnabled = RtsOptsSafeOnly,
1484 rtsOptsSuggestions = True,
1485
1486 hpcDir = ".hpc",
1487
1488 extraPkgConfs = id,
1489 packageFlags = [],
1490 packageEnv = Nothing,
1491 pkgDatabase = Nothing,
1492 -- This gets filled in with GHC.setSessionDynFlags
1493 pkgState = emptyPackageState,
1494 ways = defaultWays mySettings,
1495 buildTag = mkBuildTag (defaultWays mySettings),
1496 rtsBuildTag = mkBuildTag (defaultWays mySettings),
1497 splitInfo = Nothing,
1498 settings = mySettings,
1499 -- ghc -M values
1500 depMakefile = "Makefile",
1501 depIncludePkgDeps = False,
1502 depExcludeMods = [],
1503 depSuffixes = [],
1504 -- end of ghc -M values
1505 nextTempSuffix = panic "defaultDynFlags: No nextTempSuffix",
1506 filesToClean = panic "defaultDynFlags: No filesToClean",
1507 dirsToClean = panic "defaultDynFlags: No dirsToClean",
1508 filesToNotIntermediateClean = panic "defaultDynFlags: No filesToNotIntermediateClean",
1509 generatedDumps = panic "defaultDynFlags: No generatedDumps",
1510 haddockOptions = Nothing,
1511 dumpFlags = IntSet.empty,
1512 generalFlags = IntSet.fromList (map fromEnum (defaultFlags mySettings)),
1513 warningFlags = IntSet.fromList (map fromEnum standardWarnings),
1514 ghciScripts = [],
1515 language = Nothing,
1516 safeHaskell = Sf_None,
1517 safeInfer = True,
1518 safeInferred = True,
1519 thOnLoc = noSrcSpan,
1520 newDerivOnLoc = noSrcSpan,
1521 overlapInstLoc = noSrcSpan,
1522 incoherentOnLoc = noSrcSpan,
1523 pkgTrustOnLoc = noSrcSpan,
1524 warnSafeOnLoc = noSrcSpan,
1525 warnUnsafeOnLoc = noSrcSpan,
1526 trustworthyOnLoc = noSrcSpan,
1527 extensions = [],
1528 extensionFlags = flattenExtensionFlags Nothing [],
1529
1530 -- The ufCreationThreshold threshold must be reasonably high to
1531 -- take account of possible discounts.
1532 -- E.g. 450 is not enough in 'fulsom' for Interval.sqr to inline
1533 -- into Csg.calc (The unfolding for sqr never makes it into the
1534 -- interface file.)
1535 ufCreationThreshold = 750,
1536 ufUseThreshold = 60,
1537 ufFunAppDiscount = 60,
1538 -- Be fairly keen to inline a fuction if that means
1539 -- we'll be able to pick the right method from a dictionary
1540 ufDictDiscount = 30,
1541 ufKeenessFactor = 1.5,
1542 ufDearOp = 40,
1543
1544 maxWorkerArgs = 10,
1545
1546 ghciHistSize = 50, -- keep a log of length 50 by default
1547
1548 log_action = defaultLogAction,
1549 flushOut = defaultFlushOut,
1550 flushErr = defaultFlushErr,
1551 pprUserLength = 5,
1552 pprCols = 100,
1553 useUnicode = False,
1554 traceLevel = 1,
1555 profAuto = NoProfAuto,
1556 llvmVersion = panic "defaultDynFlags: No llvmVersion",
1557 interactivePrint = Nothing,
1558 nextWrapperNum = panic "defaultDynFlags: No nextWrapperNum",
1559 sseVersion = Nothing,
1560 avx = False,
1561 avx2 = False,
1562 avx512cd = False,
1563 avx512er = False,
1564 avx512f = False,
1565 avx512pf = False,
1566 rtldInfo = panic "defaultDynFlags: no rtldInfo",
1567 rtccInfo = panic "defaultDynFlags: no rtccInfo",
1568
1569 maxInlineAllocSize = 128,
1570 maxInlineMemcpyInsns = 32,
1571 maxInlineMemsetInsns = 32
1572 }
1573
1574 defaultWays :: Settings -> [Way]
1575 defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
1576 then [WayDyn]
1577 else []
1578
1579 interpWays :: [Way]
1580 interpWays = if dynamicGhc
1581 then [WayDyn]
1582 else []
1583
1584 --------------------------------------------------------------------------
1585
1586 type FatalMessager = String -> IO ()
1587 type LogAction = DynFlags -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO ()
1588
1589 defaultFatalMessager :: FatalMessager
1590 defaultFatalMessager = hPutStrLn stderr
1591
1592 defaultLogAction :: LogAction
1593 defaultLogAction dflags severity srcSpan style msg
1594 = case severity of
1595 SevOutput -> printSDoc msg style
1596 SevDump -> printSDoc (msg $$ blankLine) style
1597 SevInteractive -> putStrSDoc msg style
1598 SevInfo -> printErrs msg style
1599 SevFatal -> printErrs msg style
1600 _ -> do hPutChar stderr '\n'
1601 printErrs (mkLocMessage severity srcSpan msg) style
1602 -- careful (#2302): printErrs prints in UTF-8,
1603 -- whereas converting to string first and using
1604 -- hPutStr would just emit the low 8 bits of
1605 -- each unicode char.
1606 where printSDoc = defaultLogActionHPrintDoc dflags stdout
1607 printErrs = defaultLogActionHPrintDoc dflags stderr
1608 putStrSDoc = defaultLogActionHPutStrDoc dflags stdout
1609
1610 defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
1611 defaultLogActionHPrintDoc dflags h d sty
1612 = defaultLogActionHPutStrDoc dflags h (d $$ text "") sty
1613 -- Adds a newline
1614
1615 defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
1616 defaultLogActionHPutStrDoc dflags h d sty
1617 = Pretty.printDoc_ Pretty.PageMode (pprCols dflags) h doc
1618 where -- Don't add a newline at the end, so that successive
1619 -- calls to this log-action can output all on the same line
1620 doc = runSDoc d (initSDocContext dflags sty)
1621
1622 newtype FlushOut = FlushOut (IO ())
1623
1624 defaultFlushOut :: FlushOut
1625 defaultFlushOut = FlushOut $ hFlush stdout
1626
1627 newtype FlushErr = FlushErr (IO ())
1628
1629 defaultFlushErr :: FlushErr
1630 defaultFlushErr = FlushErr $ hFlush stderr
1631
1632 {-
1633 Note [Verbosity levels]
1634 ~~~~~~~~~~~~~~~~~~~~~~~
1635 0 | print errors & warnings only
1636 1 | minimal verbosity: print "compiling M ... done." for each module.
1637 2 | equivalent to -dshow-passes
1638 3 | equivalent to existing "ghc -v"
1639 4 | "ghc -v -ddump-most"
1640 5 | "ghc -v -ddump-all"
1641 -}
1642
1643 data OnOff a = On a
1644 | Off a
1645
1646 -- OnOffs accumulate in reverse order, so we use foldr in order to
1647 -- process them in the right order
1648 flattenExtensionFlags :: Maybe Language -> [OnOff ExtensionFlag] -> IntSet
1649 flattenExtensionFlags ml = foldr f defaultExtensionFlags
1650 where f (On f) flags = IntSet.insert (fromEnum f) flags
1651 f (Off f) flags = IntSet.delete (fromEnum f) flags
1652 defaultExtensionFlags = IntSet.fromList (map fromEnum (languageExtensions ml))
1653
1654 languageExtensions :: Maybe Language -> [ExtensionFlag]
1655
1656 languageExtensions Nothing
1657 -- Nothing => the default case
1658 = Opt_NondecreasingIndentation -- This has been on by default for some time
1659 : delete Opt_DatatypeContexts -- The Haskell' committee decided to
1660 -- remove datatype contexts from the
1661 -- language:
1662 -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
1663 (languageExtensions (Just Haskell2010))
1664
1665 -- NB: MonoPatBinds is no longer the default
1666
1667 languageExtensions (Just Haskell98)
1668 = [Opt_ImplicitPrelude,
1669 Opt_MonomorphismRestriction,
1670 Opt_NPlusKPatterns,
1671 Opt_DatatypeContexts,
1672 Opt_TraditionalRecordSyntax,
1673 Opt_NondecreasingIndentation
1674 -- strictly speaking non-standard, but we always had this
1675 -- on implicitly before the option was added in 7.1, and
1676 -- turning it off breaks code, so we're keeping it on for
1677 -- backwards compatibility. Cabal uses -XHaskell98 by
1678 -- default unless you specify another language.
1679 ]
1680
1681 languageExtensions (Just Haskell2010)
1682 = [Opt_ImplicitPrelude,
1683 Opt_MonomorphismRestriction,
1684 Opt_DatatypeContexts,
1685 Opt_TraditionalRecordSyntax,
1686 Opt_EmptyDataDecls,
1687 Opt_ForeignFunctionInterface,
1688 Opt_PatternGuards,
1689 Opt_DoAndIfThenElse,
1690 Opt_RelaxedPolyRec]
1691
1692 -- | Test whether a 'DumpFlag' is set
1693 dopt :: DumpFlag -> DynFlags -> Bool
1694 dopt f dflags = (fromEnum f `IntSet.member` dumpFlags dflags)
1695 || (verbosity dflags >= 4 && enableIfVerbose f)
1696 where enableIfVerbose Opt_D_dump_tc_trace = False
1697 enableIfVerbose Opt_D_dump_rn_trace = False
1698 enableIfVerbose Opt_D_dump_cs_trace = False
1699 enableIfVerbose Opt_D_dump_if_trace = False
1700 enableIfVerbose Opt_D_dump_vt_trace = False
1701 enableIfVerbose Opt_D_dump_tc = False
1702 enableIfVerbose Opt_D_dump_rn = False
1703 enableIfVerbose Opt_D_dump_rn_stats = False
1704 enableIfVerbose Opt_D_dump_hi_diffs = False
1705 enableIfVerbose Opt_D_verbose_core2core = False
1706 enableIfVerbose Opt_D_verbose_stg2stg = False
1707 enableIfVerbose Opt_D_dump_splices = False
1708 enableIfVerbose Opt_D_th_dec_file = False
1709 enableIfVerbose Opt_D_dump_rule_firings = False
1710 enableIfVerbose Opt_D_dump_rule_rewrites = False
1711 enableIfVerbose Opt_D_dump_simpl_trace = False
1712 enableIfVerbose Opt_D_dump_rtti = False
1713 enableIfVerbose Opt_D_dump_inlinings = False
1714 enableIfVerbose Opt_D_dump_core_stats = False
1715 enableIfVerbose Opt_D_dump_asm_stats = False
1716 enableIfVerbose Opt_D_dump_types = False
1717 enableIfVerbose Opt_D_dump_simpl_iterations = False
1718 enableIfVerbose Opt_D_dump_ticked = False
1719 enableIfVerbose Opt_D_dump_view_pattern_commoning = False
1720 enableIfVerbose Opt_D_dump_mod_cycles = False
1721 enableIfVerbose Opt_D_dump_mod_map = False
1722 enableIfVerbose _ = True
1723
1724 -- | Set a 'DumpFlag'
1725 dopt_set :: DynFlags -> DumpFlag -> DynFlags
1726 dopt_set dfs f = dfs{ dumpFlags = IntSet.insert (fromEnum f) (dumpFlags dfs) }
1727
1728 -- | Unset a 'DumpFlag'
1729 dopt_unset :: DynFlags -> DumpFlag -> DynFlags
1730 dopt_unset dfs f = dfs{ dumpFlags = IntSet.delete (fromEnum f) (dumpFlags dfs) }
1731
1732 -- | Test whether a 'GeneralFlag' is set
1733 gopt :: GeneralFlag -> DynFlags -> Bool
1734 gopt f dflags = fromEnum f `IntSet.member` generalFlags dflags
1735
1736 -- | Set a 'GeneralFlag'
1737 gopt_set :: DynFlags -> GeneralFlag -> DynFlags
1738 gopt_set dfs f = dfs{ generalFlags = IntSet.insert (fromEnum f) (generalFlags dfs) }
1739
1740 -- | Unset a 'GeneralFlag'
1741 gopt_unset :: DynFlags -> GeneralFlag -> DynFlags
1742 gopt_unset dfs f = dfs{ generalFlags = IntSet.delete (fromEnum f) (generalFlags dfs) }
1743
1744 -- | Test whether a 'WarningFlag' is set
1745 wopt :: WarningFlag -> DynFlags -> Bool
1746 wopt f dflags = fromEnum f `IntSet.member` warningFlags dflags
1747
1748 -- | Set a 'WarningFlag'
1749 wopt_set :: DynFlags -> WarningFlag -> DynFlags
1750 wopt_set dfs f = dfs{ warningFlags = IntSet.insert (fromEnum f) (warningFlags dfs) }
1751
1752 -- | Unset a 'WarningFlag'
1753 wopt_unset :: DynFlags -> WarningFlag -> DynFlags
1754 wopt_unset dfs f = dfs{ warningFlags = IntSet.delete (fromEnum f) (warningFlags dfs) }
1755
1756 -- | Test whether a 'ExtensionFlag' is set
1757 xopt :: ExtensionFlag -> DynFlags -> Bool
1758 xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags
1759
1760 -- | Set a 'ExtensionFlag'
1761 xopt_set :: DynFlags -> ExtensionFlag -> DynFlags
1762 xopt_set dfs f
1763 = let onoffs = On f : extensions dfs
1764 in dfs { extensions = onoffs,
1765 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
1766
1767 -- | Unset a 'ExtensionFlag'
1768 xopt_unset :: DynFlags -> ExtensionFlag -> DynFlags
1769 xopt_unset dfs f
1770 = let onoffs = Off f : extensions dfs
1771 in dfs { extensions = onoffs,
1772 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
1773
1774 lang_set :: DynFlags -> Maybe Language -> DynFlags
1775 lang_set dflags lang =
1776 dflags {
1777 language = lang,
1778 extensionFlags = flattenExtensionFlags lang (extensions dflags)
1779 }
1780
1781 -- | Check whether to use unicode syntax for output
1782 useUnicodeSyntax :: DynFlags -> Bool
1783 useUnicodeSyntax = gopt Opt_PrintUnicodeSyntax
1784
1785 -- | Set the Haskell language standard to use
1786 setLanguage :: Language -> DynP ()
1787 setLanguage l = upd (`lang_set` Just l)
1788
1789 -- | Some modules have dependencies on others through the DynFlags rather than textual imports
1790 dynFlagDependencies :: DynFlags -> [ModuleName]
1791 dynFlagDependencies = pluginModNames
1792
1793 -- | Is the -fpackage-trust mode on
1794 packageTrustOn :: DynFlags -> Bool
1795 packageTrustOn = gopt Opt_PackageTrust
1796
1797 -- | Is Safe Haskell on in some way (including inference mode)
1798 safeHaskellOn :: DynFlags -> Bool
1799 safeHaskellOn dflags = safeHaskell dflags /= Sf_None || safeInferOn dflags
1800
1801 -- | Is the Safe Haskell safe language in use
1802 safeLanguageOn :: DynFlags -> Bool
1803 safeLanguageOn dflags = safeHaskell dflags == Sf_Safe
1804
1805 -- | Is the Safe Haskell safe inference mode active
1806 safeInferOn :: DynFlags -> Bool
1807 safeInferOn = safeInfer
1808
1809 -- | Test if Safe Imports are on in some form
1810 safeImportsOn :: DynFlags -> Bool
1811 safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
1812 safeHaskell dflags == Sf_Trustworthy ||
1813 safeHaskell dflags == Sf_Safe
1814
1815 -- | Set a 'Safe Haskell' flag
1816 setSafeHaskell :: SafeHaskellMode -> DynP ()
1817 setSafeHaskell s = updM f
1818 where f dfs = do
1819 let sf = safeHaskell dfs
1820 safeM <- combineSafeFlags sf s
1821 case s of
1822 Sf_Safe -> return $ dfs { safeHaskell = safeM, safeInfer = False }
1823 -- leave safe inferrence on in Trustworthy mode so we can warn
1824 -- if it could have been inferred safe.
1825 Sf_Trustworthy -> do
1826 l <- getCurLoc
1827 return $ dfs { safeHaskell = safeM, trustworthyOnLoc = l }
1828 -- leave safe inference on in Unsafe mode as well.
1829 _ -> return $ dfs { safeHaskell = safeM }
1830
1831 -- | Are all direct imports required to be safe for this Safe Haskell mode?
1832 -- Direct imports are when the code explicitly imports a module
1833 safeDirectImpsReq :: DynFlags -> Bool
1834 safeDirectImpsReq d = safeLanguageOn d
1835
1836 -- | Are all implicit imports required to be safe for this Safe Haskell mode?
1837 -- Implicit imports are things in the prelude. e.g System.IO when print is used.
1838 safeImplicitImpsReq :: DynFlags -> Bool
1839 safeImplicitImpsReq d = safeLanguageOn d
1840
1841 -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
1842 -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
1843 -- want to export this functionality from the module but do want to export the
1844 -- type constructors.
1845 combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
1846 combineSafeFlags a b | a == Sf_None = return b
1847 | b == Sf_None = return a
1848 | a == b = return a
1849 | otherwise = addErr errm >> return (panic errm)
1850 where errm = "Incompatible Safe Haskell flags! ("
1851 ++ show a ++ ", " ++ show b ++ ")"
1852
1853 -- | A list of unsafe flags under Safe Haskell. Tuple elements are:
1854 -- * name of the flag
1855 -- * function to get srcspan that enabled the flag
1856 -- * function to test if the flag is on
1857 -- * function to turn the flag off
1858 unsafeFlags, unsafeFlagsForInfer
1859 :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
1860 unsafeFlags = [ ("-XGeneralizedNewtypeDeriving", newDerivOnLoc,
1861 xopt Opt_GeneralizedNewtypeDeriving,
1862 flip xopt_unset Opt_GeneralizedNewtypeDeriving)
1863 , ("-XTemplateHaskell", thOnLoc,
1864 xopt Opt_TemplateHaskell,
1865 flip xopt_unset Opt_TemplateHaskell)
1866 ]
1867 unsafeFlagsForInfer = unsafeFlags
1868
1869
1870 -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
1871 getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
1872 -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
1873 -> [a] -- ^ Correctly ordered extracted options
1874 getOpts dflags opts = reverse (opts dflags)
1875 -- We add to the options from the front, so we need to reverse the list
1876
1877 -- | Gets the verbosity flag for the current verbosity level. This is fed to
1878 -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
1879 getVerbFlags :: DynFlags -> [String]
1880 getVerbFlags dflags
1881 | verbosity dflags >= 4 = ["-v"]
1882 | otherwise = []
1883
1884 setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir,
1885 setDynObjectSuf, setDynHiSuf,
1886 setDylibInstallName,
1887 setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode,
1888 setPgmP, addOptl, addOptc, addOptP,
1889 addCmdlineFramework, addHaddockOpts, addGhciScript,
1890 setInteractivePrint
1891 :: String -> DynFlags -> DynFlags
1892 setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce
1893 :: Maybe String -> DynFlags -> DynFlags
1894
1895 setObjectDir f d = d{ objectDir = Just f}
1896 setHiDir f d = d{ hiDir = Just f}
1897 setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d }
1898 -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
1899 -- \#included from the .hc file when compiling via C (i.e. unregisterised
1900 -- builds).
1901 setDumpDir f d = d{ dumpDir = Just f}
1902 setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f
1903 setDylibInstallName f d = d{ dylibInstallName = Just f}
1904
1905 setObjectSuf f d = d{ objectSuf = f}
1906 setDynObjectSuf f d = d{ dynObjectSuf = f}
1907 setHiSuf f d = d{ hiSuf = f}
1908 setDynHiSuf f d = d{ dynHiSuf = f}
1909 setHcSuf f d = d{ hcSuf = f}
1910
1911 setOutputFile f d = d{ outputFile = f}
1912 setDynOutputFile f d = d{ dynOutputFile = f}
1913 setOutputHi f d = d{ outputHi = f}
1914
1915 parseSigOf :: String -> SigOf
1916 parseSigOf str = case filter ((=="").snd) (readP_to_S parse str) of
1917 [(r, "")] -> r
1918 _ -> throwGhcException $ CmdLineError ("Can't parse -sig-of: " ++ str)
1919 where parse = Map.fromList <$> sepBy parseEntry (R.char ',')
1920 parseEntry = do
1921 n <- tok $ parseModuleName
1922 -- ToDo: deprecate this 'is' syntax?
1923 tok $ ((string "is" >> return ()) +++ (R.char '=' >> return ()))
1924 m <- tok $ parseModule
1925 return (n, m)
1926 parseModule = do
1927 pk <- munch1 (\c -> isAlphaNum c || c `elem` "-_")
1928 _ <- R.char ':'
1929 m <- parseModuleName
1930 return (mkModule (stringToPackageKey pk) m)
1931 tok m = skipSpaces >> m
1932
1933 setSigOf :: String -> DynFlags -> DynFlags
1934 setSigOf s d = d { sigOf = parseSigOf s }
1935
1936 addPluginModuleName :: String -> DynFlags -> DynFlags
1937 addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
1938
1939 addPluginModuleNameOption :: String -> DynFlags -> DynFlags
1940 addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
1941 where (m, rest) = break (== ':') optflag
1942 option = case rest of
1943 [] -> "" -- should probably signal an error
1944 (_:plug_opt) -> plug_opt -- ignore the ':' from break
1945
1946 parseDynLibLoaderMode f d =
1947 case splitAt 8 f of
1948 ("deploy", "") -> d{ dynLibLoader = Deployable }
1949 ("sysdep", "") -> d{ dynLibLoader = SystemDependent }
1950 _ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f))
1951
1952 setDumpPrefixForce f d = d { dumpPrefixForce = f}
1953
1954 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
1955 -- Config.hs should really use Option.
1956 setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)})
1957 addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s})
1958 addOptc f = alterSettings (\s -> s { sOpt_c = f : sOpt_c s})
1959 addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s})
1960
1961
1962 setDepMakefile :: FilePath -> DynFlags -> DynFlags
1963 setDepMakefile f d = d { depMakefile = f }
1964
1965 setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
1966 setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
1967
1968 addDepExcludeMod :: String -> DynFlags -> DynFlags
1969 addDepExcludeMod m d
1970 = d { depExcludeMods = mkModuleName m : depExcludeMods d }
1971
1972 addDepSuffix :: FilePath -> DynFlags -> DynFlags
1973 addDepSuffix s d = d { depSuffixes = s : depSuffixes d }
1974
1975 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
1976
1977 addHaddockOpts f d = d{ haddockOptions = Just f}
1978
1979 addGhciScript f d = d{ ghciScripts = f : ghciScripts d}
1980
1981 setInteractivePrint f d = d{ interactivePrint = Just f}
1982
1983 -- -----------------------------------------------------------------------------
1984 -- Command-line options
1985
1986 -- | When invoking external tools as part of the compilation pipeline, we
1987 -- pass these a sequence of options on the command-line. Rather than
1988 -- just using a list of Strings, we use a type that allows us to distinguish
1989 -- between filepaths and 'other stuff'. The reason for this is that
1990 -- this type gives us a handle on transforming filenames, and filenames only,
1991 -- to whatever format they're expected to be on a particular platform.
1992 data Option
1993 = FileOption -- an entry that _contains_ filename(s) / filepaths.
1994 String -- a non-filepath prefix that shouldn't be
1995 -- transformed (e.g., "/out=")
1996 String -- the filepath/filename portion
1997 | Option String
1998 deriving ( Eq )
1999
2000 showOpt :: Option -> String
2001 showOpt (FileOption pre f) = pre ++ f
2002 showOpt (Option s) = s
2003
2004 -----------------------------------------------------------------------------
2005 -- Setting the optimisation level
2006
2007 updOptLevel :: Int -> DynFlags -> DynFlags
2008 -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
2009 updOptLevel n dfs
2010 = dfs2{ optLevel = final_n }
2011 where
2012 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
2013 dfs1 = foldr (flip gopt_unset) dfs remove_gopts
2014 dfs2 = foldr (flip gopt_set) dfs1 extra_gopts
2015
2016 extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
2017 remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
2018
2019 -- -----------------------------------------------------------------------------
2020 -- StgToDo: abstraction of stg-to-stg passes to run.
2021
2022 data StgToDo
2023 = StgDoMassageForProfiling -- should be (next to) last
2024 -- There's also setStgVarInfo, but its absolute "lastness"
2025 -- is so critical that it is hardwired in (no flag).
2026 | D_stg_stats
2027
2028 getStgToDo :: DynFlags -> [StgToDo]
2029 getStgToDo dflags
2030 = todo2
2031 where
2032 stg_stats = gopt Opt_StgStats dflags
2033
2034 todo1 = if stg_stats then [D_stg_stats] else []
2035
2036 todo2 | WayProf `elem` ways dflags
2037 = StgDoMassageForProfiling : todo1
2038 | otherwise
2039 = todo1
2040
2041 {- **********************************************************************
2042 %* *
2043 DynFlags parser
2044 %* *
2045 %********************************************************************* -}
2046
2047 -- -----------------------------------------------------------------------------
2048 -- Parsing the dynamic flags.
2049
2050
2051 -- | Parse dynamic flags from a list of command line arguments. Returns the
2052 -- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
2053 -- Throws a 'UsageError' if errors occurred during parsing (such as unknown
2054 -- flags or missing arguments).
2055 parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String]
2056 -> m (DynFlags, [Located String], [Located String])
2057 -- ^ Updated 'DynFlags', left-over arguments, and
2058 -- list of warnings.
2059 parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True
2060
2061
2062 -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
2063 -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db).
2064 -- Used to parse flags set in a modules pragma.
2065 parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String]
2066 -> m (DynFlags, [Located String], [Located String])
2067 -- ^ Updated 'DynFlags', left-over arguments, and
2068 -- list of warnings.
2069 parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False
2070
2071
2072 -- | Parses the dynamically set flags for GHC. This is the most general form of
2073 -- the dynamic flag parser that the other methods simply wrap. It allows
2074 -- saying which flags are valid flags and indicating if we are parsing
2075 -- arguments from the command line or from a file pragma.
2076 parseDynamicFlagsFull :: MonadIO m
2077 => [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against
2078 -> Bool -- ^ are the arguments from the command line?
2079 -> DynFlags -- ^ current dynamic flags
2080 -> [Located String] -- ^ arguments to parse
2081 -> m (DynFlags, [Located String], [Located String])
2082 parseDynamicFlagsFull activeFlags cmdline dflags0 args = do
2083 let ((leftover, errs, warns), dflags1)
2084 = runCmdLine (processArgs activeFlags args) dflags0
2085
2086 -- See Note [Handling errors when parsing commandline flags]
2087 unless (null errs) $ liftIO $ throwGhcExceptionIO $
2088 errorsToGhcException . map (showPpr dflags0 . getLoc &&& unLoc) $ errs
2089
2090 -- check for disabled flags in safe haskell
2091 let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1
2092 dflags3 = updateWays dflags2
2093 theWays = ways dflags3
2094
2095 unless (allowed_combination theWays) $ liftIO $
2096 throwGhcExceptionIO (CmdLineError ("combination not supported: " ++
2097 intercalate "/" (map wayDesc theWays)))
2098
2099 let chooseOutput
2100 | isJust (outputFile dflags3) -- Only iff user specified -o ...
2101 , not (isJust (dynOutputFile dflags3)) -- but not -dyno
2102 = return $ dflags3 { dynOutputFile = Just $ dynOut (fromJust $ outputFile dflags3) }
2103 | otherwise
2104 = return dflags3
2105 where
2106 dynOut = flip addExtension (dynObjectSuf dflags3) . dropExtension
2107 dflags4 <- ifGeneratingDynamicToo dflags3 chooseOutput (return dflags3)
2108
2109 let (dflags5, consistency_warnings) = makeDynFlagsConsistent dflags4
2110
2111 dflags6 <- case dllSplitFile dflags5 of
2112 Nothing -> return (dflags5 { dllSplit = Nothing })
2113 Just f ->
2114 case dllSplit dflags5 of
2115 Just _ ->
2116 -- If dllSplit is out of date then it would have
2117 -- been set to Nothing. As it's a Just, it must be
2118 -- up-to-date.
2119 return dflags5
2120 Nothing ->
2121 do xs <- liftIO $ readFile f
2122 let ss = map (Set.fromList . words) (lines xs)
2123 return $ dflags5 { dllSplit = Just ss }
2124
2125 -- Set timer stats & heap size
2126 when (enableTimeStats dflags6) $ liftIO enableTimingStats
2127 case (ghcHeapSize dflags6) of
2128 Just x -> liftIO (setHeapSize x)
2129 _ -> return ()
2130
2131 liftIO $ setUnsafeGlobalDynFlags dflags6
2132
2133 return (dflags6, leftover, consistency_warnings ++ sh_warns ++ warns)
2134
2135 updateWays :: DynFlags -> DynFlags
2136 updateWays dflags
2137 = let theWays = sort $ nub $ ways dflags
2138 f = if WayDyn `elem` theWays then unSetGeneralFlag'
2139 else setGeneralFlag'
2140 in f Opt_Static
2141 $ dflags {
2142 ways = theWays,
2143 buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays),
2144 rtsBuildTag = mkBuildTag theWays
2145 }
2146
2147 -- | Check (and potentially disable) any extensions that aren't allowed
2148 -- in safe mode.
2149 --
2150 -- The bool is to indicate if we are parsing command line flags (false means
2151 -- file pragma). This allows us to generate better warnings.
2152 safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
2153 safeFlagCheck _ dflags | safeLanguageOn dflags = (dflagsUnset, warns)
2154 where
2155 -- Handle illegal flags under safe language.
2156 (dflagsUnset, warns) = foldl check_method (dflags, []) unsafeFlags
2157
2158 check_method (df, warns) (str,loc,test,fix)
2159 | test df = (fix df, warns ++ safeFailure (loc df) str)
2160 | otherwise = (df, warns)
2161
2162 safeFailure loc str
2163 = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring "
2164 ++ str]
2165
2166 safeFlagCheck cmdl dflags =
2167 case (safeInferOn dflags) of
2168 True | safeFlags -> (dflags', warn)
2169 True -> (dflags' { safeInferred = False }, warn)
2170 False -> (dflags', warn)
2171
2172 where
2173 -- dynflags and warn for when -fpackage-trust by itself with no safe
2174 -- haskell flag
2175 (dflags', warn)
2176 | safeHaskell dflags == Sf_None && not cmdl && packageTrustOn dflags
2177 = (gopt_unset dflags Opt_PackageTrust, pkgWarnMsg)
2178 | otherwise = (dflags, [])
2179
2180 pkgWarnMsg = [L (pkgTrustOnLoc dflags') $
2181 "-fpackage-trust ignored;" ++
2182 " must be specified with a Safe Haskell flag"]
2183
2184 -- Have we inferred Unsafe? See Note [HscMain . Safe Haskell Inference]
2185 safeFlags = all (\(_,_,t,_) -> not $ t dflags) unsafeFlagsForInfer
2186
2187
2188 {- **********************************************************************
2189 %* *
2190 DynFlags specifications
2191 %* *
2192 %********************************************************************* -}
2193
2194 -- | All dynamic flags option strings. These are the user facing strings for
2195 -- enabling and disabling options.
2196 allFlags :: [String]
2197 allFlags = [ '-':flagName flag
2198 | flag <- flagsAll
2199 , ok (flagOptKind flag) ]
2200 where ok (PrefixPred _ _) = False
2201 ok _ = True
2202
2203 {-
2204 - Below we export user facing symbols for GHC dynamic flags for use with the
2205 - GHC API.
2206 -}
2207
2208 -- All dynamic flags present in GHC.
2209 flagsAll :: [Flag (CmdLineP DynFlags)]
2210 flagsAll = package_flags ++ dynamic_flags
2211
2212 -- All dynamic flags, minus package flags, present in GHC.
2213 flagsDynamic :: [Flag (CmdLineP DynFlags)]
2214 flagsDynamic = dynamic_flags
2215
2216 -- ALl package flags present in GHC.
2217 flagsPackage :: [Flag (CmdLineP DynFlags)]
2218 flagsPackage = package_flags
2219
2220 --------------- The main flags themselves ------------------
2221 -- See Note [Updating flag description in the User's Guide]
2222 -- See Note [Supporting CLI completion]
2223 dynamic_flags :: [Flag (CmdLineP DynFlags)]
2224 dynamic_flags = [
2225 defFlag "n"
2226 (NoArg (addWarn "The -n flag is deprecated and no longer has any effect"))
2227 , defFlag "cpp" (NoArg (setExtensionFlag Opt_Cpp))
2228 , defFlag "F" (NoArg (setGeneralFlag Opt_Pp))
2229 , defFlag "#include"
2230 (HasArg (\s -> do
2231 addCmdlineHCInclude s
2232 addWarn ("-#include and INCLUDE pragmas are " ++
2233 "deprecated: They no longer have any effect")))
2234 , defFlag "v" (OptIntSuffix setVerbosity)
2235
2236 , defGhcFlag "j" (OptIntSuffix (\n -> upd (\d -> d {parMakeCount = n})))
2237 , defFlag "sig-of" (sepArg setSigOf)
2238
2239 -- RTS options -------------------------------------------------------------
2240 , defFlag "H" (HasArg (\s -> upd (\d ->
2241 d { ghcHeapSize = Just $ fromIntegral (decodeSize s)})))
2242
2243 , defFlag "Rghc-timing" (NoArg (upd (\d -> d { enableTimeStats = True })))
2244
2245 ------- ways ---------------------------------------------------------------
2246 , defGhcFlag "prof" (NoArg (addWay WayProf))
2247 , defGhcFlag "eventlog" (NoArg (addWay WayEventLog))
2248 , defGhcFlag "parallel" (NoArg (addWay WayPar))
2249 , defGhcFlag "smp"
2250 (NoArg (addWay WayThreaded >> deprecate "Use -threaded instead"))
2251 , defGhcFlag "debug" (NoArg (addWay WayDebug))
2252 , defGhcFlag "threaded" (NoArg (addWay WayThreaded))
2253
2254 , defGhcFlag "ticky"
2255 (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug))
2256
2257 -- -ticky enables ticky-ticky code generation, and also implies -debug which
2258 -- is required to get the RTS ticky support.
2259
2260 ----- Linker --------------------------------------------------------
2261 , defGhcFlag "static" (NoArg removeWayDyn)
2262 , defGhcFlag "dynamic" (NoArg (addWay WayDyn))
2263 , defGhcFlag "rdynamic" $ noArg $
2264 #ifdef linux_HOST_OS
2265 addOptl "-rdynamic"
2266 #elif defined (mingw32_HOST_OS)
2267 addOptl "-export-all-symbols"
2268 #else
2269 -- ignored for compat w/ gcc:
2270 id
2271 #endif
2272 , defGhcFlag "relative-dynlib-paths"
2273 (NoArg (setGeneralFlag Opt_RelativeDynlibPaths))
2274
2275 ------- Specific phases --------------------------------------------
2276 -- need to appear before -pgmL to be parsed as LLVM flags.
2277 , defFlag "pgmlo"
2278 (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
2279 , defFlag "pgmlc"
2280 (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
2281 , defFlag "pgmL"
2282 (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
2283 , defFlag "pgmP"
2284 (hasArg setPgmP)
2285 , defFlag "pgmF"
2286 (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
2287 , defFlag "pgmc"
2288 (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])})))
2289 , defFlag "pgms"
2290 (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])})))
2291 , defFlag "pgma"
2292 (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
2293 , defFlag "pgml"
2294 (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
2295 , defFlag "pgmdll"
2296 (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
2297 , defFlag "pgmwindres"
2298 (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
2299 , defFlag "pgmlibtool"
2300 (hasArg (\f -> alterSettings (\s -> s { sPgm_libtool = f})))
2301
2302 -- need to appear before -optl/-opta to be parsed as LLVM flags.
2303 , defFlag "optlo"
2304 (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
2305 , defFlag "optlc"
2306 (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
2307 , defFlag "optL"
2308 (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
2309 , defFlag "optP"
2310 (hasArg addOptP)
2311 , defFlag "optF"
2312 (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
2313 , defFlag "optc"
2314 (hasArg addOptc)
2315 , defFlag "opta"
2316 (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
2317 , defFlag "optl"
2318 (hasArg addOptl)
2319 , defFlag "optwindres"
2320 (hasArg (\f ->
2321 alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
2322
2323 , defGhcFlag "split-objs"
2324 (NoArg (if can_split
2325 then setGeneralFlag Opt_SplitObjs
2326 else addWarn "ignoring -fsplit-objs"))
2327
2328 -------- ghc -M -----------------------------------------------------
2329 , defGhcFlag "dep-suffix" (hasArg addDepSuffix)
2330 , defGhcFlag "dep-makefile" (hasArg setDepMakefile)
2331 , defGhcFlag "include-pkg-deps" (noArg (setDepIncludePkgDeps True))
2332 , defGhcFlag "exclude-module" (hasArg addDepExcludeMod)
2333
2334 -------- Linking ----------------------------------------------------
2335 , defGhcFlag "no-link" (noArg (\d -> d{ ghcLink=NoLink }))
2336 , defGhcFlag "shared" (noArg (\d -> d{ ghcLink=LinkDynLib }))
2337 , defGhcFlag "staticlib" (noArg (\d -> d{ ghcLink=LinkStaticLib }))
2338 , defGhcFlag "dynload" (hasArg parseDynLibLoaderMode)
2339 , defGhcFlag "dylib-install-name" (hasArg setDylibInstallName)
2340 -- -dll-split is an internal flag, used only during the GHC build
2341 , defHiddenFlag "dll-split"
2342 (hasArg (\f d -> d{ dllSplitFile = Just f, dllSplit = Nothing }))
2343
2344 ------- Libraries ---------------------------------------------------
2345 , defFlag "L" (Prefix addLibraryPath)
2346 , defFlag "l" (hasArg (addLdInputs . Option . ("-l" ++)))
2347
2348 ------- Frameworks --------------------------------------------------
2349 -- -framework-path should really be -F ...
2350 , defFlag "framework-path" (HasArg addFrameworkPath)
2351 , defFlag "framework" (hasArg addCmdlineFramework)
2352
2353 ------- Output Redirection ------------------------------------------
2354 , defGhcFlag "odir" (hasArg setObjectDir)
2355 , defGhcFlag "o" (sepArg (setOutputFile . Just))
2356 , defGhcFlag "dyno" (sepArg (setDynOutputFile . Just))
2357 , defGhcFlag "ohi" (hasArg (setOutputHi . Just ))
2358 , defGhcFlag "osuf" (hasArg setObjectSuf)
2359 , defGhcFlag "dynosuf" (hasArg setDynObjectSuf)
2360 , defGhcFlag "hcsuf" (hasArg setHcSuf)
2361 , defGhcFlag "hisuf" (hasArg setHiSuf)
2362 , defGhcFlag "dynhisuf" (hasArg setDynHiSuf)
2363 , defGhcFlag "hidir" (hasArg setHiDir)
2364 , defGhcFlag "tmpdir" (hasArg setTmpDir)
2365 , defGhcFlag "stubdir" (hasArg setStubDir)
2366 , defGhcFlag "dumpdir" (hasArg setDumpDir)
2367 , defGhcFlag "outputdir" (hasArg setOutputDir)
2368 , defGhcFlag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just))
2369
2370 , defGhcFlag "dynamic-too" (NoArg (setGeneralFlag Opt_BuildDynamicToo))
2371
2372 ------- Keeping temporary files -------------------------------------
2373 -- These can be singular (think ghc -c) or plural (think ghc --make)
2374 , defGhcFlag "keep-hc-file" (NoArg (setGeneralFlag Opt_KeepHcFiles))
2375 , defGhcFlag "keep-hc-files" (NoArg (setGeneralFlag Opt_KeepHcFiles))
2376 , defGhcFlag "keep-s-file" (NoArg (setGeneralFlag Opt_KeepSFiles))
2377 , defGhcFlag "keep-s-files" (NoArg (setGeneralFlag Opt_KeepSFiles))
2378 , defGhcFlag "keep-llvm-file" (NoArg (do setObjTarget HscLlvm
2379 setGeneralFlag Opt_KeepLlvmFiles))
2380 , defGhcFlag "keep-llvm-files" (NoArg (do setObjTarget HscLlvm
2381 setGeneralFlag Opt_KeepLlvmFiles))
2382 -- This only makes sense as plural
2383 , defGhcFlag "keep-tmp-files" (NoArg (setGeneralFlag Opt_KeepTmpFiles))
2384
2385 ------- Miscellaneous ----------------------------------------------
2386 , defGhcFlag "no-auto-link-packages"
2387 (NoArg (unSetGeneralFlag Opt_AutoLinkPackages))
2388 , defGhcFlag "no-hs-main" (NoArg (setGeneralFlag Opt_NoHsMain))
2389 , defGhcFlag "with-rtsopts" (HasArg setRtsOpts)
2390 , defGhcFlag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll))
2391 , defGhcFlag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll))
2392 , defGhcFlag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
2393 , defGhcFlag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone))
2394 , defGhcFlag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone))
2395 , defGhcFlag "no-rtsopts-suggestions"
2396 (noArg (\d -> d {rtsOptsSuggestions = False} ))
2397 , defGhcFlag "main-is" (SepArg setMainIs)
2398 , defGhcFlag "haddock" (NoArg (setGeneralFlag Opt_Haddock))
2399 , defGhcFlag "haddock-opts" (hasArg addHaddockOpts)
2400 , defGhcFlag "hpcdir" (SepArg setOptHpcDir)
2401 , defGhciFlag "ghci-script" (hasArg addGhciScript)
2402 , defGhciFlag "interactive-print" (hasArg setInteractivePrint)
2403 , defGhcFlag "ticky-allocd" (NoArg (setGeneralFlag Opt_Ticky_Allocd))
2404 , defGhcFlag "ticky-LNE" (NoArg (setGeneralFlag Opt_Ticky_LNE))
2405 , defGhcFlag "ticky-dyn-thunk" (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk))
2406 ------- recompilation checker --------------------------------------
2407 , defGhcFlag "recomp" (NoArg (do unSetGeneralFlag Opt_ForceRecomp
2408 deprecate "Use -fno-force-recomp instead"))
2409 , defGhcFlag "no-recomp" (NoArg (do setGeneralFlag Opt_ForceRecomp
2410 deprecate "Use -fforce-recomp instead"))
2411
2412 ------ HsCpp opts ---------------------------------------------------
2413 , defFlag "D" (AnySuffix (upd . addOptP))
2414 , defFlag "U" (AnySuffix (upd . addOptP))
2415
2416 ------- Include/Import Paths ----------------------------------------
2417 , defFlag "I" (Prefix addIncludePath)
2418 , defFlag "i" (OptPrefix addImportPath)
2419
2420 ------ Output style options -----------------------------------------
2421 , defFlag "dppr-user-length" (intSuffix (\n d -> d{ pprUserLength = n }))
2422 , defFlag "dppr-cols" (intSuffix (\n d -> d{ pprCols = n }))
2423 , defGhcFlag "dtrace-level" (intSuffix (\n d -> d{ traceLevel = n }))
2424 -- Suppress all that is suppressable in core dumps.
2425 -- Except for uniques, as some simplifier phases introduce new varibles that
2426 -- have otherwise identical names.
2427 , defGhcFlag "dsuppress-all"
2428 (NoArg $ do setGeneralFlag Opt_SuppressCoercions
2429 setGeneralFlag Opt_SuppressVarKinds
2430 setGeneralFlag Opt_SuppressModulePrefixes
2431 setGeneralFlag Opt_SuppressTypeApplications
2432 setGeneralFlag Opt_SuppressIdInfo
2433 setGeneralFlag Opt_SuppressTypeSignatures)
2434
2435 ------ Debugging ----------------------------------------------------
2436 , defGhcFlag "dstg-stats" (NoArg (setGeneralFlag Opt_StgStats))
2437
2438 , defGhcFlag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm)
2439 , defGhcFlag "ddump-cmm-raw" (setDumpFlag Opt_D_dump_cmm_raw)
2440 , defGhcFlag "ddump-cmm-cfg" (setDumpFlag Opt_D_dump_cmm_cfg)
2441 , defGhcFlag "ddump-cmm-cbe" (setDumpFlag Opt_D_dump_cmm_cbe)
2442 , defGhcFlag "ddump-cmm-switch" (setDumpFlag Opt_D_dump_cmm_switch)
2443 , defGhcFlag "ddump-cmm-proc" (setDumpFlag Opt_D_dump_cmm_proc)
2444 , defGhcFlag "ddump-cmm-sink" (setDumpFlag Opt_D_dump_cmm_sink)
2445 , defGhcFlag "ddump-cmm-sp" (setDumpFlag Opt_D_dump_cmm_sp)
2446 , defGhcFlag "ddump-cmm-procmap" (setDumpFlag Opt_D_dump_cmm_procmap)
2447 , defGhcFlag "ddump-cmm-split" (setDumpFlag Opt_D_dump_cmm_split)
2448 , defGhcFlag "ddump-cmm-info" (setDumpFlag Opt_D_dump_cmm_info)
2449 , defGhcFlag "ddump-cmm-cps" (setDumpFlag Opt_D_dump_cmm_cps)
2450 , defGhcFlag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats)
2451 , defGhcFlag "ddump-asm" (setDumpFlag Opt_D_dump_asm)
2452 , defGhcFlag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native)
2453 , defGhcFlag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness)
2454 , defGhcFlag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc)
2455 , defGhcFlag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts)
2456 , defGhcFlag "ddump-asm-regalloc-stages"
2457 (setDumpFlag Opt_D_dump_asm_regalloc_stages)
2458 , defGhcFlag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats)
2459 , defGhcFlag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded)
2460 , defGhcFlag "ddump-llvm" (NoArg (do setObjTarget HscLlvm
2461 setDumpFlag' Opt_D_dump_llvm))
2462 , defGhcFlag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv)
2463 , defGhcFlag "ddump-ds" (setDumpFlag Opt_D_dump_ds)
2464 , defGhcFlag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign)
2465 , defGhcFlag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings)
2466 , defGhcFlag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings)
2467 , defGhcFlag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites)
2468 , defGhcFlag "ddump-simpl-trace" (setDumpFlag Opt_D_dump_simpl_trace)
2469 , defGhcFlag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal)
2470 , defGhcFlag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed)
2471 , defGhcFlag "ddump-rn" (setDumpFlag Opt_D_dump_rn)
2472 , defGhcFlag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl)
2473 , defGhcFlag "ddump-simpl-iterations"
2474 (setDumpFlag Opt_D_dump_simpl_iterations)
2475 , defGhcFlag "ddump-spec" (setDumpFlag Opt_D_dump_spec)
2476 , defGhcFlag "ddump-prep" (setDumpFlag Opt_D_dump_prep)
2477 , defGhcFlag "ddump-stg" (setDumpFlag Opt_D_dump_stg)
2478 , defGhcFlag "ddump-call-arity" (setDumpFlag Opt_D_dump_call_arity)
2479 , defGhcFlag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal)
2480 , defGhcFlag "ddump-strsigs" (setDumpFlag Opt_D_dump_strsigs)
2481 , defGhcFlag "ddump-tc" (setDumpFlag Opt_D_dump_tc)
2482 , defGhcFlag "ddump-types" (setDumpFlag Opt_D_dump_types)
2483 , defGhcFlag "ddump-rules" (setDumpFlag Opt_D_dump_rules)
2484 , defGhcFlag "ddump-cse" (setDumpFlag Opt_D_dump_cse)
2485 , defGhcFlag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper)
2486 , defGhcFlag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace)
2487 , defGhcFlag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace)
2488 , defGhcFlag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace)
2489 , defGhcFlag "ddump-tc-trace" (NoArg (do
2490 setDumpFlag' Opt_D_dump_tc_trace
2491 setDumpFlag' Opt_D_dump_cs_trace))
2492 , defGhcFlag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace)
2493 , defGhcFlag "ddump-splices" (setDumpFlag Opt_D_dump_splices)
2494 , defGhcFlag "dth-dec-file" (setDumpFlag Opt_D_th_dec_file)
2495
2496 , defGhcFlag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats)
2497 , defGhcFlag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm)
2498 , defGhcFlag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats)
2499 , defGhcFlag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs)
2500 , defGhcFlag "dsource-stats" (setDumpFlag Opt_D_source_stats)
2501 , defGhcFlag "dverbose-core2core" (NoArg (do setVerbosity (Just 2)
2502 setVerboseCore2Core))
2503 , defGhcFlag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg)
2504 , defGhcFlag "ddump-hi" (setDumpFlag Opt_D_dump_hi)
2505 , defGhcFlag "ddump-minimal-imports"
2506 (NoArg (setGeneralFlag Opt_D_dump_minimal_imports))
2507 , defGhcFlag "ddump-vect" (setDumpFlag Opt_D_dump_vect)
2508 , defGhcFlag "ddump-hpc"
2509 (setDumpFlag Opt_D_dump_ticked) -- back compat
2510 , defGhcFlag "ddump-ticked" (setDumpFlag Opt_D_dump_ticked)
2511 , defGhcFlag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles)
2512 , defGhcFlag "ddump-mod-map" (setDumpFlag Opt_D_dump_mod_map)
2513 , defGhcFlag "ddump-view-pattern-commoning"
2514 (setDumpFlag Opt_D_dump_view_pattern_commoning)
2515 , defGhcFlag "ddump-to-file" (NoArg (setGeneralFlag Opt_DumpToFile))
2516 , defGhcFlag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs)
2517 , defGhcFlag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti)
2518 , defGhcFlag "dcore-lint"
2519 (NoArg (setGeneralFlag Opt_DoCoreLinting))
2520 , defGhcFlag "dstg-lint"
2521 (NoArg (setGeneralFlag Opt_DoStgLinting))
2522 , defGhcFlag "dcmm-lint"
2523 (NoArg (setGeneralFlag Opt_DoCmmLinting))
2524 , defGhcFlag "dasm-lint"
2525 (NoArg (setGeneralFlag Opt_DoAsmLinting))
2526 , defGhcFlag "dannot-lint"
2527 (NoArg (setGeneralFlag Opt_DoAnnotationLinting))
2528 , defGhcFlag "dshow-passes" (NoArg (do forceRecompile
2529 setVerbosity $ Just 2))
2530 , defGhcFlag "dfaststring-stats"
2531 (NoArg (setGeneralFlag Opt_D_faststring_stats))
2532 , defGhcFlag "dno-llvm-mangler"
2533 (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag
2534 , defGhcFlag "ddump-debug" (setDumpFlag Opt_D_dump_debug)
2535
2536 ------ Machine dependant (-m<blah>) stuff ---------------------------
2537
2538 , defGhcFlag "msse" (noArg (\d -> d{ sseVersion = Just SSE1 }))
2539 , defGhcFlag "msse2" (noArg (\d -> d{ sseVersion = Just SSE2 }))
2540 , defGhcFlag "msse3" (noArg (\d -> d{ sseVersion = Just SSE3 }))
2541 , defGhcFlag "msse4" (noArg (\d -> d{ sseVersion = Just SSE4 }))
2542 , defGhcFlag "msse4.2" (noArg (\d -> d{ sseVersion = Just SSE42 }))
2543 , defGhcFlag "mavx" (noArg (\d -> d{ avx = True }))
2544 , defGhcFlag "mavx2" (noArg (\d -> d{ avx2 = True }))
2545 , defGhcFlag "mavx512cd" (noArg (\d -> d{ avx512cd = True }))
2546 , defGhcFlag "mavx512er" (noArg (\d -> d{ avx512er = True }))
2547 , defGhcFlag "mavx512f" (noArg (\d -> d{ avx512f = True }))
2548 , defGhcFlag "mavx512pf" (noArg (\d -> d{ avx512pf = True }))
2549
2550 ------ Warning opts -------------------------------------------------
2551 , defFlag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
2552 , defFlag "Werror" (NoArg (setGeneralFlag Opt_WarnIsError))
2553 , defFlag "Wwarn" (NoArg (unSetGeneralFlag Opt_WarnIsError))
2554 , defFlag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts))
2555 , defFlag "Wnot" (NoArg (do upd (\dfs -> dfs {warningFlags = IntSet.empty})
2556 deprecate "Use -w instead"))
2557 , defFlag "w" (NoArg (upd (\dfs -> dfs {warningFlags = IntSet.empty})))
2558
2559 ------ Plugin flags ------------------------------------------------
2560 , defGhcFlag "fplugin-opt" (hasArg addPluginModuleNameOption)
2561 , defGhcFlag "fplugin" (hasArg addPluginModuleName)
2562
2563 ------ Optimisation flags ------------------------------------------
2564 , defGhcFlag "O" (noArgM (setOptLevel 1))
2565 , defGhcFlag "Onot" (noArgM (\dflags -> do deprecate "Use -O0 instead"
2566 setOptLevel 0 dflags))
2567 , defGhcFlag "Odph" (noArgM setDPHOpt)
2568 , defGhcFlag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1)))
2569 -- If the number is missing, use 1
2570
2571
2572 , defFlag "fmax-relevant-binds"
2573 (intSuffix (\n d -> d{ maxRelevantBinds = Just n }))
2574 , defFlag "fno-max-relevant-binds"
2575 (noArg (\d -> d{ maxRelevantBinds = Nothing }))
2576 , defFlag "fsimplifier-phases"
2577 (intSuffix (\n d -> d{ simplPhases = n }))
2578 , defFlag "fmax-simplifier-iterations"
2579 (intSuffix (\n d -> d{ maxSimplIterations = n }))
2580 , defFlag "fsimpl-tick-factor"
2581 (intSuffix (\n d -> d{ simplTickFactor = n }))
2582 , defFlag "fspec-constr-threshold"
2583 (intSuffix (\n d -> d{ specConstrThreshold = Just n }))
2584 , defFlag "fno-spec-constr-threshold"
2585 (noArg (\d -> d{ specConstrThreshold = Nothing }))
2586 , defFlag "fspec-constr-count"
2587 (intSuffix (\n d -> d{ specConstrCount = Just n }))
2588 , defFlag "fno-spec-constr-count"
2589 (noArg (\d -> d{ specConstrCount = Nothing }))
2590 , defFlag "fspec-constr-recursive"
2591 (intSuffix (\n d -> d{ specConstrRecursive = n }))
2592 , defFlag "fliberate-case-threshold"
2593 (intSuffix (\n d -> d{ liberateCaseThreshold = Just n }))
2594 , defFlag "fno-liberate-case-threshold"
2595 (noArg (\d -> d{ liberateCaseThreshold = Nothing }))
2596 , defFlag "frule-check"
2597 (sepArg (\s d -> d{ ruleCheck = Just s }))
2598 , defFlag "freduction-depth"
2599 (intSuffix (\n d -> d{ reductionDepth = treatZeroAsInf n }))
2600 , defFlag "fconstraint-solver-iterations"
2601 (intSuffix (\n d -> d{ solverIterations = treatZeroAsInf n }))
2602 , defFlag "fcontext-stack"
2603 (intSuffixM (\n d ->
2604 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
2605 ; return $ d{ reductionDepth = treatZeroAsInf n } }))
2606 , defFlag "ftype-function-depth"
2607 (intSuffixM (\n d ->
2608 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
2609 ; return $ d{ reductionDepth = treatZeroAsInf n } }))
2610 , defFlag "fstrictness-before"
2611 (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d }))
2612 , defFlag "ffloat-lam-args"
2613 (intSuffix (\n d -> d{ floatLamArgs = Just n }))
2614 , defFlag "ffloat-all-lams"
2615 (noArg (\d -> d{ floatLamArgs = Nothing }))
2616
2617 , defFlag "fhistory-size" (intSuffix (\n d -> d{ historySize = n }))
2618
2619 , defFlag "funfolding-creation-threshold"
2620 (intSuffix (\n d -> d {ufCreationThreshold = n}))
2621 , defFlag "funfolding-use-threshold"
2622 (intSuffix (\n d -> d {ufUseThreshold = n}))
2623 , defFlag "funfolding-fun-discount"
2624 (intSuffix (\n d -> d {ufFunAppDiscount = n}))
2625 , defFlag "funfolding-dict-discount"
2626 (intSuffix (\n d -> d {ufDictDiscount = n}))
2627 , defFlag "funfolding-keeness-factor"
2628 (floatSuffix (\n d -> d {ufKeenessFactor = n}))
2629
2630 , defFlag "fmax-worker-args" (intSuffix (\n d -> d {maxWorkerArgs = n}))
2631
2632 , defGhciFlag "fghci-hist-size" (intSuffix (\n d -> d {ghciHistSize = n}))
2633 , defGhcFlag "fmax-inline-alloc-size"
2634 (intSuffix (\n d -> d{ maxInlineAllocSize = n }))
2635 , defGhcFlag "fmax-inline-memcpy-insns"
2636 (intSuffix (\n d -> d{ maxInlineMemcpyInsns = n }))
2637 , defGhcFlag "fmax-inline-memset-insns"
2638 (intSuffix (\n d -> d{ maxInlineMemsetInsns = n }))
2639
2640 ------ Profiling ----------------------------------------------------
2641
2642 -- OLD profiling flags
2643 , defGhcFlag "auto-all" (noArg (\d -> d { profAuto = ProfAutoAll } ))
2644 , defGhcFlag "no-auto-all" (noArg (\d -> d { profAuto = NoProfAuto } ))
2645 , defGhcFlag "auto" (noArg (\d -> d { profAuto = ProfAutoExports } ))
2646 , defGhcFlag "no-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
2647 , defGhcFlag "caf-all"
2648 (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs))
2649 , defGhcFlag "no-caf-all"
2650 (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs))
2651
2652 -- NEW profiling flags
2653 , defGhcFlag "fprof-auto"
2654 (noArg (\d -> d { profAuto = ProfAutoAll } ))
2655 , defGhcFlag "fprof-auto-top"
2656 (noArg (\d -> d { profAuto = ProfAutoTop } ))
2657 , defGhcFlag "fprof-auto-exported"
2658 (noArg (\d -> d { profAuto = ProfAutoExports } ))
2659 , defGhcFlag "fprof-auto-calls"
2660 (noArg (\d -> d { profAuto = ProfAutoCalls } ))
2661 , defGhcFlag "fno-prof-auto"
2662 (noArg (\d -> d { profAuto = NoProfAuto } ))
2663
2664 ------ Compiler flags -----------------------------------------------
2665
2666 , defGhcFlag "fasm" (NoArg (setObjTarget HscAsm))
2667 , defGhcFlag "fvia-c" (NoArg
2668 (addWarn $ "The -fvia-c flag does nothing; " ++
2669 "it will be removed in a future GHC release"))
2670 , defGhcFlag "fvia-C" (NoArg
2671 (addWarn $ "The -fvia-C flag does nothing; " ++
2672 "it will be removed in a future GHC release"))
2673 , defGhcFlag "fllvm" (NoArg (setObjTarget HscLlvm))
2674
2675 , defFlag "fno-code" (NoArg (do upd $ \d -> d{ ghcLink=NoLink }
2676 setTarget HscNothing))
2677 , defFlag "fbyte-code" (NoArg (setTarget HscInterpreted))
2678 , defFlag "fobject-code" (NoArg (setTargetWithPlatform defaultHscTarget))
2679 , defFlag "fglasgow-exts"
2680 (NoArg (do enableGlasgowExts
2681 deprecate "Use individual extensions instead"))
2682 , defFlag "fno-glasgow-exts"
2683 (NoArg (do disableGlasgowExts
2684 deprecate "Use individual extensions instead"))
2685 , defFlag "fwarn-unused-binds" (NoArg enableUnusedBinds)
2686 , defFlag "fno-warn-unused-binds" (NoArg disableUnusedBinds)
2687
2688 ------ Safe Haskell flags -------------------------------------------
2689 , defFlag "fpackage-trust" (NoArg setPackageTrust)
2690 , defFlag "fno-safe-infer" (noArg (\d -> d { safeInfer = False } ))
2691 , defGhcFlag "fPIC" (NoArg (setGeneralFlag Opt_PIC))
2692 , defGhcFlag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC))
2693
2694 ------ Debugging flags ----------------------------------------------
2695 , defGhcFlag "g" (NoArg (setGeneralFlag Opt_Debug))
2696 ]
2697 ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlags
2698 ++ map (mkFlag turnOff "no-" unSetGeneralFlag) negatableFlags
2699 ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlags
2700 ++ map (mkFlag turnOff "dno-" unSetGeneralFlag) dFlags
2701 ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlags
2702 ++ map (mkFlag turnOff "fno-" unSetGeneralFlag) fFlags
2703 ++ map (mkFlag turnOn "f" setWarningFlag ) fWarningFlags
2704 ++ map (mkFlag turnOff "fno-" unSetWarningFlag) fWarningFlags
2705 ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlags
2706 ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags
2707 ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlags
2708 ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlags
2709 ++ map (mkFlag turnOn "X" setLanguage) languageFlags
2710 ++ map (mkFlag turnOn "X" setSafeHaskell) safeHaskellFlags
2711 ++ [ defFlag "XGenerics"
2712 (NoArg (deprecate $
2713 "it does nothing; look into -XDefaultSignatures " ++
2714 "and -XDeriveGeneric for generic programming support."))
2715 , defFlag "XNoGenerics"
2716 (NoArg (deprecate $
2717 "it does nothing; look into -XDefaultSignatures and " ++
2718 "-XDeriveGeneric for generic programming support.")) ]
2719
2720 -- See Note [Supporting CLI completion]
2721 package_flags :: [Flag (CmdLineP DynFlags)]
2722 package_flags = [
2723 ------- Packages ----------------------------------------------------
2724 defFlag "package-db" (HasArg (addPkgConfRef . PkgConfFile))
2725 , defFlag "clear-package-db" (NoArg clearPkgConf)
2726 , defFlag "no-global-package-db" (NoArg removeGlobalPkgConf)
2727 , defFlag "no-user-package-db" (NoArg removeUserPkgConf)
2728 , defFlag "global-package-db" (NoArg (addPkgConfRef GlobalPkgConf))
2729 , defFlag "user-package-db" (NoArg (addPkgConfRef UserPkgConf))
2730
2731 -- backwards compat with GHC<=7.4 :
2732 , defFlag "package-conf" (HasArg $ \path -> do
2733 addPkgConfRef (PkgConfFile path)
2734 deprecate "Use -package-db instead")
2735 , defFlag "no-user-package-conf"
2736 (NoArg $ do removeUserPkgConf
2737 deprecate "Use -no-user-package-db instead")
2738
2739 , defGhcFlag "package-name" (HasArg $ \name -> do
2740 upd (setPackageKey name)
2741 deprecate "Use -this-package-key instead")
2742 , defGhcFlag "this-package-key" (hasArg setPackageKey)
2743 , defFlag "package-id" (HasArg exposePackageId)
2744 , defFlag "package" (HasArg exposePackage)
2745 , defFlag "package-key" (HasArg exposePackageKey)
2746 , defFlag "hide-package" (HasArg hidePackage)
2747 , defFlag "hide-all-packages" (NoArg (setGeneralFlag Opt_HideAllPackages))
2748 , defFlag "package-env" (HasArg setPackageEnv)
2749 , defFlag "ignore-package" (HasArg ignorePackage)
2750 , defFlag "syslib"
2751 (HasArg (\s -> do exposePackage s
2752 deprecate "Use -package instead"))
2753 , defFlag "distrust-all-packages"
2754 (NoArg (setGeneralFlag Opt_DistrustAllPackages))
2755 , defFlag "trust" (HasArg trustPackage)
2756 , defFlag "distrust" (HasArg distrustPackage)
2757 ]
2758 where
2759 setPackageEnv env = upd $ \s -> s { packageEnv = Just env }
2760
2761 -- | Make a list of flags for shell completion.
2762 -- Filter all available flags into two groups, for interactive GHC vs all other.
2763 flagsForCompletion :: Bool -> [String]
2764 flagsForCompletion isInteractive
2765 = [ '-':flagName flag
2766 | flag <- flagsAll
2767 , modeFilter (flagGhcMode flag)
2768 ]
2769 where
2770 modeFilter AllModes = True
2771 modeFilter OnlyGhci = isInteractive
2772 modeFilter OnlyGhc = not isInteractive
2773 modeFilter HiddenFlag = False
2774
2775 type TurnOnFlag = Bool -- True <=> we are turning the flag on
2776 -- False <=> we are turning the flag off
2777 turnOn :: TurnOnFlag; turnOn = True
2778 turnOff :: TurnOnFlag; turnOff = False
2779
2780 data FlagSpec flag
2781 = FlagSpec
2782 { flagSpecName :: String -- ^ Flag in string form
2783 , flagSpecFlag :: flag -- ^ Flag in internal form
2784 , flagSpecAction :: (TurnOnFlag -> DynP ())
2785 -- ^ Extra action to run when the flag is found
2786 -- Typically, emit a warning or error
2787 , flagSpecGhcMode :: GhcFlagMode
2788 -- ^ In which ghc mode the flag has effect
2789 }
2790
2791 -- | Define a new flag.
2792 flagSpec :: String -> flag -> FlagSpec flag
2793 flagSpec name flag = flagSpec' name flag nop
2794
2795 -- | Define a new flag with an effect.
2796 flagSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> FlagSpec flag
2797 flagSpec' name flag act = FlagSpec name flag act AllModes
2798
2799 -- | Define a new flag for GHCi.
2800 flagGhciSpec :: String -> flag -> FlagSpec flag
2801 flagGhciSpec name flag = flagGhciSpec' name flag nop
2802
2803 -- | Define a new flag for GHCi with an effect.
2804 flagGhciSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> FlagSpec flag
2805 flagGhciSpec' name flag act = FlagSpec name flag act OnlyGhci
2806
2807 -- | Define a new flag invisible to CLI completion.
2808 flagHiddenSpec :: String -> flag -> FlagSpec flag
2809 flagHiddenSpec name flag = flagHiddenSpec' name flag nop
2810
2811 -- | Define a new flag invisible to CLI completion with an effect.
2812 flagHiddenSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> FlagSpec flag
2813 flagHiddenSpec' name flag act = FlagSpec name flag act HiddenFlag
2814
2815 mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on
2816 -> String -- ^ The flag prefix
2817 -> (flag -> DynP ()) -- ^ What to do when the flag is found
2818 -> FlagSpec flag -- ^ Specification of this particular flag
2819 -> Flag (CmdLineP DynFlags)
2820 mkFlag turn_on flagPrefix f (FlagSpec name flag extra_action mode)
2821 = Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on)) mode
2822
2823 deprecatedForExtension :: String -> TurnOnFlag -> DynP ()
2824 deprecatedForExtension lang turn_on
2825 = deprecate ("use -X" ++ flag ++
2826 " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead")
2827 where
2828 flag | turn_on = lang
2829 | otherwise = "No"++lang
2830
2831 useInstead :: String -> TurnOnFlag -> DynP ()
2832 useInstead flag turn_on
2833 = deprecate ("Use -f" ++ no ++ flag ++ " instead")
2834 where
2835 no = if turn_on then "" else "no-"
2836
2837 nop :: TurnOnFlag -> DynP ()
2838 nop _ = return ()
2839
2840 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
2841 fWarningFlags :: [FlagSpec WarningFlag]
2842 fWarningFlags = [
2843 -- See Note [Updating flag description in the User's Guide]
2844 -- See Note [Supporting CLI completion]
2845 -- Please keep the list of flags below sorted alphabetically
2846 flagSpec "warn-alternative-layout-rule-transitional"
2847 Opt_WarnAlternativeLayoutRuleTransitional,
2848 flagSpec' "warn-amp" Opt_WarnAMP
2849 (\_ -> deprecate "it has no effect, and will be removed in GHC 7.12"),
2850 flagSpec "warn-auto-orphans" Opt_WarnAutoOrphans,
2851 flagSpec "warn-deprecations" Opt_WarnWarningsDeprecations,
2852 flagSpec "warn-deprecated-flags" Opt_WarnDeprecatedFlags,
2853 flagSpec "warn-deriving-typeable" Opt_WarnDerivingTypeable,
2854 flagSpec "warn-dodgy-exports" Opt_WarnDodgyExports,
2855 flagSpec "warn-dodgy-foreign-imports" Opt_WarnDodgyForeignImports,
2856 flagSpec "warn-dodgy-imports" Opt_WarnDodgyImports,
2857 flagSpec "warn-empty-enumerations" Opt_WarnEmptyEnumerations,
2858 flagSpec "warn-context-quantification" Opt_WarnContextQuantification,
2859 flagSpec' "warn-duplicate-constraints" Opt_WarnDuplicateConstraints
2860 (\_ -> deprecate "it is subsumed by -fwarn-redundant-constraints"),
2861 flagSpec "warn-redundant-constraints" Opt_WarnRedundantConstraints,
2862 flagSpec "warn-duplicate-exports" Opt_WarnDuplicateExports,
2863 flagSpec "warn-hi-shadowing" Opt_WarnHiShadows,
2864 flagSpec "warn-implicit-prelude" Opt_WarnImplicitPrelude,
2865 flagSpec "warn-incomplete-patterns" Opt_WarnIncompletePatterns,
2866 flagSpec "warn-incomplete-record-updates" Opt_WarnIncompletePatternsRecUpd,
2867 flagSpec "warn-incomplete-uni-patterns" Opt_WarnIncompleteUniPatterns,
2868 flagSpec "warn-inline-rule-shadowing" Opt_WarnInlineRuleShadowing,
2869 flagSpec "warn-identities" Opt_WarnIdentities,
2870 flagSpec "warn-missing-fields" Opt_WarnMissingFields,
2871 flagSpec "warn-missing-import-lists" Opt_WarnMissingImportList,
2872 flagSpec "warn-missing-local-sigs" Opt_WarnMissingLocalSigs,
2873 flagSpec "warn-missing-methods" Opt_WarnMissingMethods,
2874 flagSpec "warn-missing-signatures" Opt_WarnMissingSigs,
2875 flagSpec "warn-missing-exported-sigs" Opt_WarnMissingExportedSigs,
2876 flagSpec "warn-monomorphism-restriction" Opt_WarnMonomorphism,
2877 flagSpec "warn-name-shadowing" Opt_WarnNameShadowing,
2878 flagSpec "warn-orphans" Opt_WarnOrphans,
2879 flagSpec "warn-overflowed-literals" Opt_WarnOverflowedLiterals,
2880 flagSpec "warn-overlapping-patterns" Opt_WarnOverlappingPatterns,
2881 flagSpec "warn-pointless-pragmas" Opt_WarnPointlessPragmas,
2882 flagSpec' "warn-safe" Opt_WarnSafe setWarnSafe,
2883 flagSpec "warn-trustworthy-safe" Opt_WarnTrustworthySafe,
2884 flagSpec "warn-tabs" Opt_WarnTabs,
2885 flagSpec "warn-type-defaults" Opt_WarnTypeDefaults,
2886 flagSpec "warn-typed-holes" Opt_WarnTypedHoles,
2887 flagSpec "warn-partial-type-signatures" Opt_WarnPartialTypeSignatures,
2888 flagSpec "warn-unrecognised-pragmas" Opt_WarnUnrecognisedPragmas,
2889 flagSpec' "warn-unsafe" Opt_WarnUnsafe setWarnUnsafe,
2890 flagSpec "warn-unsupported-calling-conventions"
2891 Opt_WarnUnsupportedCallingConventions,
2892 flagSpec "warn-unsupported-llvm-version" Opt_WarnUnsupportedLlvmVersion,
2893 flagSpec "warn-unticked-promoted-constructors"
2894 Opt_WarnUntickedPromotedConstructors,
2895 flagSpec "warn-unused-do-bind" Opt_WarnUnusedDoBind,
2896 flagSpec "warn-unused-imports" Opt_WarnUnusedImports,
2897 flagSpec "warn-unused-local-binds" Opt_WarnUnusedLocalBinds,
2898 flagSpec "warn-unused-matches" Opt_WarnUnusedMatches,
2899 flagSpec "warn-unused-pattern-binds" Opt_WarnUnusedPatternBinds,
2900 flagSpec "warn-unused-top-binds" Opt_WarnUnusedTopBinds,
2901 flagSpec "warn-warnings-deprecations" Opt_WarnWarningsDeprecations,
2902 flagSpec "warn-wrong-do-bind" Opt_WarnWrongDoBind]
2903
2904 -- | These @-\<blah\>@ flags can all be reversed with @-no-\<blah\>@
2905 negatableFlags :: [FlagSpec GeneralFlag]
2906 negatableFlags = [
2907 flagGhciSpec "ignore-dot-ghci" Opt_IgnoreDotGhci ]
2908
2909 -- | These @-d\<blah\>@ flags can all be reversed with @-dno-\<blah\>@
2910 dFlags :: [FlagSpec GeneralFlag]
2911 dFlags = [
2912 -- See Note [Updating flag description in the User's Guide]
2913 -- See Note [Supporting CLI completion]
2914 -- Please keep the list of flags below sorted alphabetically
2915 flagSpec "ppr-case-as-let" Opt_PprCaseAsLet,
2916 flagSpec "ppr-ticks" Opt_PprShowTicks,
2917 flagSpec "suppress-coercions" Opt_SuppressCoercions,
2918 flagSpec "suppress-idinfo" Opt_SuppressIdInfo,
2919 flagSpec "suppress-module-prefixes" Opt_SuppressModulePrefixes,
2920 flagSpec "suppress-type-applications" Opt_SuppressTypeApplications,
2921 flagSpec "suppress-type-signatures" Opt_SuppressTypeSignatures,
2922 flagSpec "suppress-uniques" Opt_SuppressUniques,
2923 flagSpec "suppress-var-kinds" Opt_SuppressVarKinds]
2924
2925 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
2926 fFlags :: [FlagSpec GeneralFlag]
2927 fFlags = [
2928 -- See Note [Updating flag description in the User's Guide]
2929 -- See Note [Supporting CLI completion]
2930 -- Please keep the list of flags below sorted alphabetically
2931 flagGhciSpec "break-on-error" Opt_BreakOnError,
2932 flagGhciSpec "break-on-exception" Opt_BreakOnException,
2933 flagSpec "building-cabal-package" Opt_BuildingCabalPackage,
2934 flagSpec "call-arity" Opt_CallArity,
2935 flagSpec "case-merge" Opt_CaseMerge,
2936 flagSpec "cmm-elim-common-blocks" Opt_CmmElimCommonBlocks,
2937 flagSpec "cmm-sink" Opt_CmmSink,
2938 flagSpec "cse" Opt_CSE,
2939 flagSpec "defer-type-errors" Opt_DeferTypeErrors,
2940 flagSpec "defer-typed-holes" Opt_DeferTypedHoles,
2941 flagSpec "dicts-cheap" Opt_DictsCheap,
2942 flagSpec "dicts-strict" Opt_DictsStrict,
2943 flagSpec "dmd-tx-dict-sel" Opt_DmdTxDictSel,
2944 flagSpec "do-eta-reduction" Opt_DoEtaReduction,
2945 flagSpec "do-lambda-eta-expansion" Opt_DoLambdaEtaExpansion,
2946 flagSpec "eager-blackholing" Opt_EagerBlackHoling,
2947 flagSpec "embed-manifest" Opt_EmbedManifest,
2948 flagSpec "enable-rewrite-rules" Opt_EnableRewriteRules,
2949 flagSpec "error-spans" Opt_ErrorSpans,
2950 flagSpec "excess-precision" Opt_ExcessPrecision,
2951 flagSpec "expose-all-unfoldings" Opt_ExposeAllUnfoldings,
2952 flagSpec "flat-cache" Opt_FlatCache,
2953 flagSpec "float-in" Opt_FloatIn,
2954 flagSpec "force-recomp" Opt_ForceRecomp,
2955 flagSpec "full-laziness" Opt_FullLaziness,
2956 flagSpec "fun-to-thunk" Opt_FunToThunk,
2957 flagSpec "gen-manifest" Opt_GenManifest,
2958 flagSpec "ghci-history" Opt_GhciHistory,
2959 flagSpec "ghci-sandbox" Opt_GhciSandbox,
2960 flagSpec "helpful-errors" Opt_HelpfulErrors,
2961 flagSpec "hpc" Opt_Hpc,
2962 flagSpec "ignore-asserts" Opt_IgnoreAsserts,
2963 flagSpec "ignore-interface-pragmas" Opt_IgnoreInterfacePragmas,
2964 flagGhciSpec "implicit-import-qualified" Opt_ImplicitImportQualified,
2965 flagSpec "irrefutable-tuples" Opt_IrrefutableTuples,
2966 flagSpec "kill-absence" Opt_KillAbsence,
2967 flagSpec "kill-one-shot" Opt_KillOneShot,
2968 flagSpec "late-dmd-anal" Opt_LateDmdAnal,
2969 flagSpec "liberate-case" Opt_LiberateCase,
2970 flagHiddenSpec "llvm-pass-vectors-in-regs" Opt_LlvmPassVectorsInRegisters,
2971 flagHiddenSpec "llvm-tbaa" Opt_LlvmTBAA,
2972 flagSpec "loopification" Opt_Loopification,
2973 flagSpec "omit-interface-pragmas" Opt_OmitInterfacePragmas,
2974 flagSpec "omit-yields" Opt_OmitYields,
2975 flagSpec "pedantic-bottoms" Opt_PedanticBottoms,
2976 flagSpec "pre-inlining" Opt_SimplPreInlining,
2977 flagGhciSpec "print-bind-contents" Opt_PrintBindContents,
2978 flagGhciSpec "print-bind-result" Opt_PrintBindResult,
2979 flagGhciSpec "print-evld-with-show" Opt_PrintEvldWithShow,
2980 flagSpec "print-explicit-foralls" Opt_PrintExplicitForalls,
2981 flagSpec "print-explicit-kinds" Opt_PrintExplicitKinds,
2982 flagSpec "print-unicode-syntax" Opt_PrintUnicodeSyntax,
2983 flagSpec "prof-cafs" Opt_AutoSccsOnIndividualCafs,
2984 flagSpec "prof-count-entries" Opt_ProfCountEntries,
2985 flagSpec "regs-graph" Opt_RegsGraph,
2986 flagSpec "regs-iterative" Opt_RegsIterative,
2987 flagSpec' "rewrite-rules" Opt_EnableRewriteRules
2988 (useInstead "enable-rewrite-rules"),
2989 flagSpec "shared-implib" Opt_SharedImplib,
2990 flagSpec "simple-list-literals" Opt_SimpleListLiterals,
2991 flagSpec "spec-constr" Opt_SpecConstr,
2992 flagSpec "specialise" Opt_Specialise,
2993 flagSpec "specialise-aggressively" Opt_SpecialiseAggressively,
2994 flagSpec "cross-module-specialise" Opt_CrossModuleSpecialise,
2995 flagSpec "static-argument-transformation" Opt_StaticArgumentTransformation,
2996 flagSpec "strictness" Opt_Strictness,
2997 flagSpec "use-rpaths" Opt_RPath,
2998 flagSpec "write-interface" Opt_WriteInterface,
2999 flagSpec "unbox-small-strict-fields" Opt_UnboxSmallStrictFields,
3000 flagSpec "unbox-strict-fields" Opt_UnboxStrictFields,
3001 flagSpec "vectorisation-avoidance" Opt_VectorisationAvoidance,
3002 flagSpec "vectorise" Opt_Vectorise
3003 ]
3004
3005 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
3006 fLangFlags :: [FlagSpec ExtensionFlag]
3007 fLangFlags = [
3008 -- See Note [Updating flag description in the User's Guide]
3009 -- See Note [Supporting CLI completion]
3010 flagSpec' "th" Opt_TemplateHaskell
3011 (\on -> deprecatedForExtension "TemplateHaskell" on
3012 >> setTemplateHaskellLoc on),
3013 flagSpec' "fi" Opt_ForeignFunctionInterface
3014 (deprecatedForExtension "ForeignFunctionInterface"),
3015 flagSpec' "ffi" Opt_ForeignFunctionInterface
3016 (deprecatedForExtension "ForeignFunctionInterface"),
3017 flagSpec' "arrows" Opt_Arrows
3018 (deprecatedForExtension "Arrows"),
3019 flagSpec' "implicit-prelude" Opt_ImplicitPrelude
3020 (deprecatedForExtension "ImplicitPrelude"),
3021 flagSpec' "bang-patterns" Opt_BangPatterns
3022 (deprecatedForExtension "BangPatterns"),
3023 flagSpec' "monomorphism-restriction" Opt_MonomorphismRestriction
3024 (deprecatedForExtension "MonomorphismRestriction"),
3025 flagSpec' "mono-pat-binds" Opt_MonoPatBinds
3026 (deprecatedForExtension "MonoPatBinds"),
3027 flagSpec' "extended-default-rules" Opt_ExtendedDefaultRules
3028 (deprecatedForExtension "ExtendedDefaultRules"),
3029 flagSpec' "implicit-params" Opt_ImplicitParams
3030 (deprecatedForExtension "ImplicitParams"),
3031 flagSpec' "scoped-type-variables" Opt_ScopedTypeVariables
3032 (deprecatedForExtension "ScopedTypeVariables"),
3033 flagSpec' "parr" Opt_ParallelArrays
3034 (deprecatedForExtension "ParallelArrays"),
3035 flagSpec' "PArr" Opt_ParallelArrays
3036 (deprecatedForExtension "ParallelArrays"),
3037 flagSpec' "allow-overlapping-instances" Opt_OverlappingInstances
3038 (deprecatedForExtension "OverlappingInstances"),
3039 flagSpec' "allow-undecidable-instances" Opt_UndecidableInstances
3040 (deprecatedForExtension "UndecidableInstances"),
3041 flagSpec' "allow-incoherent-instances" Opt_IncoherentInstances
3042 (deprecatedForExtension "IncoherentInstances")
3043 ]
3044
3045 supportedLanguages :: [String]
3046 supportedLanguages = map flagSpecName languageFlags
3047
3048 supportedLanguageOverlays :: [String]
3049 supportedLanguageOverlays = map flagSpecName safeHaskellFlags
3050
3051 supportedExtensions :: [String]
3052 supportedExtensions
3053 = concatMap (\name -> [name, "No" ++ name]) (map flagSpecName xFlags)
3054
3055 supportedLanguagesAndExtensions :: [String]
3056 supportedLanguagesAndExtensions =
3057 supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions
3058
3059 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
3060 languageFlags :: [FlagSpec Language]
3061 languageFlags = [
3062 flagSpec "Haskell98" Haskell98,
3063 flagSpec "Haskell2010" Haskell2010
3064 ]
3065
3066 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
3067 -- They are used to place hard requirements on what GHC Haskell language
3068 -- features can be used.
3069 safeHaskellFlags :: [FlagSpec SafeHaskellMode]
3070 safeHaskellFlags = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe]
3071 where mkF flag = flagSpec (show flag) flag
3072
3073 -- | These -X<blah> flags can all be reversed with -XNo<blah>
3074 xFlags :: [FlagSpec ExtensionFlag]
3075 xFlags = [
3076 -- See Note [Updating flag description in the User's Guide]
3077 -- See Note [Supporting CLI completion]
3078 -- Please keep the list of flags below sorted alphabetically
3079 flagSpec "AllowAmbiguousTypes" Opt_AllowAmbiguousTypes,
3080 flagSpec "AlternativeLayoutRule" Opt_AlternativeLayoutRule,
3081 flagSpec "AlternativeLayoutRuleTransitional"
3082 Opt_AlternativeLayoutRuleTransitional,
3083 flagSpec "Arrows" Opt_Arrows,
3084 flagSpec "AutoDeriveTypeable" Opt_AutoDeriveTypeable,
3085 flagSpec "BangPatterns" Opt_BangPatterns,
3086 flagSpec "BinaryLiterals" Opt_BinaryLiterals,
3087 flagSpec "CApiFFI" Opt_CApiFFI,
3088 flagSpec "CPP" Opt_Cpp,
3089 flagSpec "ConstrainedClassMethods" Opt_ConstrainedClassMethods,
3090 flagSpec "ConstraintKinds" Opt_ConstraintKinds,
3091 flagSpec "DataKinds" Opt_DataKinds,
3092 flagSpec' "DatatypeContexts" Opt_DatatypeContexts
3093 (\ turn_on -> when turn_on $
3094 deprecate $ "It was widely considered a misfeature, " ++
3095 "and has been removed from the Haskell language."),
3096 flagSpec "DefaultSignatures" Opt_DefaultSignatures,
3097 flagSpec "DeriveAnyClass" Opt_DeriveAnyClass,
3098 flagSpec "DeriveDataTypeable" Opt_DeriveDataTypeable,
3099 flagSpec "DeriveFoldable" Opt_DeriveFoldable,
3100 flagSpec "DeriveFunctor" Opt_DeriveFunctor,
3101 flagSpec "DeriveGeneric" Opt_DeriveGeneric,
3102 flagSpec "DeriveTraversable" Opt_DeriveTraversable,
3103 flagSpec "DisambiguateRecordFields" Opt_DisambiguateRecordFields,
3104 flagSpec "DoAndIfThenElse" Opt_DoAndIfThenElse,
3105 flagSpec' "DoRec" Opt_RecursiveDo
3106 (deprecatedForExtension "RecursiveDo"),
3107 flagSpec "EmptyCase" Opt_EmptyCase,
3108 flagSpec "EmptyDataDecls" Opt_EmptyDataDecls,
3109 flagSpec "ExistentialQuantification" Opt_ExistentialQuantification,
3110 flagSpec "ExplicitForAll" Opt_ExplicitForAll,
3111 flagSpec "ExplicitNamespaces" Opt_ExplicitNamespaces,
3112 flagSpec "ExtendedDefaultRules" Opt_ExtendedDefaultRules,
3113 flagSpec "FlexibleContexts" Opt_FlexibleContexts,
3114 flagSpec "FlexibleInstances" Opt_FlexibleInstances,
3115 flagSpec "ForeignFunctionInterface" Opt_ForeignFunctionInterface,
3116 flagSpec "FunctionalDependencies" Opt_FunctionalDependencies,
3117 flagSpec "GADTSyntax" Opt_GADTSyntax,
3118 flagSpec "GADTs" Opt_GADTs,
3119 flagSpec "GHCForeignImportPrim" Opt_GHCForeignImportPrim,
3120 flagSpec' "GeneralizedNewtypeDeriving" Opt_GeneralizedNewtypeDeriving
3121 setGenDeriving,
3122 flagSpec "ImplicitParams" Opt_ImplicitParams,
3123 flagSpec "ImplicitPrelude" Opt_ImplicitPrelude,
3124 flagSpec "ImpredicativeTypes" Opt_ImpredicativeTypes,
3125 flagSpec' "IncoherentInstances" Opt_IncoherentInstances
3126 setIncoherentInsts,
3127 flagSpec "InstanceSigs" Opt_InstanceSigs,
3128 flagSpec "InterruptibleFFI" Opt_InterruptibleFFI,
3129 flagSpec "JavaScriptFFI" Opt_JavaScriptFFI,
3130 flagSpec "KindSignatures" Opt_KindSignatures,
3131 flagSpec "LambdaCase" Opt_LambdaCase,
3132 flagSpec "LiberalTypeSynonyms" Opt_LiberalTypeSynonyms,
3133 flagSpec "MagicHash" Opt_MagicHash,
3134 flagSpec "MonadComprehensions" Opt_MonadComprehensions,
3135 flagSpec "MonoLocalBinds" Opt_MonoLocalBinds,
3136 flagSpec' "MonoPatBinds" Opt_MonoPatBinds
3137 (\ turn_on -> when turn_on $
3138 deprecate "Experimental feature now removed; has no effect"),
3139 flagSpec "MonomorphismRestriction" Opt_MonomorphismRestriction,
3140 flagSpec "MultiParamTypeClasses" Opt_MultiParamTypeClasses,
3141 flagSpec "MultiWayIf" Opt_MultiWayIf,
3142 flagSpec "NPlusKPatterns" Opt_NPlusKPatterns,
3143 flagSpec "NamedFieldPuns" Opt_RecordPuns,
3144 flagSpec "NamedWildCards" Opt_NamedWildCards,
3145 flagSpec "NegativeLiterals" Opt_NegativeLiterals,
3146 flagSpec "NondecreasingIndentation" Opt_NondecreasingIndentation,
3147 flagSpec' "NullaryTypeClasses" Opt_NullaryTypeClasses
3148 (deprecatedForExtension "MultiParamTypeClasses"),
3149 flagSpec "NumDecimals" Opt_NumDecimals,
3150 flagSpec' "OverlappingInstances" Opt_OverlappingInstances
3151 setOverlappingInsts,
3152 flagSpec "OverloadedLists" Opt_OverloadedLists,
3153 flagSpec "OverloadedStrings" Opt_OverloadedStrings,
3154 flagSpec "PackageImports" Opt_PackageImports,
3155 flagSpec "ParallelArrays" Opt_ParallelArrays,
3156 flagSpec "ParallelListComp" Opt_ParallelListComp,
3157 flagSpec "PartialTypeSignatures" Opt_PartialTypeSignatures,
3158 flagSpec "PatternGuards" Opt_PatternGuards,
3159 flagSpec' "PatternSignatures" Opt_ScopedTypeVariables
3160 (deprecatedForExtension "ScopedTypeVariables"),
3161 flagSpec "PatternSynonyms" Opt_PatternSynonyms,
3162 flagSpec "PolyKinds" Opt_PolyKinds,
3163 flagSpec "PolymorphicComponents" Opt_RankNTypes,
3164 flagSpec "PostfixOperators" Opt_PostfixOperators,
3165 flagSpec "QuasiQuotes" Opt_QuasiQuotes,
3166 flagSpec "Rank2Types" Opt_RankNTypes,
3167 flagSpec "RankNTypes" Opt_RankNTypes,
3168 flagSpec "RebindableSyntax" Opt_RebindableSyntax,
3169 flagSpec' "RecordPuns" Opt_RecordPuns
3170 (deprecatedForExtension "NamedFieldPuns"),
3171 flagSpec "RecordWildCards" Opt_RecordWildCards,
3172 flagSpec "RecursiveDo" Opt_RecursiveDo,
3173 flagSpec "RelaxedLayout" Opt_RelaxedLayout,
3174 flagSpec' "RelaxedPolyRec" Opt_RelaxedPolyRec
3175 (\ turn_on -> unless turn_on $
3176 deprecate "You can't turn off RelaxedPolyRec any more"),
3177 flagSpec "RoleAnnotations" Opt_RoleAnnotations,
3178 flagSpec "ScopedTypeVariables" Opt_ScopedTypeVariables,
3179 flagSpec "StandaloneDeriving" Opt_StandaloneDeriving,
3180 flagSpec "StaticPointers" Opt_StaticPointers,
3181 flagSpec' "TemplateHaskell" Opt_TemplateHaskell
3182 setTemplateHaskellLoc,
3183 flagSpec "TraditionalRecordSyntax" Opt_TraditionalRecordSyntax,
3184 flagSpec "TransformListComp" Opt_TransformListComp,
3185 flagSpec "TupleSections" Opt_TupleSections,
3186 flagSpec "TypeFamilies" Opt_TypeFamilies,
3187 flagSpec "TypeOperators" Opt_TypeOperators,
3188 flagSpec "TypeSynonymInstances" Opt_TypeSynonymInstances,
3189 flagSpec "UnboxedTuples" Opt_UnboxedTuples,
3190 flagSpec "UndecidableInstances" Opt_UndecidableInstances,
3191 flagSpec "UnicodeSyntax" Opt_UnicodeSyntax,
3192 flagSpec "UnliftedFFITypes" Opt_UnliftedFFITypes,
3193 flagSpec "ViewPatterns" Opt_ViewPatterns
3194 ]
3195
3196 defaultFlags :: Settings -> [GeneralFlag]
3197 defaultFlags settings
3198 -- See Note [Updating flag description in the User's Guide]
3199 = [ Opt_AutoLinkPackages,
3200 Opt_EmbedManifest,
3201 Opt_FlatCache,
3202 Opt_GenManifest,
3203 Opt_GhciHistory,
3204 Opt_GhciSandbox,
3205 Opt_HelpfulErrors,
3206 Opt_OmitYields,
3207 Opt_PrintBindContents,
3208 Opt_ProfCountEntries,
3209 Opt_RPath,
3210 Opt_SharedImplib,
3211 Opt_SimplPreInlining
3212 ]
3213
3214 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
3215 -- The default -O0 options
3216
3217 ++ default_PIC platform
3218
3219 ++ (if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
3220 then wayGeneralFlags platform WayDyn
3221 else [])
3222
3223 where platform = sTargetPlatform settings
3224
3225 default_PIC :: Platform -> [GeneralFlag]
3226 default_PIC platform =
3227 case (platformOS platform, platformArch platform) of
3228 (OSDarwin, ArchX86_64) -> [Opt_PIC]
3229 _ -> []
3230
3231 impliedGFlags :: [(GeneralFlag, TurnOnFlag, GeneralFlag)]
3232 impliedGFlags = [(Opt_DeferTypeErrors, turnOn, Opt_DeferTypedHoles)]
3233
3234 impliedXFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)]
3235 impliedXFlags
3236 -- See Note [Updating flag description in the User's Guide]
3237 = [ (Opt_RankNTypes, turnOn, Opt_ExplicitForAll)
3238 , (Opt_ScopedTypeVariables, turnOn, Opt_ExplicitForAll)
3239 , (Opt_LiberalTypeSynonyms, turnOn, Opt_ExplicitForAll)
3240 , (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll)
3241 , (Opt_FlexibleInstances, turnOn, Opt_TypeSynonymInstances)
3242 , (Opt_FunctionalDependencies, turnOn, Opt_MultiParamTypeClasses)
3243 , (Opt_MultiParamTypeClasses, turnOn, Opt_ConstrainedClassMethods) -- c.f. Trac #7854
3244
3245 , (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude) -- NB: turn off!
3246
3247 , (Opt_GADTs, turnOn, Opt_GADTSyntax)
3248 , (Opt_GADTs, turnOn, Opt_MonoLocalBinds)
3249 , (Opt_TypeFamilies, turnOn, Opt_MonoLocalBinds)
3250
3251 , (Opt_TypeFamilies, turnOn, Opt_KindSignatures) -- Type families use kind signatures
3252 , (Opt_PolyKinds, turnOn, Opt_KindSignatures) -- Ditto polymorphic kinds
3253
3254 -- AutoDeriveTypeable is not very useful without DeriveDataTypeable
3255 , (Opt_AutoDeriveTypeable, turnOn, Opt_DeriveDataTypeable)
3256
3257 -- We turn this on so that we can export associated type
3258 -- type synonyms in subordinates (e.g. MyClass(type AssocType))
3259 , (Opt_TypeFamilies, turnOn, Opt_ExplicitNamespaces)
3260 , (Opt_TypeOperators, turnOn, Opt_ExplicitNamespaces)
3261
3262 , (Opt_ImpredicativeTypes, turnOn, Opt_RankNTypes)
3263
3264 -- Record wild-cards implies field disambiguation
3265 -- Otherwise if you write (C {..}) you may well get
3266 -- stuff like " 'a' not in scope ", which is a bit silly
3267 -- if the compiler has just filled in field 'a' of constructor 'C'
3268 , (Opt_RecordWildCards, turnOn, Opt_DisambiguateRecordFields)
3269
3270 , (Opt_ParallelArrays, turnOn, Opt_ParallelListComp)
3271
3272 , (Opt_JavaScriptFFI, turnOn, Opt_InterruptibleFFI)
3273
3274 , (Opt_DeriveTraversable, turnOn, Opt_DeriveFunctor)
3275 , (Opt_DeriveTraversable, turnOn, Opt_DeriveFoldable)
3276 ]
3277
3278 -- Note [Documenting optimisation flags]
3279 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3280 --
3281 -- If you change the list of flags enabled for particular optimisation levels
3282 -- please remember to update the User's Guide. The relevant files are:
3283 --
3284 -- * docs/users_guide/flags.xml
3285 -- * docs/users_guide/using.xml
3286 --
3287 -- The first contains the Flag Refrence section, which breifly lists all
3288 -- available flags. The second contains a detailed description of the
3289 -- flags. Both places should contain information whether a flag is implied by
3290 -- -O0, -O or -O2.
3291
3292 optLevelFlags :: [([Int], GeneralFlag)]
3293 optLevelFlags -- see Note [Documenting optimisation flags]
3294 = [ ([0,1,2], Opt_DoLambdaEtaExpansion)
3295 , ([0,1,2], Opt_DmdTxDictSel)
3296 , ([0,1,2], Opt_LlvmTBAA)
3297 , ([0,1,2], Opt_VectorisationAvoidance)
3298 -- This one is important for a tiresome reason:
3299 -- we want to make sure that the bindings for data
3300 -- constructors are eta-expanded. This is probably
3301 -- a good thing anyway, but it seems fragile.
3302
3303 , ([0], Opt_IgnoreInterfacePragmas)
3304 , ([0], Opt_OmitInterfacePragmas)
3305
3306 , ([1,2], Opt_CallArity)
3307 , ([1,2], Opt_CaseMerge)
3308 , ([1,2], Opt_CmmElimCommonBlocks)
3309 , ([1,2], Opt_CmmSink)
3310 , ([1,2], Opt_CSE)
3311 , ([1,2], Opt_DoEtaReduction)
3312 , ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
3313 -- in PrelRules
3314 , ([1,2], Opt_FloatIn)
3315 , ([1,2], Opt_FullLaziness)
3316 , ([1,2], Opt_IgnoreAsserts)
3317 , ([1,2], Opt_Loopification)
3318 , ([1,2], Opt_Specialise)
3319 , ([1,2], Opt_CrossModuleSpecialise)
3320 , ([1,2], Opt_Strictness)
3321 , ([1,2], Opt_UnboxSmallStrictFields)
3322
3323 , ([2], Opt_LiberateCase)
3324 , ([2], Opt_SpecConstr)
3325 -- , ([2], Opt_RegsGraph)
3326 -- RegsGraph suffers performance regression. See #7679
3327 -- , ([2], Opt_StaticArgumentTransformation)
3328 -- Static Argument Transformation needs investigation. See #9374
3329 ]
3330
3331 -- -----------------------------------------------------------------------------
3332 -- Standard sets of warning options
3333
3334 -- Note [Documenting warning flags]
3335 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3336 --
3337 -- If you change the list of warning enabled by default
3338 -- please remember to update the User's Guide. The relevant file is:
3339 --
3340 -- * docs/users_guide/using.xml
3341
3342 standardWarnings :: [WarningFlag]
3343 standardWarnings -- see Note [Documenting warning flags]
3344 = [ Opt_WarnOverlappingPatterns,
3345 Opt_WarnWarningsDeprecations,
3346 Opt_WarnDeprecatedFlags,
3347 Opt_WarnTypedHoles,
3348 Opt_WarnPartialTypeSignatures,
3349 Opt_WarnUnrecognisedPragmas,
3350 Opt_WarnPointlessPragmas,
3351 Opt_WarnRedundantConstraints,
3352 Opt_WarnDuplicateExports,
3353 Opt_WarnOverflowedLiterals,
3354 Opt_WarnEmptyEnumerations,
3355 Opt_WarnMissingFields,
3356 Opt_WarnMissingMethods,
3357 Opt_WarnWrongDoBind,
3358 Opt_WarnUnsupportedCallingConventions,
3359 Opt_WarnDodgyForeignImports,
3360 Opt_WarnInlineRuleShadowing,
3361 Opt_WarnAlternativeLayoutRuleTransitional,
3362 Opt_WarnUnsupportedLlvmVersion,
3363 Opt_WarnContextQuantification,
3364 Opt_WarnTabs
3365 ]
3366
3367 minusWOpts :: [WarningFlag]
3368 -- Things you get with -W
3369 minusWOpts
3370 = standardWarnings ++
3371 [ Opt_WarnUnusedTopBinds,
3372 Opt_WarnUnusedLocalBinds,
3373 Opt_WarnUnusedPatternBinds,
3374 Opt_WarnUnusedMatches,
3375 Opt_WarnUnusedImports,
3376 Opt_WarnIncompletePatterns,
3377 Opt_WarnDodgyExports,
3378 Opt_WarnDodgyImports
3379 ]
3380
3381 minusWallOpts :: [WarningFlag]
3382 -- Things you get with -Wall
3383 minusWallOpts
3384 = minusWOpts ++
3385 [ Opt_WarnTypeDefaults,
3386 Opt_WarnNameShadowing,
3387 Opt_WarnMissingSigs,
3388 Opt_WarnHiShadows,
3389 Opt_WarnOrphans,
3390 Opt_WarnUnusedDoBind,
3391 Opt_WarnTrustworthySafe,
3392 Opt_WarnUntickedPromotedConstructors
3393 ]
3394
3395 enableUnusedBinds :: DynP ()
3396 enableUnusedBinds = mapM_ setWarningFlag unusedBindsFlags
3397
3398 disableUnusedBinds :: DynP ()
3399 disableUnusedBinds = mapM_ unSetWarningFlag unusedBindsFlags
3400
3401 -- Things you get with -fwarn-unused-binds
3402 unusedBindsFlags :: [WarningFlag]
3403 unusedBindsFlags = [ Opt_WarnUnusedTopBinds
3404 , Opt_WarnUnusedLocalBinds
3405 , Opt_WarnUnusedPatternBinds
3406 ]
3407
3408 enableGlasgowExts :: DynP ()
3409 enableGlasgowExts = do setGeneralFlag Opt_PrintExplicitForalls
3410 mapM_ setExtensionFlag glasgowExtsFlags
3411
3412 disableGlasgowExts :: DynP ()
3413 disableGlasgowExts = do unSetGeneralFlag Opt_PrintExplicitForalls
3414 mapM_ unSetExtensionFlag glasgowExtsFlags
3415
3416 glasgowExtsFlags :: [ExtensionFlag]
3417 glasgowExtsFlags = [
3418 Opt_ConstrainedClassMethods
3419 , Opt_DeriveDataTypeable
3420 , Opt_DeriveFoldable
3421 , Opt_DeriveFunctor
3422 , Opt_DeriveGeneric
3423 , Opt_DeriveTraversable
3424 , Opt_EmptyDataDecls
3425 , Opt_ExistentialQuantification
3426 , Opt_ExplicitNamespaces
3427 , Opt_FlexibleContexts
3428 , Opt_FlexibleInstances
3429 , Opt_ForeignFunctionInterface
3430 , Opt_FunctionalDependencies
3431 , Opt_GeneralizedNewtypeDeriving
3432 , Opt_ImplicitParams
3433 , Opt_KindSignatures
3434 , Opt_LiberalTypeSynonyms
3435 , Opt_MagicHash
3436 , Opt_MultiParamTypeClasses
3437 , Opt_ParallelListComp
3438 , Opt_PatternGuards
3439 , Opt_PostfixOperators
3440 , Opt_RankNTypes
3441 , Opt_RecursiveDo
3442 , Opt_ScopedTypeVariables
3443 , Opt_StandaloneDeriving
3444 , Opt_TypeOperators
3445 , Opt_TypeSynonymInstances
3446 , Opt_UnboxedTuples
3447 , Opt_UnicodeSyntax
3448 , Opt_UnliftedFFITypes ]
3449
3450 #ifdef GHCI
3451 -- Consult the RTS to find whether GHC itself has been built profiled
3452 -- If so, you can't use Template Haskell
3453 foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt
3454
3455 rtsIsProfiled :: Bool
3456 rtsIsProfiled = unsafeDupablePerformIO rtsIsProfiledIO /= 0
3457 #endif
3458
3459 #ifdef GHCI
3460 -- Consult the RTS to find whether GHC itself has been built with
3461 -- dynamic linking. This can't be statically known at compile-time,
3462 -- because we build both the static and dynamic versions together with
3463 -- -dynamic-too.
3464 foreign import ccall unsafe "rts_isDynamic" rtsIsDynamicIO :: IO CInt
3465
3466 dynamicGhc :: Bool
3467 dynamicGhc = unsafeDupablePerformIO rtsIsDynamicIO /= 0
3468 #else
3469 dynamicGhc :: Bool
3470 dynamicGhc = False
3471 #endif
3472
3473 setWarnSafe :: Bool -> DynP ()
3474 setWarnSafe True = getCurLoc >>= \l -> upd (\d -> d { warnSafeOnLoc = l })
3475 setWarnSafe False = return ()
3476
3477 setWarnUnsafe :: Bool -> DynP ()
3478 setWarnUnsafe True = getCurLoc >>= \l -> upd (\d -> d { warnUnsafeOnLoc = l })
3479 setWarnUnsafe False = return ()
3480
3481 setPackageTrust :: DynP ()
3482 setPackageTrust = do
3483 setGeneralFlag Opt_PackageTrust
3484 l <- getCurLoc
3485 upd $ \d -> d { pkgTrustOnLoc = l }
3486
3487 setGenDeriving :: TurnOnFlag -> DynP ()
3488 setGenDeriving True = getCurLoc >>= \l -> upd (\d -> d { newDerivOnLoc = l })
3489 setGenDeriving False = return ()
3490
3491 setOverlappingInsts :: TurnOnFlag -> DynP ()
3492 setOverlappingInsts False = return ()
3493 setOverlappingInsts True = do
3494 l <- getCurLoc
3495 upd (\d -> d { overlapInstLoc = l })
3496 deprecate "instead use per-instance pragmas OVERLAPPING/OVERLAPPABLE/OVERLAPS"
3497
3498 setIncoherentInsts :: TurnOnFlag -> DynP ()
3499 setIncoherentInsts False = return ()
3500 setIncoherentInsts True = do
3501 l <- getCurLoc
3502 upd (\d -> d { incoherentOnLoc = l })
3503
3504 setTemplateHaskellLoc :: TurnOnFlag -> DynP ()
3505 setTemplateHaskellLoc _
3506 = getCurLoc >>= \l -> upd (\d -> d { thOnLoc = l })
3507
3508 {- **********************************************************************
3509 %* *
3510 DynFlags constructors
3511 %* *
3512 %********************************************************************* -}
3513
3514 type DynP = EwM (CmdLineP DynFlags)
3515
3516 upd :: (DynFlags -> DynFlags) -> DynP ()
3517 upd f = liftEwM (do dflags <- getCmdLineState
3518 putCmdLineState $! f dflags)
3519
3520 updM :: (DynFlags -> DynP DynFlags) -> DynP ()
3521 updM f = do dflags <- liftEwM getCmdLineState
3522 dflags' <- f dflags
3523 liftEwM $ putCmdLineState $! dflags'
3524
3525 --------------- Constructor functions for OptKind -----------------
3526 noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3527 noArg fn = NoArg (upd fn)
3528
3529 noArgM :: (DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags)
3530 noArgM fn = NoArg (updM fn)
3531
3532 hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3533 hasArg fn = HasArg (upd . fn)
3534
3535 sepArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3536 sepArg fn = SepArg (upd . fn)
3537
3538 intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3539 intSuffix fn = IntSuffix (\n -> upd (fn n))
3540
3541 intSuffixM :: (Int -> DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags)
3542 intSuffixM fn = IntSuffix (\n -> updM (fn n))
3543
3544 floatSuffix :: (Float -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3545 floatSuffix fn = FloatSuffix (\n -> upd (fn n))
3546
3547 optIntSuffixM :: (Maybe Int -> DynFlags -> DynP DynFlags)
3548 -> OptKind (CmdLineP DynFlags)
3549 optIntSuffixM fn = OptIntSuffix (\mi -> updM (fn mi))
3550
3551 setDumpFlag :: DumpFlag -> OptKind (CmdLineP DynFlags)
3552 setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
3553
3554 --------------------------
3555 addWay :: Way -> DynP ()
3556 addWay w = upd (addWay' w)
3557
3558 addWay' :: Way -> DynFlags -> DynFlags
3559 addWay' w dflags0 = let platform = targetPlatform dflags0
3560 dflags1 = dflags0 { ways = w : ways dflags0 }
3561 dflags2 = wayExtras platform w dflags1
3562 dflags3 = foldr setGeneralFlag' dflags2
3563 (wayGeneralFlags platform w)
3564 dflags4 = foldr unSetGeneralFlag' dflags3
3565 (wayUnsetGeneralFlags platform w)
3566 in dflags4
3567
3568 removeWayDyn :: DynP ()
3569 removeWayDyn = upd (\dfs -> dfs { ways = filter (WayDyn /=) (ways dfs) })
3570
3571 --------------------------
3572 setGeneralFlag, unSetGeneralFlag :: GeneralFlag -> DynP ()
3573 setGeneralFlag f = upd (setGeneralFlag' f)
3574 unSetGeneralFlag f = upd (unSetGeneralFlag' f)
3575
3576 setGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags
3577 setGeneralFlag' f dflags = foldr ($) (gopt_set dflags f) deps
3578 where
3579 deps = [ if turn_on then setGeneralFlag' d
3580 else unSetGeneralFlag' d
3581 | (f', turn_on, d) <- impliedGFlags, f' == f ]
3582 -- When you set f, set the ones it implies
3583 -- NB: use setGeneralFlag recursively, in case the implied flags
3584 -- implies further flags
3585
3586 unSetGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags
3587 unSetGeneralFlag' f dflags = gopt_unset dflags f
3588 -- When you un-set f, however, we don't un-set the things it implies
3589
3590 --------------------------
3591 setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP ()
3592 setWarningFlag f = upd (\dfs -> wopt_set dfs f)
3593 unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f)
3594
3595 --------------------------
3596 setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP ()
3597 setExtensionFlag f = upd (setExtensionFlag' f)
3598 unSetExtensionFlag f = upd (unSetExtensionFlag' f)
3599
3600 setExtensionFlag', unSetExtensionFlag' :: ExtensionFlag -> DynFlags -> DynFlags
3601 setExtensionFlag' f dflags = foldr ($) (xopt_set dflags f) deps
3602 where
3603 deps = [ if turn_on then setExtensionFlag' d
3604 else unSetExtensionFlag' d
3605 | (f', turn_on, d) <- impliedXFlags, f' == f ]
3606 -- When you set f, set the ones it implies
3607 -- NB: use setExtensionFlag recursively, in case the implied flags
3608 -- implies further flags
3609
3610 unSetExtensionFlag' f dflags = xopt_unset dflags f
3611 -- When you un-set f, however, we don't un-set the things it implies
3612 -- (except for -fno-glasgow-exts, which is treated specially)
3613
3614 --------------------------
3615 alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags
3616 alterSettings f dflags = dflags { settings = f (settings dflags) }
3617
3618 --------------------------
3619 setDumpFlag' :: DumpFlag -> DynP ()
3620 setDumpFlag' dump_flag
3621 = do upd (\dfs -> dopt_set dfs dump_flag)
3622 when want_recomp forceRecompile
3623 where -- Certain dumpy-things are really interested in what's going
3624 -- on during recompilation checking, so in those cases we
3625 -- don't want to turn it off.
3626 want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace,
3627 Opt_D_dump_hi_diffs]
3628
3629 forceRecompile :: DynP ()
3630 -- Whenver we -ddump, force recompilation (by switching off the
3631 -- recompilation checker), else you don't see the dump! However,
3632 -- don't switch it off in --make mode, else *everything* gets
3633 -- recompiled which probably isn't what you want
3634 forceRecompile = do dfs <- liftEwM getCmdLineState
3635 when (force_recomp dfs) (setGeneralFlag Opt_ForceRecomp)
3636 where
3637 force_recomp dfs = isOneShot (ghcMode dfs)
3638
3639
3640 setVerboseCore2Core :: DynP ()
3641 setVerboseCore2Core = setDumpFlag' Opt_D_verbose_core2core
3642
3643 setVerbosity :: Maybe Int -> DynP ()
3644 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
3645
3646 addCmdlineHCInclude :: String -> DynP ()
3647 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
3648
3649 data PkgConfRef
3650 = GlobalPkgConf
3651 | UserPkgConf
3652 | PkgConfFile FilePath
3653
3654 addPkgConfRef :: PkgConfRef -> DynP ()
3655 addPkgConfRef p = upd $ \s -> s { extraPkgConfs = (p:) . extraPkgConfs s }
3656
3657 removeUserPkgConf :: DynP ()
3658 removeUserPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotUser . extraPkgConfs s }
3659 where
3660 isNotUser UserPkgConf = False
3661 isNotUser _ = True
3662
3663 removeGlobalPkgConf :: DynP ()
3664 removeGlobalPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotGlobal . extraPkgConfs s }
3665 where
3666 isNotGlobal GlobalPkgConf = False
3667 isNotGlobal _ = True
3668
3669 clearPkgConf :: DynP ()
3670 clearPkgConf = upd $ \s -> s { extraPkgConfs = const [] }
3671
3672 parseModuleName :: ReadP ModuleName
3673 parseModuleName = fmap mkModuleName
3674 $ munch1 (\c -> isAlphaNum c || c `elem` ".")
3675
3676 parsePackageFlag :: (String -> PackageArg) -- type of argument
3677 -> String -- string to parse
3678 -> PackageFlag
3679 parsePackageFlag constr str = case filter ((=="").snd) (readP_to_S parse str) of
3680 [(r, "")] -> r
3681 _ -> throwGhcException $ CmdLineError ("Can't parse package flag: " ++ str)
3682 where parse = do
3683 pkg <- tok $ munch1 (\c -> isAlphaNum c || c `elem` ":-_.")
3684 ( do _ <- tok $ string "with"
3685 fmap (ExposePackage (constr pkg) . ModRenaming True) parseRns
3686 <++ fmap (ExposePackage (constr pkg) . ModRenaming False) parseRns
3687 <++ return (ExposePackage (constr pkg) (ModRenaming True [])))
3688 parseRns = do _ <- tok $ R.char '('
3689 rns <- tok $ sepBy parseItem (tok $ R.char ',')
3690 _ <- tok $ R.char ')'
3691 return rns
3692 parseItem = do
3693 orig <- tok $ parseModuleName
3694 (do _ <- tok $ string "as"
3695 new <- tok $ parseModuleName
3696 return (orig, new)
3697 +++
3698 return (orig, orig))
3699 tok m = m >>= \x -> skipSpaces >> return x
3700
3701 exposePackage, exposePackageId, exposePackageKey, hidePackage, ignorePackage,
3702 trustPackage, distrustPackage :: String -> DynP ()
3703 exposePackage p = upd (exposePackage' p)
3704 exposePackageId p =
3705 upd (\s -> s{ packageFlags =
3706 parsePackageFlag PackageIdArg p : packageFlags s })
3707 exposePackageKey p =
3708 upd (\s -> s{ packageFlags =
3709 parsePackageFlag PackageKeyArg p : packageFlags s })
3710 hidePackage p =
3711 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
3712 ignorePackage p =
3713 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
3714 trustPackage p = exposePackage p >> -- both trust and distrust also expose a package
3715 upd (\s -> s{ packageFlags = TrustPackage p : packageFlags s })
3716 distrustPackage p = exposePackage p >>
3717 upd (\s -> s{ packageFlags = DistrustPackage p : packageFlags s })
3718
3719 exposePackage' :: String -> DynFlags -> DynFlags
3720 exposePackage' p dflags
3721 = dflags { packageFlags =
3722 parsePackageFlag PackageArg p : packageFlags dflags }
3723
3724 setPackageKey :: String -> DynFlags -> DynFlags
3725 setPackageKey p s = s{ thisPackage = stringToPackageKey p }
3726
3727 -- -----------------------------------------------------------------------------
3728 -- | Find the package environment (if one exists)
3729 --
3730 -- We interpret the package environment as a set of package flags; to be
3731 -- specific, if we find a package environment
3732 --
3733 -- > id1
3734 -- > id2
3735 -- > ..
3736 -- > idn
3737 --
3738 -- we interpret this as
3739 --
3740 -- > [ -hide-all-packages
3741 -- > , -package-id id1
3742 -- > , -package-id id2
3743 -- > , ..
3744 -- > , -package-id idn
3745 -- > ]
3746 interpretPackageEnv :: DynFlags -> IO DynFlags
3747 interpretPackageEnv dflags = do
3748 mPkgEnv <- runMaybeT $ msum $ [
3749 getCmdLineArg >>= \env -> msum [
3750 loadEnvFile env
3751 , loadEnvName env
3752 , cmdLineError env
3753 ]
3754 , getEnvVar >>= \env -> msum [
3755 loadEnvFile env
3756 , loadEnvName env
3757 , envError env
3758 ]
3759 , loadEnvFile localEnvFile
3760 , loadEnvName defaultEnvName
3761 ]
3762 case mPkgEnv of
3763 Nothing ->
3764 -- No environment found. Leave DynFlags unchanged.
3765 return dflags
3766 Just ids -> do
3767 let setFlags :: DynP ()
3768 setFlags = do
3769 setGeneralFlag Opt_HideAllPackages
3770 mapM_ exposePackageId (lines ids)
3771
3772 (_, dflags') = runCmdLine (runEwM setFlags) dflags
3773
3774 return dflags'
3775 where
3776 -- Loading environments (by name or by location)
3777
3778 namedEnvPath :: String -> MaybeT IO FilePath
3779 namedEnvPath name = do
3780 appdir <- liftMaybeT $ versionedAppDir dflags
3781 return $ appdir </> "environments" </> name
3782
3783 loadEnvName :: String -> MaybeT IO String
3784 loadEnvName name = loadEnvFile =<< namedEnvPath name
3785
3786 loadEnvFile :: String -> MaybeT IO String
3787 loadEnvFile path = do
3788 guard =<< liftMaybeT (doesFileExist path)
3789 liftMaybeT $ readFile path
3790
3791 -- Various ways to define which environment to use
3792
3793 getCmdLineArg :: MaybeT IO String
3794 getCmdLineArg = MaybeT $ return $ packageEnv dflags
3795
3796 getEnvVar :: MaybeT IO String
3797 getEnvVar = do
3798 mvar <- liftMaybeT $ try $ getEnv "GHC_ENVIRONMENT"
3799 case mvar of
3800 Right var -> return var
3801 Left err -> if isDoesNotExistError err then mzero
3802 else liftMaybeT $ throwIO err
3803
3804 defaultEnvName :: String
3805 defaultEnvName = "default"