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