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