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