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