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