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