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