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