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