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