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