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