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