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