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