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