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