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