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