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