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