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