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