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