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