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