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