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