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