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