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