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