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