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