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