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