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