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