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