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