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