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