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