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