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