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