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