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