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