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