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