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