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