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