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