users-guide: Document -XHaskell98 and -XHaskell2010
[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 -- | The language extensions implied by the various language variants.
2300 -- When updating this be sure to update the flag documentation in
2301 -- @docs/users-guide/glasgow_exts.rst@.
2302 languageExtensions :: Maybe Language -> [LangExt.Extension]
2303
2304 languageExtensions Nothing
2305 -- Nothing => the default case
2306 = LangExt.NondecreasingIndentation -- This has been on by default for some time
2307 : delete LangExt.DatatypeContexts -- The Haskell' committee decided to
2308 -- remove datatype contexts from the
2309 -- language:
2310 -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
2311 (languageExtensions (Just Haskell2010))
2312
2313 -- NB: MonoPatBinds is no longer the default
2314
2315 languageExtensions (Just Haskell98)
2316 = [LangExt.ImplicitPrelude,
2317 -- See Note [When is StarIsType enabled]
2318 LangExt.StarIsType,
2319 LangExt.CUSKs,
2320 LangExt.MonomorphismRestriction,
2321 LangExt.NPlusKPatterns,
2322 LangExt.DatatypeContexts,
2323 LangExt.TraditionalRecordSyntax,
2324 LangExt.NondecreasingIndentation
2325 -- strictly speaking non-standard, but we always had this
2326 -- on implicitly before the option was added in 7.1, and
2327 -- turning it off breaks code, so we're keeping it on for
2328 -- backwards compatibility. Cabal uses -XHaskell98 by
2329 -- default unless you specify another language.
2330 ]
2331
2332 languageExtensions (Just Haskell2010)
2333 = [LangExt.ImplicitPrelude,
2334 -- See Note [When is StarIsType enabled]
2335 LangExt.StarIsType,
2336 LangExt.CUSKs,
2337 LangExt.MonomorphismRestriction,
2338 LangExt.DatatypeContexts,
2339 LangExt.TraditionalRecordSyntax,
2340 LangExt.EmptyDataDecls,
2341 LangExt.ForeignFunctionInterface,
2342 LangExt.PatternGuards,
2343 LangExt.DoAndIfThenElse,
2344 LangExt.RelaxedPolyRec]
2345
2346 hasPprDebug :: DynFlags -> Bool
2347 hasPprDebug = dopt Opt_D_ppr_debug
2348
2349 hasNoDebugOutput :: DynFlags -> Bool
2350 hasNoDebugOutput = dopt Opt_D_no_debug_output
2351
2352 hasNoStateHack :: DynFlags -> Bool
2353 hasNoStateHack = gopt Opt_G_NoStateHack
2354
2355 hasNoOptCoercion :: DynFlags -> Bool
2356 hasNoOptCoercion = gopt Opt_G_NoOptCoercion
2357
2358
2359 -- | Test whether a 'DumpFlag' is set
2360 dopt :: DumpFlag -> DynFlags -> Bool
2361 dopt f dflags = (f `EnumSet.member` dumpFlags dflags)
2362 || (verbosity dflags >= 4 && enableIfVerbose f)
2363 where enableIfVerbose Opt_D_dump_tc_trace = False
2364 enableIfVerbose Opt_D_dump_rn_trace = False
2365 enableIfVerbose Opt_D_dump_cs_trace = False
2366 enableIfVerbose Opt_D_dump_if_trace = False
2367 enableIfVerbose Opt_D_dump_vt_trace = False
2368 enableIfVerbose Opt_D_dump_tc = False
2369 enableIfVerbose Opt_D_dump_rn = False
2370 enableIfVerbose Opt_D_dump_rn_stats = False
2371 enableIfVerbose Opt_D_dump_hi_diffs = False
2372 enableIfVerbose Opt_D_verbose_core2core = False
2373 enableIfVerbose Opt_D_verbose_stg2stg = False
2374 enableIfVerbose Opt_D_dump_splices = False
2375 enableIfVerbose Opt_D_th_dec_file = False
2376 enableIfVerbose Opt_D_dump_rule_firings = False
2377 enableIfVerbose Opt_D_dump_rule_rewrites = False
2378 enableIfVerbose Opt_D_dump_simpl_trace = False
2379 enableIfVerbose Opt_D_dump_rtti = False
2380 enableIfVerbose Opt_D_dump_inlinings = False
2381 enableIfVerbose Opt_D_dump_core_stats = False
2382 enableIfVerbose Opt_D_dump_asm_stats = False
2383 enableIfVerbose Opt_D_dump_types = False
2384 enableIfVerbose Opt_D_dump_simpl_iterations = False
2385 enableIfVerbose Opt_D_dump_ticked = False
2386 enableIfVerbose Opt_D_dump_view_pattern_commoning = False
2387 enableIfVerbose Opt_D_dump_mod_cycles = False
2388 enableIfVerbose Opt_D_dump_mod_map = False
2389 enableIfVerbose Opt_D_dump_ec_trace = False
2390 enableIfVerbose _ = True
2391
2392 -- | Set a 'DumpFlag'
2393 dopt_set :: DynFlags -> DumpFlag -> DynFlags
2394 dopt_set dfs f = dfs{ dumpFlags = EnumSet.insert f (dumpFlags dfs) }
2395
2396 -- | Unset a 'DumpFlag'
2397 dopt_unset :: DynFlags -> DumpFlag -> DynFlags
2398 dopt_unset dfs f = dfs{ dumpFlags = EnumSet.delete f (dumpFlags dfs) }
2399
2400 -- | Test whether a 'GeneralFlag' is set
2401 gopt :: GeneralFlag -> DynFlags -> Bool
2402 gopt f dflags = f `EnumSet.member` generalFlags dflags
2403
2404 -- | Set a 'GeneralFlag'
2405 gopt_set :: DynFlags -> GeneralFlag -> DynFlags
2406 gopt_set dfs f = dfs{ generalFlags = EnumSet.insert f (generalFlags dfs) }
2407
2408 -- | Unset a 'GeneralFlag'
2409 gopt_unset :: DynFlags -> GeneralFlag -> DynFlags
2410 gopt_unset dfs f = dfs{ generalFlags = EnumSet.delete f (generalFlags dfs) }
2411
2412 -- | Test whether a 'WarningFlag' is set
2413 wopt :: WarningFlag -> DynFlags -> Bool
2414 wopt f dflags = f `EnumSet.member` warningFlags dflags
2415
2416 -- | Set a 'WarningFlag'
2417 wopt_set :: DynFlags -> WarningFlag -> DynFlags
2418 wopt_set dfs f = dfs{ warningFlags = EnumSet.insert f (warningFlags dfs) }
2419
2420 -- | Unset a 'WarningFlag'
2421 wopt_unset :: DynFlags -> WarningFlag -> DynFlags
2422 wopt_unset dfs f = dfs{ warningFlags = EnumSet.delete f (warningFlags dfs) }
2423
2424 -- | Test whether a 'WarningFlag' is set as fatal
2425 wopt_fatal :: WarningFlag -> DynFlags -> Bool
2426 wopt_fatal f dflags = f `EnumSet.member` fatalWarningFlags dflags
2427
2428 -- | Mark a 'WarningFlag' as fatal (do not set the flag)
2429 wopt_set_fatal :: DynFlags -> WarningFlag -> DynFlags
2430 wopt_set_fatal dfs f
2431 = dfs { fatalWarningFlags = EnumSet.insert f (fatalWarningFlags dfs) }
2432
2433 -- | Mark a 'WarningFlag' as not fatal
2434 wopt_unset_fatal :: DynFlags -> WarningFlag -> DynFlags
2435 wopt_unset_fatal dfs f
2436 = dfs { fatalWarningFlags = EnumSet.delete f (fatalWarningFlags dfs) }
2437
2438 -- | Test whether a 'LangExt.Extension' is set
2439 xopt :: LangExt.Extension -> DynFlags -> Bool
2440 xopt f dflags = f `EnumSet.member` extensionFlags dflags
2441
2442 -- | Set a 'LangExt.Extension'
2443 xopt_set :: DynFlags -> LangExt.Extension -> DynFlags
2444 xopt_set dfs f
2445 = let onoffs = On f : extensions dfs
2446 in dfs { extensions = onoffs,
2447 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
2448
2449 -- | Unset a 'LangExt.Extension'
2450 xopt_unset :: DynFlags -> LangExt.Extension -> DynFlags
2451 xopt_unset dfs f
2452 = let onoffs = Off f : extensions dfs
2453 in dfs { extensions = onoffs,
2454 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
2455
2456 -- | Set or unset a 'LangExt.Extension', unless it has been explicitly
2457 -- set or unset before.
2458 xopt_set_unlessExplSpec
2459 :: LangExt.Extension
2460 -> (DynFlags -> LangExt.Extension -> DynFlags)
2461 -> DynFlags -> DynFlags
2462 xopt_set_unlessExplSpec ext setUnset dflags =
2463 let referedExts = stripOnOff <$> extensions dflags
2464 stripOnOff (On x) = x
2465 stripOnOff (Off x) = x
2466 in
2467 if ext `elem` referedExts then dflags else setUnset dflags ext
2468
2469 lang_set :: DynFlags -> Maybe Language -> DynFlags
2470 lang_set dflags lang =
2471 dflags {
2472 language = lang,
2473 extensionFlags = flattenExtensionFlags lang (extensions dflags)
2474 }
2475
2476 -- | An internal helper to check whether to use unicode syntax for output.
2477 --
2478 -- Note: You should very likely be using 'Outputable.unicodeSyntax' instead
2479 -- of this function.
2480 useUnicodeSyntax :: DynFlags -> Bool
2481 useUnicodeSyntax = gopt Opt_PrintUnicodeSyntax
2482
2483 useStarIsType :: DynFlags -> Bool
2484 useStarIsType = xopt LangExt.StarIsType
2485
2486 -- | Set the Haskell language standard to use
2487 setLanguage :: Language -> DynP ()
2488 setLanguage l = upd (`lang_set` Just l)
2489
2490 -- | Some modules have dependencies on others through the DynFlags rather than textual imports
2491 dynFlagDependencies :: DynFlags -> [ModuleName]
2492 dynFlagDependencies = pluginModNames
2493
2494 -- | Is the -fpackage-trust mode on
2495 packageTrustOn :: DynFlags -> Bool
2496 packageTrustOn = gopt Opt_PackageTrust
2497
2498 -- | Is Safe Haskell on in some way (including inference mode)
2499 safeHaskellOn :: DynFlags -> Bool
2500 safeHaskellOn dflags = safeHaskellModeEnabled dflags || safeInferOn dflags
2501
2502 safeHaskellModeEnabled :: DynFlags -> Bool
2503 safeHaskellModeEnabled dflags = safeHaskell dflags `elem` [Sf_Unsafe, Sf_Trustworthy
2504 , Sf_Safe ]
2505
2506
2507 -- | Is the Safe Haskell safe language in use
2508 safeLanguageOn :: DynFlags -> Bool
2509 safeLanguageOn dflags = safeHaskell dflags == Sf_Safe
2510
2511 -- | Is the Safe Haskell safe inference mode active
2512 safeInferOn :: DynFlags -> Bool
2513 safeInferOn = safeInfer
2514
2515 -- | Test if Safe Imports are on in some form
2516 safeImportsOn :: DynFlags -> Bool
2517 safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
2518 safeHaskell dflags == Sf_Trustworthy ||
2519 safeHaskell dflags == Sf_Safe
2520
2521 -- | Set a 'Safe Haskell' flag
2522 setSafeHaskell :: SafeHaskellMode -> DynP ()
2523 setSafeHaskell s = updM f
2524 where f dfs = do
2525 let sf = safeHaskell dfs
2526 safeM <- combineSafeFlags sf s
2527 case s of
2528 Sf_Safe -> return $ dfs { safeHaskell = safeM, safeInfer = False }
2529 -- leave safe inferrence on in Trustworthy mode so we can warn
2530 -- if it could have been inferred safe.
2531 Sf_Trustworthy -> do
2532 l <- getCurLoc
2533 return $ dfs { safeHaskell = safeM, trustworthyOnLoc = l }
2534 -- leave safe inference on in Unsafe mode as well.
2535 _ -> return $ dfs { safeHaskell = safeM }
2536
2537 -- | Are all direct imports required to be safe for this Safe Haskell mode?
2538 -- Direct imports are when the code explicitly imports a module
2539 safeDirectImpsReq :: DynFlags -> Bool
2540 safeDirectImpsReq d = safeLanguageOn d
2541
2542 -- | Are all implicit imports required to be safe for this Safe Haskell mode?
2543 -- Implicit imports are things in the prelude. e.g System.IO when print is used.
2544 safeImplicitImpsReq :: DynFlags -> Bool
2545 safeImplicitImpsReq d = safeLanguageOn d
2546
2547 -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
2548 -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
2549 -- want to export this functionality from the module but do want to export the
2550 -- type constructors.
2551 combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
2552 combineSafeFlags a b | a == Sf_None = return b
2553 | b == Sf_None = return a
2554 | a == Sf_Ignore || b == Sf_Ignore = return Sf_Ignore
2555 | a == b = return a
2556 | otherwise = addErr errm >> pure a
2557 where errm = "Incompatible Safe Haskell flags! ("
2558 ++ show a ++ ", " ++ show b ++ ")"
2559
2560 -- | A list of unsafe flags under Safe Haskell. Tuple elements are:
2561 -- * name of the flag
2562 -- * function to get srcspan that enabled the flag
2563 -- * function to test if the flag is on
2564 -- * function to turn the flag off
2565 unsafeFlags, unsafeFlagsForInfer
2566 :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
2567 unsafeFlags = [ ("-XGeneralizedNewtypeDeriving", newDerivOnLoc,
2568 xopt LangExt.GeneralizedNewtypeDeriving,
2569 flip xopt_unset LangExt.GeneralizedNewtypeDeriving)
2570 , ("-XTemplateHaskell", thOnLoc,
2571 xopt LangExt.TemplateHaskell,
2572 flip xopt_unset LangExt.TemplateHaskell)
2573 ]
2574 unsafeFlagsForInfer = unsafeFlags
2575
2576
2577 -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
2578 getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
2579 -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
2580 -> [a] -- ^ Correctly ordered extracted options
2581 getOpts dflags opts = reverse (opts dflags)
2582 -- We add to the options from the front, so we need to reverse the list
2583
2584 -- | Gets the verbosity flag for the current verbosity level. This is fed to
2585 -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
2586 getVerbFlags :: DynFlags -> [String]
2587 getVerbFlags dflags
2588 | verbosity dflags >= 4 = ["-v"]
2589 | otherwise = []
2590
2591 setObjectDir, setHiDir, setHieDir, setStubDir, setDumpDir, setOutputDir,
2592 setDynObjectSuf, setDynHiSuf,
2593 setDylibInstallName,
2594 setObjectSuf, setHiSuf, setHieSuf, setHcSuf, parseDynLibLoaderMode,
2595 setPgmP, addOptl, addOptc, addOptcxx, addOptP,
2596 addCmdlineFramework, addHaddockOpts, addGhciScript,
2597 setInteractivePrint
2598 :: String -> DynFlags -> DynFlags
2599 setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce
2600 :: Maybe String -> DynFlags -> DynFlags
2601
2602 setObjectDir f d = d { objectDir = Just f}
2603 setHiDir f d = d { hiDir = Just f}
2604 setHieDir f d = d { hieDir = Just f}
2605 setStubDir f d = d { stubDir = Just f
2606 , includePaths = addGlobalInclude (includePaths d) [f] }
2607 -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
2608 -- \#included from the .hc file when compiling via C (i.e. unregisterised
2609 -- builds).
2610 setDumpDir f d = d { dumpDir = Just f}
2611 setOutputDir f = setObjectDir f
2612 . setHieDir f
2613 . setHiDir f
2614 . setStubDir f
2615 . setDumpDir f
2616 setDylibInstallName f d = d { dylibInstallName = Just f}
2617
2618 setObjectSuf f d = d { objectSuf = f}
2619 setDynObjectSuf f d = d { dynObjectSuf = f}
2620 setHiSuf f d = d { hiSuf = f}
2621 setHieSuf f d = d { hieSuf = f}
2622 setDynHiSuf f d = d { dynHiSuf = f}
2623 setHcSuf f d = d { hcSuf = f}
2624
2625 setOutputFile f d = d { outputFile = f}
2626 setDynOutputFile f d = d { dynOutputFile = f}
2627 setOutputHi f d = d { outputHi = f}
2628
2629 setJsonLogAction :: DynFlags -> DynFlags
2630 setJsonLogAction d = d { log_action = jsonLogAction }
2631
2632 thisComponentId :: DynFlags -> ComponentId
2633 thisComponentId dflags =
2634 case thisComponentId_ dflags of
2635 Just cid -> cid
2636 Nothing ->
2637 case thisUnitIdInsts_ dflags of
2638 Just _ ->
2639 throwGhcException $ CmdLineError ("Use of -instantiated-with requires -this-component-id")
2640 Nothing -> ComponentId (unitIdFS (thisPackage dflags))
2641
2642 thisUnitIdInsts :: DynFlags -> [(ModuleName, Module)]
2643 thisUnitIdInsts dflags =
2644 case thisUnitIdInsts_ dflags of
2645 Just insts -> insts
2646 Nothing -> []
2647
2648 thisPackage :: DynFlags -> UnitId
2649 thisPackage dflags =
2650 case thisUnitIdInsts_ dflags of
2651 Nothing -> default_uid
2652 Just insts
2653 | all (\(x,y) -> mkHoleModule x == y) insts
2654 -> newUnitId (thisComponentId dflags) insts
2655 | otherwise
2656 -> default_uid
2657 where
2658 default_uid = DefiniteUnitId (DefUnitId (thisInstalledUnitId dflags))
2659
2660 parseUnitIdInsts :: String -> [(ModuleName, Module)]
2661 parseUnitIdInsts str = case filter ((=="").snd) (readP_to_S parse str) of
2662 [(r, "")] -> r
2663 _ -> throwGhcException $ CmdLineError ("Can't parse -instantiated-with: " ++ str)
2664 where parse = sepBy parseEntry (R.char ',')
2665 parseEntry = do
2666 n <- parseModuleName
2667 _ <- R.char '='
2668 m <- parseModuleId
2669 return (n, m)
2670
2671 setUnitIdInsts :: String -> DynFlags -> DynFlags
2672 setUnitIdInsts s d =
2673 d { thisUnitIdInsts_ = Just (parseUnitIdInsts s) }
2674
2675 setComponentId :: String -> DynFlags -> DynFlags
2676 setComponentId s d =
2677 d { thisComponentId_ = Just (ComponentId (fsLit s)) }
2678
2679 addPluginModuleName :: String -> DynFlags -> DynFlags
2680 addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
2681
2682 clearPluginModuleNames :: DynFlags -> DynFlags
2683 clearPluginModuleNames d =
2684 d { pluginModNames = []
2685 , pluginModNameOpts = []
2686 , cachedPlugins = [] }
2687
2688 addPluginModuleNameOption :: String -> DynFlags -> DynFlags
2689 addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
2690 where (m, rest) = break (== ':') optflag
2691 option = case rest of
2692 [] -> "" -- should probably signal an error
2693 (_:plug_opt) -> plug_opt -- ignore the ':' from break
2694
2695 addFrontendPluginOption :: String -> DynFlags -> DynFlags
2696 addFrontendPluginOption s d = d { frontendPluginOpts = s : frontendPluginOpts d }
2697
2698 parseDynLibLoaderMode f d =
2699 case splitAt 8 f of
2700 ("deploy", "") -> d { dynLibLoader = Deployable }
2701 ("sysdep", "") -> d { dynLibLoader = SystemDependent }
2702 _ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f))
2703
2704 setDumpPrefixForce f d = d { dumpPrefixForce = f}
2705
2706 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
2707 -- Config.hs should really use Option.
2708 setPgmP f = alterToolSettings (\s -> s { toolSettings_pgm_P = (pgm, map Option args)})
2709 where (pgm:args) = words f
2710 addOptl f = alterToolSettings (\s -> s { toolSettings_opt_l = f : toolSettings_opt_l s})
2711 addOptc f = alterToolSettings (\s -> s { toolSettings_opt_c = f : toolSettings_opt_c s})
2712 addOptcxx f = alterToolSettings (\s -> s { toolSettings_opt_cxx = f : toolSettings_opt_cxx s})
2713 addOptP f = alterToolSettings $ \s -> s
2714 { toolSettings_opt_P = f : toolSettings_opt_P s
2715 , toolSettings_opt_P_fingerprint = fingerprintStrings (f : toolSettings_opt_P s)
2716 }
2717 -- See Note [Repeated -optP hashing]
2718 where
2719 fingerprintStrings ss = fingerprintFingerprints $ map fingerprintString ss
2720
2721
2722 setDepMakefile :: FilePath -> DynFlags -> DynFlags
2723 setDepMakefile f d = d { depMakefile = f }
2724
2725 setDepIncludeCppDeps :: Bool -> DynFlags -> DynFlags
2726 setDepIncludeCppDeps b d = d { depIncludeCppDeps = b }
2727
2728 setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
2729 setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
2730
2731 addDepExcludeMod :: String -> DynFlags -> DynFlags
2732 addDepExcludeMod m d
2733 = d { depExcludeMods = mkModuleName m : depExcludeMods d }
2734
2735 addDepSuffix :: FilePath -> DynFlags -> DynFlags
2736 addDepSuffix s d = d { depSuffixes = s : depSuffixes d }
2737
2738 addCmdlineFramework f d = d { cmdlineFrameworks = f : cmdlineFrameworks d}
2739
2740 addGhcVersionFile :: FilePath -> DynFlags -> DynFlags
2741 addGhcVersionFile f d = d { ghcVersionFile = Just f }
2742
2743 addHaddockOpts f d = d { haddockOptions = Just f}
2744
2745 addGhciScript f d = d { ghciScripts = f : ghciScripts d}
2746
2747 setInteractivePrint f d = d { interactivePrint = Just f}
2748
2749 -----------------------------------------------------------------------------
2750 -- Setting the optimisation level
2751
2752 updOptLevel :: Int -> DynFlags -> DynFlags
2753 -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
2754 updOptLevel n dfs
2755 = dfs2{ optLevel = final_n }
2756 where
2757 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
2758 dfs1 = foldr (flip gopt_unset) dfs remove_gopts
2759 dfs2 = foldr (flip gopt_set) dfs1 extra_gopts
2760
2761 extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
2762 remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
2763
2764 {- **********************************************************************
2765 %* *
2766 DynFlags parser
2767 %* *
2768 %********************************************************************* -}
2769
2770 -- -----------------------------------------------------------------------------
2771 -- Parsing the dynamic flags.
2772
2773
2774 -- | Parse dynamic flags from a list of command line arguments. Returns
2775 -- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
2776 -- Throws a 'UsageError' if errors occurred during parsing (such as unknown
2777 -- flags or missing arguments).
2778 parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String]
2779 -> m (DynFlags, [Located String], [Warn])
2780 -- ^ Updated 'DynFlags', left-over arguments, and
2781 -- list of warnings.
2782 parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True
2783
2784
2785 -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
2786 -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db).
2787 -- Used to parse flags set in a modules pragma.
2788 parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String]
2789 -> m (DynFlags, [Located String], [Warn])
2790 -- ^ Updated 'DynFlags', left-over arguments, and
2791 -- list of warnings.
2792 parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False
2793
2794
2795 -- | Parses the dynamically set flags for GHC. This is the most general form of
2796 -- the dynamic flag parser that the other methods simply wrap. It allows
2797 -- saying which flags are valid flags and indicating if we are parsing
2798 -- arguments from the command line or from a file pragma.
2799 parseDynamicFlagsFull :: MonadIO m
2800 => [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against
2801 -> Bool -- ^ are the arguments from the command line?
2802 -> DynFlags -- ^ current dynamic flags
2803 -> [Located String] -- ^ arguments to parse
2804 -> m (DynFlags, [Located String], [Warn])
2805 parseDynamicFlagsFull activeFlags cmdline dflags0 args = do
2806 let ((leftover, errs, warns), dflags1)
2807 = runCmdLine (processArgs activeFlags args) dflags0
2808
2809 -- See Note [Handling errors when parsing commandline flags]
2810 unless (null errs) $ liftIO $ throwGhcExceptionIO $ errorsToGhcException $
2811 map ((showPpr dflags0 . getLoc &&& unLoc) . errMsg) $ errs
2812
2813 -- check for disabled flags in safe haskell
2814 let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1
2815 dflags3 = updateWays dflags2
2816 theWays = ways dflags3
2817
2818 unless (allowed_combination theWays) $ liftIO $
2819 throwGhcExceptionIO (CmdLineError ("combination not supported: " ++
2820 intercalate "/" (map wayDesc theWays)))
2821
2822 let chooseOutput
2823 | isJust (outputFile dflags3) -- Only iff user specified -o ...
2824 , not (isJust (dynOutputFile dflags3)) -- but not -dyno
2825 = return $ dflags3 { dynOutputFile = Just $ dynamicOutputFile dflags3 outFile }
2826 | otherwise
2827 = return dflags3
2828 where
2829 outFile = fromJust $ outputFile dflags3
2830 dflags4 <- ifGeneratingDynamicToo dflags3 chooseOutput (return dflags3)
2831
2832 let (dflags5, consistency_warnings) = makeDynFlagsConsistent dflags4
2833
2834 -- Set timer stats & heap size
2835 when (enableTimeStats dflags5) $ liftIO enableTimingStats
2836 case (ghcHeapSize dflags5) of
2837 Just x -> liftIO (setHeapSize x)
2838 _ -> return ()
2839
2840 liftIO $ setUnsafeGlobalDynFlags dflags5
2841
2842 let warns' = map (Warn Cmd.NoReason) (consistency_warnings ++ sh_warns)
2843
2844 return (dflags5, leftover, warns' ++ warns)
2845
2846 -- | Write an error or warning to the 'LogOutput'.
2847 putLogMsg :: DynFlags -> WarnReason -> Severity -> SrcSpan -> PprStyle
2848 -> MsgDoc -> IO ()
2849 putLogMsg dflags = log_action dflags dflags
2850
2851 updateWays :: DynFlags -> DynFlags
2852 updateWays dflags
2853 = let theWays = sort $ nub $ ways dflags
2854 in dflags {
2855 ways = theWays,
2856 buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays)
2857 }
2858
2859 -- | Check (and potentially disable) any extensions that aren't allowed
2860 -- in safe mode.
2861 --
2862 -- The bool is to indicate if we are parsing command line flags (false means
2863 -- file pragma). This allows us to generate better warnings.
2864 safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
2865 safeFlagCheck _ dflags | safeLanguageOn dflags = (dflagsUnset, warns)
2866 where
2867 -- Handle illegal flags under safe language.
2868 (dflagsUnset, warns) = foldl' check_method (dflags, []) unsafeFlags
2869
2870 check_method (df, warns) (str,loc,test,fix)
2871 | test df = (fix df, warns ++ safeFailure (loc df) str)
2872 | otherwise = (df, warns)
2873
2874 safeFailure loc str
2875 = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring "
2876 ++ str]
2877
2878 safeFlagCheck cmdl dflags =
2879 case (safeInferOn dflags) of
2880 True | safeFlags -> (dflags', warn)
2881 True -> (dflags' { safeInferred = False }, warn)
2882 False -> (dflags', warn)
2883
2884 where
2885 -- dynflags and warn for when -fpackage-trust by itself with no safe
2886 -- haskell flag
2887 (dflags', warn)
2888 | not (safeHaskellModeEnabled dflags) && not cmdl && packageTrustOn dflags
2889 = (gopt_unset dflags Opt_PackageTrust, pkgWarnMsg)
2890 | otherwise = (dflags, [])
2891
2892 pkgWarnMsg = [L (pkgTrustOnLoc dflags') $
2893 "-fpackage-trust ignored;" ++
2894 " must be specified with a Safe Haskell flag"]
2895
2896 -- Have we inferred Unsafe? See Note [HscMain . Safe Haskell Inference]
2897 safeFlags = all (\(_,_,t,_) -> not $ t dflags) unsafeFlagsForInfer
2898
2899
2900 {- **********************************************************************
2901 %* *
2902 DynFlags specifications
2903 %* *
2904 %********************************************************************* -}
2905
2906 -- | All dynamic flags option strings without the deprecated ones.
2907 -- These are the user facing strings for enabling and disabling options.
2908 allNonDeprecatedFlags :: [String]
2909 allNonDeprecatedFlags = allFlagsDeps False
2910
2911 -- | All flags with possibility to filter deprecated ones
2912 allFlagsDeps :: Bool -> [String]
2913 allFlagsDeps keepDeprecated = [ '-':flagName flag
2914 | (deprecated, flag) <- flagsAllDeps
2915 , keepDeprecated || not (isDeprecated deprecated)]
2916 where isDeprecated Deprecated = True
2917 isDeprecated _ = False
2918
2919 {-
2920 - Below we export user facing symbols for GHC dynamic flags for use with the
2921 - GHC API.
2922 -}
2923
2924 -- All dynamic flags present in GHC.
2925 flagsAll :: [Flag (CmdLineP DynFlags)]
2926 flagsAll = map snd flagsAllDeps
2927
2928 -- All dynamic flags present in GHC with deprecation information.
2929 flagsAllDeps :: [(Deprecation, Flag (CmdLineP DynFlags))]
2930 flagsAllDeps = package_flags_deps ++ dynamic_flags_deps
2931
2932
2933 -- All dynamic flags, minus package flags, present in GHC.
2934 flagsDynamic :: [Flag (CmdLineP DynFlags)]
2935 flagsDynamic = map snd dynamic_flags_deps
2936
2937 -- ALl package flags present in GHC.
2938 flagsPackage :: [Flag (CmdLineP DynFlags)]
2939 flagsPackage = map snd package_flags_deps
2940
2941 ----------------Helpers to make flags and keep deprecation information----------
2942
2943 type FlagMaker m = String -> OptKind m -> Flag m
2944 type DynFlagMaker = FlagMaker (CmdLineP DynFlags)
2945 data Deprecation = NotDeprecated | Deprecated deriving (Eq, Ord)
2946
2947 -- Make a non-deprecated flag
2948 make_ord_flag :: DynFlagMaker -> String -> OptKind (CmdLineP DynFlags)
2949 -> (Deprecation, Flag (CmdLineP DynFlags))
2950 make_ord_flag fm name kind = (NotDeprecated, fm name kind)
2951
2952 -- Make a deprecated flag
2953 make_dep_flag :: DynFlagMaker -> String -> OptKind (CmdLineP DynFlags) -> String
2954 -> (Deprecation, Flag (CmdLineP DynFlags))
2955 make_dep_flag fm name kind message = (Deprecated,
2956 fm name $ add_dep_message kind message)
2957
2958 add_dep_message :: OptKind (CmdLineP DynFlags) -> String
2959 -> OptKind (CmdLineP DynFlags)
2960 add_dep_message (NoArg f) message = NoArg $ f >> deprecate message
2961 add_dep_message (HasArg f) message = HasArg $ \s -> f s >> deprecate message
2962 add_dep_message (SepArg f) message = SepArg $ \s -> f s >> deprecate message
2963 add_dep_message (Prefix f) message = Prefix $ \s -> f s >> deprecate message
2964 add_dep_message (OptPrefix f) message =
2965 OptPrefix $ \s -> f s >> deprecate message
2966 add_dep_message (OptIntSuffix f) message =
2967 OptIntSuffix $ \oi -> f oi >> deprecate message
2968 add_dep_message (IntSuffix f) message =
2969 IntSuffix $ \i -> f i >> deprecate message
2970 add_dep_message (FloatSuffix f) message =
2971 FloatSuffix $ \fl -> f fl >> deprecate message
2972 add_dep_message (PassFlag f) message =
2973 PassFlag $ \s -> f s >> deprecate message
2974 add_dep_message (AnySuffix f) message =
2975 AnySuffix $ \s -> f s >> deprecate message
2976
2977 ----------------------- The main flags themselves ------------------------------
2978 -- See Note [Updating flag description in the User's Guide]
2979 -- See Note [Supporting CLI completion]
2980 dynamic_flags_deps :: [(Deprecation, Flag (CmdLineP DynFlags))]
2981 dynamic_flags_deps = [
2982 make_dep_flag defFlag "n" (NoArg $ return ())
2983 "The -n flag is deprecated and no longer has any effect"
2984 , make_ord_flag defFlag "cpp" (NoArg (setExtensionFlag LangExt.Cpp))
2985 , make_ord_flag defFlag "F" (NoArg (setGeneralFlag Opt_Pp))
2986 , (Deprecated, defFlag "#include"
2987 (HasArg (\_s ->
2988 deprecate ("-#include and INCLUDE pragmas are " ++
2989 "deprecated: They no longer have any effect"))))
2990 , make_ord_flag defFlag "v" (OptIntSuffix setVerbosity)
2991
2992 , make_ord_flag defGhcFlag "j" (OptIntSuffix
2993 (\n -> case n of
2994 Just n
2995 | n > 0 -> upd (\d -> d { parMakeCount = Just n })
2996 | otherwise -> addErr "Syntax: -j[n] where n > 0"
2997 Nothing -> upd (\d -> d { parMakeCount = Nothing })))
2998 -- When the number of parallel builds
2999 -- is omitted, it is the same
3000 -- as specifing that the number of
3001 -- parallel builds is equal to the
3002 -- result of getNumProcessors
3003 , make_ord_flag defFlag "instantiated-with" (sepArg setUnitIdInsts)
3004 , make_ord_flag defFlag "this-component-id" (sepArg setComponentId)
3005
3006 -- RTS options -------------------------------------------------------------
3007 , make_ord_flag defFlag "H" (HasArg (\s -> upd (\d ->
3008 d { ghcHeapSize = Just $ fromIntegral (decodeSize s)})))
3009
3010 , make_ord_flag defFlag "Rghc-timing" (NoArg (upd (\d ->
3011 d { enableTimeStats = True })))
3012
3013 ------- ways ---------------------------------------------------------------
3014 , make_ord_flag defGhcFlag "prof" (NoArg (addWay WayProf))
3015 , make_ord_flag defGhcFlag "eventlog" (NoArg (addWay WayEventLog))
3016 , make_dep_flag defGhcFlag "smp"
3017 (NoArg $ addWay WayThreaded) "Use -threaded instead"
3018 , make_ord_flag defGhcFlag "debug" (NoArg (addWay WayDebug))
3019 , make_ord_flag defGhcFlag "threaded" (NoArg (addWay WayThreaded))
3020
3021 , make_ord_flag defGhcFlag "ticky"
3022 (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug))
3023
3024 -- -ticky enables ticky-ticky code generation, and also implies -debug which
3025 -- is required to get the RTS ticky support.
3026
3027 ----- Linker --------------------------------------------------------
3028 , make_ord_flag defGhcFlag "static" (NoArg removeWayDyn)
3029 , make_ord_flag defGhcFlag "dynamic" (NoArg (addWay WayDyn))
3030 , make_ord_flag defGhcFlag "rdynamic" $ noArg $
3031 #if defined(linux_HOST_OS)
3032 addOptl "-rdynamic"
3033 #elif defined(mingw32_HOST_OS)
3034 addOptl "-Wl,--export-all-symbols"
3035 #else
3036 -- ignored for compat w/ gcc:
3037 id
3038 #endif
3039 , make_ord_flag defGhcFlag "relative-dynlib-paths"
3040 (NoArg (setGeneralFlag Opt_RelativeDynlibPaths))
3041 , make_ord_flag defGhcFlag "copy-libs-when-linking"
3042 (NoArg (setGeneralFlag Opt_SingleLibFolder))
3043 , make_ord_flag defGhcFlag "pie" (NoArg (setGeneralFlag Opt_PICExecutable))
3044 , make_ord_flag defGhcFlag "no-pie" (NoArg (unSetGeneralFlag Opt_PICExecutable))
3045
3046 ------- Specific phases --------------------------------------------
3047 -- need to appear before -pgmL to be parsed as LLVM flags.
3048 , make_ord_flag defFlag "pgmlo"
3049 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_lo = (f,[]) }
3050 , make_ord_flag defFlag "pgmlc"
3051 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_lc = (f,[]) }
3052 , make_ord_flag defFlag "pgmi"
3053 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_i = f }
3054 , make_ord_flag defFlag "pgmL"
3055 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_L = f }
3056 , make_ord_flag defFlag "pgmP"
3057 (hasArg setPgmP)
3058 , make_ord_flag defFlag "pgmF"
3059 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_F = f }
3060 , make_ord_flag defFlag "pgmc"
3061 $ hasArg $ \f -> alterToolSettings $ \s -> s
3062 { toolSettings_pgm_c = f
3063 , -- Don't pass -no-pie with -pgmc
3064 -- (see #15319)
3065 toolSettings_ccSupportsNoPie = False
3066 }
3067 , make_ord_flag defFlag "pgms"
3068 (HasArg (\_ -> addWarn "Object splitting was removed in GHC 8.8"))
3069 , make_ord_flag defFlag "pgma"
3070 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_a = (f,[]) }
3071 , make_ord_flag defFlag "pgml"
3072 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_l = (f,[]) }
3073 , make_ord_flag defFlag "pgmdll"
3074 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_dll = (f,[]) }
3075 , make_ord_flag defFlag "pgmwindres"
3076 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_windres = f }
3077 , make_ord_flag defFlag "pgmlibtool"
3078 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_libtool = f }
3079 , make_ord_flag defFlag "pgmar"
3080 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_ar = f }
3081 , make_ord_flag defFlag "pgmranlib"
3082 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_ranlib = f }
3083
3084
3085 -- need to appear before -optl/-opta to be parsed as LLVM flags.
3086 , make_ord_flag defFlag "optlo"
3087 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_opt_lo = f : toolSettings_opt_lo s }
3088 , make_ord_flag defFlag "optlc"
3089 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_opt_lc = f : toolSettings_opt_lc s }
3090 , make_ord_flag defFlag "opti"
3091 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_opt_i = f : toolSettings_opt_i s }
3092 , make_ord_flag defFlag "optL"
3093 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_opt_L = f : toolSettings_opt_L s }
3094 , make_ord_flag defFlag "optP"
3095 (hasArg addOptP)
3096 , make_ord_flag defFlag "optF"
3097 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_opt_F = f : toolSettings_opt_F s }
3098 , make_ord_flag defFlag "optc"
3099 (hasArg addOptc)
3100 , make_ord_flag defFlag "optcxx"
3101 (hasArg addOptcxx)
3102 , make_ord_flag defFlag "opta"
3103 $ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_opt_a = f : toolSettings_opt_a s }
3104 , make_ord_flag defFlag "optl"
3105 (hasArg addOptl)
3106 , make_ord_flag defFlag "optwindres"
3107 $ hasArg $ \f ->
3108 alterToolSettings $ \s -> s { toolSettings_opt_windres = f : toolSettings_opt_windres s }
3109
3110 , make_ord_flag defGhcFlag "split-objs"
3111 (NoArg $ addWarn "ignoring -split-objs")
3112
3113 , make_ord_flag defGhcFlag "split-sections"
3114 (noArgM (\dflags -> do
3115 if platformHasSubsectionsViaSymbols (targetPlatform dflags)
3116 then do addWarn $
3117 "-split-sections is not useful on this platform " ++
3118 "since it always uses subsections via symbols. Ignoring."
3119 return dflags
3120 else return (gopt_set dflags Opt_SplitSections)))
3121
3122 -------- ghc -M -----------------------------------------------------
3123 , make_ord_flag defGhcFlag "dep-suffix" (hasArg addDepSuffix)
3124 , make_ord_flag defGhcFlag "dep-makefile" (hasArg setDepMakefile)
3125 , make_ord_flag defGhcFlag "include-cpp-deps"
3126 (noArg (setDepIncludeCppDeps True))
3127 , make_ord_flag defGhcFlag "include-pkg-deps"
3128 (noArg (setDepIncludePkgDeps True))
3129 , make_ord_flag defGhcFlag "exclude-module" (hasArg addDepExcludeMod)
3130
3131 -------- Linking ----------------------------------------------------
3132 , make_ord_flag defGhcFlag "no-link"
3133 (noArg (\d -> d { ghcLink=NoLink }))
3134 , make_ord_flag defGhcFlag "shared"
3135 (noArg (\d -> d { ghcLink=LinkDynLib }))
3136 , make_ord_flag defGhcFlag "staticlib"
3137 (noArg (\d -> d { ghcLink=LinkStaticLib }))
3138 , make_ord_flag defGhcFlag "dynload" (hasArg parseDynLibLoaderMode)
3139 , make_ord_flag defGhcFlag "dylib-install-name" (hasArg setDylibInstallName)
3140
3141 ------- Libraries ---------------------------------------------------
3142 , make_ord_flag defFlag "L" (Prefix addLibraryPath)
3143 , make_ord_flag defFlag "l" (hasArg (addLdInputs . Option . ("-l" ++)))
3144
3145 ------- Frameworks --------------------------------------------------
3146 -- -framework-path should really be -F ...
3147 , make_ord_flag defFlag "framework-path" (HasArg addFrameworkPath)
3148 , make_ord_flag defFlag "framework" (hasArg addCmdlineFramework)
3149
3150 ------- Output Redirection ------------------------------------------
3151 , make_ord_flag defGhcFlag "odir" (hasArg setObjectDir)
3152 , make_ord_flag defGhcFlag "o" (sepArg (setOutputFile . Just))
3153 , make_ord_flag defGhcFlag "dyno"
3154 (sepArg (setDynOutputFile . Just))
3155 , make_ord_flag defGhcFlag "ohi"
3156 (hasArg (setOutputHi . Just ))
3157 , make_ord_flag defGhcFlag "osuf" (hasArg setObjectSuf)
3158 , make_ord_flag defGhcFlag "dynosuf" (hasArg setDynObjectSuf)
3159 , make_ord_flag defGhcFlag "hcsuf" (hasArg setHcSuf)
3160 , make_ord_flag defGhcFlag "hisuf" (hasArg setHiSuf)
3161 , make_ord_flag defGhcFlag "hiesuf" (hasArg setHieSuf)
3162 , make_ord_flag defGhcFlag "dynhisuf" (hasArg setDynHiSuf)
3163 , make_ord_flag defGhcFlag "hidir" (hasArg setHiDir)
3164 , make_ord_flag defGhcFlag "hiedir" (hasArg setHieDir)
3165 , make_ord_flag defGhcFlag "tmpdir" (hasArg setTmpDir)
3166 , make_ord_flag defGhcFlag "stubdir" (hasArg setStubDir)
3167 , make_ord_flag defGhcFlag "dumpdir" (hasArg setDumpDir)
3168 , make_ord_flag defGhcFlag "outputdir" (hasArg setOutputDir)
3169 , make_ord_flag defGhcFlag "ddump-file-prefix"
3170 (hasArg (setDumpPrefixForce . Just))
3171
3172 , make_ord_flag defGhcFlag "dynamic-too"
3173 (NoArg (setGeneralFlag Opt_BuildDynamicToo))
3174
3175 ------- Keeping temporary files -------------------------------------
3176 -- These can be singular (think ghc -c) or plural (think ghc --make)
3177 , make_ord_flag defGhcFlag "keep-hc-file"
3178 (NoArg (setGeneralFlag Opt_KeepHcFiles))
3179 , make_ord_flag defGhcFlag "keep-hc-files"
3180 (NoArg (setGeneralFlag Opt_KeepHcFiles))
3181 , make_ord_flag defGhcFlag "keep-hscpp-file"
3182 (NoArg (setGeneralFlag Opt_KeepHscppFiles))
3183 , make_ord_flag defGhcFlag "keep-hscpp-files"
3184 (NoArg (setGeneralFlag Opt_KeepHscppFiles))
3185 , make_ord_flag defGhcFlag "keep-s-file"
3186 (NoArg (setGeneralFlag Opt_KeepSFiles))
3187 , make_ord_flag defGhcFlag "keep-s-files"
3188 (NoArg (setGeneralFlag Opt_KeepSFiles))
3189 , make_ord_flag defGhcFlag "keep-llvm-file"
3190 (NoArg $ setObjTarget HscLlvm >> setGeneralFlag Opt_KeepLlvmFiles)
3191 , make_ord_flag defGhcFlag "keep-llvm-files"
3192 (NoArg $ setObjTarget HscLlvm >> setGeneralFlag Opt_KeepLlvmFiles)
3193 -- This only makes sense as plural
3194 , make_ord_flag defGhcFlag "keep-tmp-files"
3195 (NoArg (setGeneralFlag Opt_KeepTmpFiles))
3196 , make_ord_flag defGhcFlag "keep-hi-file"
3197 (NoArg (setGeneralFlag Opt_KeepHiFiles))
3198 , make_ord_flag defGhcFlag "no-keep-hi-file"
3199 (NoArg (unSetGeneralFlag Opt_KeepHiFiles))
3200 , make_ord_flag defGhcFlag "keep-hi-files"
3201 (NoArg (setGeneralFlag Opt_KeepHiFiles))
3202 , make_ord_flag defGhcFlag "no-keep-hi-files"
3203 (NoArg (unSetGeneralFlag Opt_KeepHiFiles))
3204 , make_ord_flag defGhcFlag "keep-o-file"
3205 (NoArg (setGeneralFlag Opt_KeepOFiles))
3206 , make_ord_flag defGhcFlag "no-keep-o-file"
3207 (NoArg (unSetGeneralFlag Opt_KeepOFiles))
3208 , make_ord_flag defGhcFlag "keep-o-files"
3209 (NoArg (setGeneralFlag Opt_KeepOFiles))
3210 , make_ord_flag defGhcFlag "no-keep-o-files"
3211 (NoArg (unSetGeneralFlag Opt_KeepOFiles))
3212
3213 ------- Miscellaneous ----------------------------------------------
3214 , make_ord_flag defGhcFlag "no-auto-link-packages"
3215 (NoArg (unSetGeneralFlag Opt_AutoLinkPackages))
3216 , make_ord_flag defGhcFlag "no-hs-main"
3217 (NoArg (setGeneralFlag Opt_NoHsMain))
3218 , make_ord_flag defGhcFlag "fno-state-hack"
3219 (NoArg (setGeneralFlag Opt_G_NoStateHack))
3220 , make_ord_flag defGhcFlag "fno-opt-coercion"
3221 (NoArg (setGeneralFlag Opt_G_NoOptCoercion))
3222 , make_ord_flag defGhcFlag "with-rtsopts"
3223 (HasArg setRtsOpts)
3224 , make_ord_flag defGhcFlag "rtsopts"
3225 (NoArg (setRtsOptsEnabled RtsOptsAll))
3226 , make_ord_flag defGhcFlag "rtsopts=all"
3227 (NoArg (setRtsOptsEnabled RtsOptsAll))
3228 , make_ord_flag defGhcFlag "rtsopts=some"
3229 (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
3230 , make_ord_flag defGhcFlag "rtsopts=none"
3231 (NoArg (setRtsOptsEnabled RtsOptsNone))
3232 , make_ord_flag defGhcFlag "rtsopts=ignore"
3233 (NoArg (setRtsOptsEnabled RtsOptsIgnore))
3234 , make_ord_flag defGhcFlag "rtsopts=ignoreAll"
3235 (NoArg (setRtsOptsEnabled RtsOptsIgnoreAll))
3236 , make_ord_flag defGhcFlag "no-rtsopts"
3237 (NoArg (setRtsOptsEnabled RtsOptsNone))
3238 , make_ord_flag defGhcFlag "no-rtsopts-suggestions"
3239 (noArg (\d -> d {rtsOptsSuggestions = False}))
3240 , make_ord_flag defGhcFlag "dhex-word-literals"
3241 (NoArg (setGeneralFlag Opt_HexWordLiterals))
3242
3243 , make_ord_flag defGhcFlag "ghcversion-file" (hasArg addGhcVersionFile)
3244 , make_ord_flag defGhcFlag "main-is" (SepArg setMainIs)
3245 , make_ord_flag defGhcFlag "haddock" (NoArg (setGeneralFlag Opt_Haddock))
3246 , make_ord_flag defGhcFlag "haddock-opts" (hasArg addHaddockOpts)
3247 , make_ord_flag defGhcFlag "hpcdir" (SepArg setOptHpcDir)
3248 , make_ord_flag defGhciFlag "ghci-script" (hasArg addGhciScript)
3249 , make_ord_flag defGhciFlag "interactive-print" (hasArg setInteractivePrint)
3250 , make_ord_flag defGhcFlag "ticky-allocd"
3251 (NoArg (setGeneralFlag Opt_Ticky_Allocd))
3252 , make_ord_flag defGhcFlag "ticky-LNE"
3253 (NoArg (setGeneralFlag Opt_Ticky_LNE))
3254 , make_ord_flag defGhcFlag "ticky-dyn-thunk"
3255 (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk))
3256 ------- recompilation checker --------------------------------------
3257 , make_dep_flag defGhcFlag "recomp"
3258 (NoArg $ unSetGeneralFlag Opt_ForceRecomp)
3259 "Use -fno-force-recomp instead"
3260 , make_dep_flag defGhcFlag "no-recomp"
3261 (NoArg $ setGeneralFlag Opt_ForceRecomp) "Use -fforce-recomp instead"
3262 , make_ord_flag defFlag "fmax-errors"
3263 (intSuffix (\n d -> d { maxErrors = Just (max 1 n) }))
3264 , make_ord_flag defFlag "fno-max-errors"
3265 (noArg (\d -> d { maxErrors = Nothing }))
3266 , make_ord_flag defFlag "freverse-errors"
3267 (noArg (\d -> d {reverseErrors = True} ))
3268 , make_ord_flag defFlag "fno-reverse-errors"
3269 (noArg (\d -> d {reverseErrors = False} ))
3270
3271 ------ HsCpp opts ---------------------------------------------------
3272 , make_ord_flag defFlag "D" (AnySuffix (upd . addOptP))
3273 , make_ord_flag defFlag "U" (AnySuffix (upd . addOptP))
3274
3275 ------- Include/Import Paths ----------------------------------------
3276 , make_ord_flag defFlag "I" (Prefix addIncludePath)
3277 , make_ord_flag defFlag "i" (OptPrefix addImportPath)
3278
3279 ------ Output style options -----------------------------------------
3280 , make_ord_flag defFlag "dppr-user-length" (intSuffix (\n d ->
3281 d { pprUserLength = n }))
3282 , make_ord_flag defFlag "dppr-cols" (intSuffix (\n d ->
3283 d { pprCols = n }))
3284 , make_ord_flag defFlag "fdiagnostics-color=auto"
3285 (NoArg (upd (\d -> d { useColor = Auto })))
3286 , make_ord_flag defFlag "fdiagnostics-color=always"
3287 (NoArg (upd (\d -> d { useColor = Always })))
3288 , make_ord_flag defFlag "fdiagnostics-color=never"
3289 (NoArg (upd (\d -> d { useColor = Never })))
3290
3291 -- Suppress all that is suppressable in core dumps.
3292 -- Except for uniques, as some simplifier phases introduce new variables that
3293 -- have otherwise identical names.
3294 , make_ord_flag defGhcFlag "dsuppress-all"
3295 (NoArg $ do setGeneralFlag Opt_SuppressCoercions
3296 setGeneralFlag Opt_SuppressVarKinds
3297 setGeneralFlag Opt_SuppressModulePrefixes
3298 setGeneralFlag Opt_SuppressTypeApplications
3299 setGeneralFlag Opt_SuppressIdInfo
3300 setGeneralFlag Opt_SuppressTicks
3301 setGeneralFlag Opt_SuppressStgExts
3302 setGeneralFlag Opt_SuppressTypeSignatures
3303 setGeneralFlag Opt_SuppressTimestamps)
3304
3305 ------ Debugging ----------------------------------------------------
3306 , make_ord_flag defGhcFlag "dstg-stats"
3307 (NoArg (setGeneralFlag Opt_StgStats))
3308
3309 , make_ord_flag defGhcFlag "ddump-cmm"
3310 (setDumpFlag Opt_D_dump_cmm)
3311 , make_ord_flag defGhcFlag "ddump-cmm-from-stg"
3312 (setDumpFlag Opt_D_dump_cmm_from_stg)
3313 , make_ord_flag defGhcFlag "ddump-cmm-raw"
3314 (setDumpFlag Opt_D_dump_cmm_raw)
3315 , make_ord_flag defGhcFlag "ddump-cmm-verbose"
3316 (setDumpFlag Opt_D_dump_cmm_verbose)
3317 , make_ord_flag defGhcFlag "ddump-cmm-verbose-by-proc"
3318 (setDumpFlag Opt_D_dump_cmm_verbose_by_proc)
3319 , make_ord_flag defGhcFlag "ddump-cmm-cfg"
3320 (setDumpFlag Opt_D_dump_cmm_cfg)
3321 , make_ord_flag defGhcFlag "ddump-cmm-cbe"
3322 (setDumpFlag Opt_D_dump_cmm_cbe)
3323 , make_ord_flag defGhcFlag "ddump-cmm-switch"
3324 (setDumpFlag Opt_D_dump_cmm_switch)
3325 , make_ord_flag defGhcFlag "ddump-cmm-proc"
3326 (setDumpFlag Opt_D_dump_cmm_proc)
3327 , make_ord_flag defGhcFlag "ddump-cmm-sp"
3328 (setDumpFlag Opt_D_dump_cmm_sp)
3329 , make_ord_flag defGhcFlag "ddump-cmm-sink"
3330 (setDumpFlag Opt_D_dump_cmm_sink)
3331 , make_ord_flag defGhcFlag "ddump-cmm-caf"
3332 (setDumpFlag Opt_D_dump_cmm_caf)
3333 , make_ord_flag defGhcFlag "ddump-cmm-procmap"
3334 (setDumpFlag Opt_D_dump_cmm_procmap)
3335 , make_ord_flag defGhcFlag "ddump-cmm-split"
3336 (setDumpFlag Opt_D_dump_cmm_split)
3337 , make_ord_flag defGhcFlag "ddump-cmm-info"
3338 (setDumpFlag Opt_D_dump_cmm_info)
3339 , make_ord_flag defGhcFlag "ddump-cmm-cps"
3340 (setDumpFlag Opt_D_dump_cmm_cps)
3341 , make_ord_flag defGhcFlag "ddump-cfg-weights"
3342 (setDumpFlag Opt_D_dump_cfg_weights)
3343 , make_ord_flag defGhcFlag "ddump-core-stats"
3344 (setDumpFlag Opt_D_dump_core_stats)
3345 , make_ord_flag defGhcFlag "ddump-asm"
3346 (setDumpFlag Opt_D_dump_asm)
3347 , make_ord_flag defGhcFlag "ddump-asm-native"
3348 (setDumpFlag Opt_D_dump_asm_native)
3349 , make_ord_flag defGhcFlag "ddump-asm-liveness"
3350 (setDumpFlag Opt_D_dump_asm_liveness)
3351 , make_ord_flag defGhcFlag "ddump-asm-regalloc"
3352 (setDumpFlag Opt_D_dump_asm_regalloc)
3353 , make_ord_flag defGhcFlag "ddump-asm-conflicts"
3354 (setDumpFlag Opt_D_dump_asm_conflicts)
3355 , make_ord_flag defGhcFlag "ddump-asm-regalloc-stages"
3356 (setDumpFlag Opt_D_dump_asm_regalloc_stages)
3357 , make_ord_flag defGhcFlag "ddump-asm-stats"
3358 (setDumpFlag Opt_D_dump_asm_stats)
3359 , make_ord_flag defGhcFlag "ddump-asm-expanded"
3360 (setDumpFlag Opt_D_dump_asm_expanded)
3361 , make_ord_flag defGhcFlag "ddump-llvm"
3362 (NoArg $ setObjTarget HscLlvm >> setDumpFlag' Opt_D_dump_llvm)
3363 , make_ord_flag defGhcFlag "ddump-deriv"
3364 (setDumpFlag Opt_D_dump_deriv)
3365 , make_ord_flag defGhcFlag "ddump-ds"
3366 (setDumpFlag Opt_D_dump_ds)
3367 , make_ord_flag defGhcFlag "ddump-ds-preopt"
3368 (setDumpFlag Opt_D_dump_ds_preopt)
3369 , make_ord_flag defGhcFlag "ddump-foreign"
3370 (setDumpFlag Opt_D_dump_foreign)
3371 , make_ord_flag defGhcFlag "ddump-inlinings"
3372 (setDumpFlag Opt_D_dump_inlinings)
3373 , make_ord_flag defGhcFlag "ddump-rule-firings"
3374 (setDumpFlag Opt_D_dump_rule_firings)
3375 , make_ord_flag defGhcFlag "ddump-rule-rewrites"
3376 (setDumpFlag Opt_D_dump_rule_rewrites)
3377 , make_ord_flag defGhcFlag "ddump-simpl-trace"
3378 (setDumpFlag Opt_D_dump_simpl_trace)
3379 , make_ord_flag defGhcFlag "ddump-occur-anal"
3380 (setDumpFlag Opt_D_dump_occur_anal)
3381 , make_ord_flag defGhcFlag "ddump-parsed"
3382 (setDumpFlag Opt_D_dump_parsed)
3383 , make_ord_flag defGhcFlag "ddump-parsed-ast"
3384 (setDumpFlag Opt_D_dump_parsed_ast)
3385 , make_ord_flag defGhcFlag "ddump-rn"
3386 (setDumpFlag Opt_D_dump_rn)
3387 , make_ord_flag defGhcFlag "ddump-rn-ast"
3388 (setDumpFlag Opt_D_dump_rn_ast)
3389 , make_ord_flag defGhcFlag "ddump-simpl"
3390 (setDumpFlag Opt_D_dump_simpl)
3391 , make_ord_flag defGhcFlag "ddump-simpl-iterations"
3392 (setDumpFlag Opt_D_dump_simpl_iterations)
3393 , make_ord_flag defGhcFlag "ddump-spec"
3394 (setDumpFlag Opt_D_dump_spec)
3395 , make_ord_flag defGhcFlag "ddump-prep"
3396 (setDumpFlag Opt_D_dump_prep)
3397 , make_ord_flag defGhcFlag "ddump-stg"
3398 (setDumpFlag Opt_D_dump_stg)
3399 , make_ord_flag defGhcFlag "ddump-stg-final"
3400 (setDumpFlag Opt_D_dump_stg_final)
3401 , make_ord_flag defGhcFlag "ddump-call-arity"
3402 (setDumpFlag Opt_D_dump_call_arity)
3403 , make_ord_flag defGhcFlag "ddump-exitify"
3404 (setDumpFlag Opt_D_dump_exitify)
3405 , make_ord_flag defGhcFlag "ddump-stranal"
3406 (setDumpFlag Opt_D_dump_stranal)
3407 , make_ord_flag defGhcFlag "ddump-str-signatures"
3408 (setDumpFlag Opt_D_dump_str_signatures)
3409 , make_ord_flag defGhcFlag "ddump-tc"
3410 (setDumpFlag Opt_D_dump_tc)
3411 , make_ord_flag defGhcFlag "ddump-tc-ast"
3412 (setDumpFlag Opt_D_dump_tc_ast)
3413 , make_ord_flag defGhcFlag "ddump-types"
3414 (setDumpFlag Opt_D_dump_types)
3415 , make_ord_flag defGhcFlag "ddump-rules"
3416 (setDumpFlag Opt_D_dump_rules)
3417 , make_ord_flag defGhcFlag "ddump-cse"
3418 (setDumpFlag Opt_D_dump_cse)
3419 , make_ord_flag defGhcFlag "ddump-worker-wrapper"
3420 (setDumpFlag Opt_D_dump_worker_wrapper)
3421 , make_ord_flag defGhcFlag "ddump-rn-trace"
3422 (setDumpFlag Opt_D_dump_rn_trace)
3423 , make_ord_flag defGhcFlag "ddump-if-trace"
3424 (setDumpFlag Opt_D_dump_if_trace)
3425 , make_ord_flag defGhcFlag "ddump-cs-trace"
3426 (setDumpFlag Opt_D_dump_cs_trace)
3427 , make_ord_flag defGhcFlag "ddump-tc-trace"
3428 (NoArg (do setDumpFlag' Opt_D_dump_tc_trace
3429 setDumpFlag' Opt_D_dump_cs_trace))
3430 , make_ord_flag defGhcFlag "ddump-ec-trace"
3431 (setDumpFlag Opt_D_dump_ec_trace)
3432 , make_ord_flag defGhcFlag "ddump-vt-trace"
3433 (setDumpFlag Opt_D_dump_vt_trace)
3434 , make_ord_flag defGhcFlag "ddump-splices"
3435 (setDumpFlag Opt_D_dump_splices)
3436 , make_ord_flag defGhcFlag "dth-dec-file"
3437 (setDumpFlag Opt_D_th_dec_file)
3438
3439 , make_ord_flag defGhcFlag "ddump-rn-stats"
3440 (setDumpFlag Opt_D_dump_rn_stats)
3441 , make_ord_flag defGhcFlag "ddump-opt-cmm"
3442 (setDumpFlag Opt_D_dump_opt_cmm)
3443 , make_ord_flag defGhcFlag "ddump-simpl-stats"
3444 (setDumpFlag Opt_D_dump_simpl_stats)
3445 , make_ord_flag defGhcFlag "ddump-bcos"
3446 (setDumpFlag Opt_D_dump_BCOs)
3447 , make_ord_flag defGhcFlag "dsource-stats"
3448 (setDumpFlag Opt_D_source_stats)
3449 , make_ord_flag defGhcFlag "dverbose-core2core"
3450 (NoArg $ setVerbosity (Just 2) >> setVerboseCore2Core)
3451 , make_ord_flag defGhcFlag "dverbose-stg2stg"
3452 (setDumpFlag Opt_D_verbose_stg2stg)
3453 , make_ord_flag defGhcFlag "ddump-hi"
3454 (setDumpFlag Opt_D_dump_hi)
3455 , make_ord_flag defGhcFlag "ddump-minimal-imports"
3456 (NoArg (setGeneralFlag Opt_D_dump_minimal_imports))
3457 , make_ord_flag defGhcFlag "ddump-hpc"
3458 (setDumpFlag Opt_D_dump_ticked) -- back compat
3459 , make_ord_flag defGhcFlag "ddump-ticked"
3460 (setDumpFlag Opt_D_dump_ticked)
3461 , make_ord_flag defGhcFlag "ddump-mod-cycles"
3462 (setDumpFlag Opt_D_dump_mod_cycles)
3463 , make_ord_flag defGhcFlag "ddump-mod-map"
3464 (setDumpFlag Opt_D_dump_mod_map)
3465 , make_ord_flag defGhcFlag "ddump-timings"
3466 (setDumpFlag Opt_D_dump_timings)
3467 , make_ord_flag defGhcFlag "ddump-view-pattern-commoning"
3468 (setDumpFlag Opt_D_dump_view_pattern_commoning)
3469 , make_ord_flag defGhcFlag "ddump-to-file"
3470 (NoArg (setGeneralFlag Opt_DumpToFile))
3471 , make_ord_flag defGhcFlag "ddump-hi-diffs"
3472 (setDumpFlag Opt_D_dump_hi_diffs)
3473 , make_ord_flag defGhcFlag "ddump-rtti"
3474 (setDumpFlag Opt_D_dump_rtti)
3475 , make_ord_flag defGhcFlag "dcore-lint"
3476 (NoArg (setGeneralFlag Opt_DoCoreLinting))
3477 , make_ord_flag defGhcFlag "dstg-lint"
3478 (NoArg (setGeneralFlag Opt_DoStgLinting))
3479 , make_ord_flag defGhcFlag "dcmm-lint"
3480 (NoArg (setGeneralFlag Opt_DoCmmLinting))
3481 , make_ord_flag defGhcFlag "dasm-lint"
3482 (NoArg (setGeneralFlag Opt_DoAsmLinting))
3483 , make_ord_flag defGhcFlag "dannot-lint"
3484 (NoArg (setGeneralFlag Opt_DoAnnotationLinting))
3485 , make_ord_flag defGhcFlag "dshow-passes"
3486 (NoArg $ forceRecompile >> (setVerbosity $ Just 2))
3487 , make_ord_flag defGhcFlag "dfaststring-stats"
3488 (NoArg (setGeneralFlag Opt_D_faststring_stats))
3489 , make_ord_flag defGhcFlag "dno-llvm-mangler"
3490 (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag
3491 , make_ord_flag defGhcFlag "fast-llvm"
3492 (NoArg (setGeneralFlag Opt_FastLlvm)) -- hidden flag
3493 , make_ord_flag defGhcFlag "dno-typeable-binds"
3494 (NoArg (setGeneralFlag Opt_NoTypeableBinds))
3495 , make_ord_flag defGhcFlag "ddump-debug"
3496 (setDumpFlag Opt_D_dump_debug)
3497 , make_ord_flag defGhcFlag "ddump-json"
3498 (noArg (flip dopt_set Opt_D_dump_json . setJsonLogAction ) )
3499 , make_ord_flag defGhcFlag "dppr-debug"
3500 (setDumpFlag Opt_D_ppr_debug)
3501 , make_ord_flag defGhcFlag "ddebug-output"
3502 (noArg (flip dopt_unset Opt_D_no_debug_output))
3503 , make_ord_flag defGhcFlag "dno-debug-output"
3504 (setDumpFlag Opt_D_no_debug_output)
3505
3506 ------ Machine dependent (-m<blah>) stuff ---------------------------
3507
3508 , make_ord_flag defGhcFlag "msse" (noArg (\d ->
3509 d { sseVersion = Just SSE1 }))
3510 , make_ord_flag defGhcFlag "msse2" (noArg (\d ->
3511 d { sseVersion = Just SSE2 }))
3512 , make_ord_flag defGhcFlag "msse3" (noArg (\d ->
3513 d { sseVersion = Just SSE3 }))
3514 , make_ord_flag defGhcFlag "msse4" (noArg (\d ->
3515 d { sseVersion = Just SSE4 }))
3516 , make_ord_flag defGhcFlag "msse4.2" (noArg (\d ->
3517 d { sseVersion = Just SSE42 }))
3518 , make_ord_flag defGhcFlag "mbmi" (noArg (\d ->
3519 d { bmiVersion = Just BMI1 }))
3520 , make_ord_flag defGhcFlag "mbmi2" (noArg (\d ->
3521 d { bmiVersion = Just BMI2 }))
3522 , make_ord_flag defGhcFlag "mavx" (noArg (\d -> d { avx = True }))
3523 , make_ord_flag defGhcFlag "mavx2" (noArg (\d -> d { avx2 = True }))
3524 , make_ord_flag defGhcFlag "mavx512cd" (noArg (\d ->
3525 d { avx512cd = True }))
3526 , make_ord_flag defGhcFlag "mavx512er" (noArg (\d ->
3527 d { avx512er = True }))
3528 , make_ord_flag defGhcFlag "mavx512f" (noArg (\d -> d { avx512f = True }))
3529 , make_ord_flag defGhcFlag "mavx512pf" (noArg (\d ->
3530 d { avx512pf = True }))
3531
3532 ------ Warning opts -------------------------------------------------
3533 , make_ord_flag defFlag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
3534 , make_ord_flag defFlag "Werror"
3535 (NoArg (do { setGeneralFlag Opt_WarnIsError
3536 ; mapM_ setFatalWarningFlag minusWeverythingOpts }))
3537 , make_ord_flag defFlag "Wwarn"
3538 (NoArg (do { unSetGeneralFlag Opt_WarnIsError
3539 ; mapM_ unSetFatalWarningFlag minusWeverythingOpts }))
3540 -- Opt_WarnIsError is still needed to pass -Werror
3541 -- to CPP; see runCpp in SysTools
3542 , make_dep_flag defFlag "Wnot" (NoArg (upd (\d ->
3543 d {warningFlags = EnumSet.empty})))
3544 "Use -w or -Wno-everything instead"
3545 , make_ord_flag defFlag "w" (NoArg (upd (\d ->
3546 d {warningFlags = EnumSet.empty})))
3547
3548 -- New-style uniform warning sets
3549 --
3550 -- Note that -Weverything > -Wall > -Wextra > -Wdefault > -Wno-everything
3551 , make_ord_flag defFlag "Weverything" (NoArg (mapM_
3552 setWarningFlag minusWeverythingOpts))
3553 , make_ord_flag defFlag "Wno-everything"
3554 (NoArg (upd (\d -> d {warningFlags = EnumSet.empty})))
3555
3556 , make_ord_flag defFlag "Wall" (NoArg (mapM_
3557 setWarningFlag minusWallOpts))
3558 , make_ord_flag defFlag "Wno-all" (NoArg (mapM_
3559 unSetWarningFlag minusWallOpts))
3560
3561 , make_ord_flag defFlag "Wextra" (NoArg (mapM_
3562 setWarningFlag minusWOpts))
3563 , make_ord_flag defFlag "Wno-extra" (NoArg (mapM_
3564 unSetWarningFlag minusWOpts))
3565
3566 , make_ord_flag defFlag "Wdefault" (NoArg (mapM_
3567 setWarningFlag standardWarnings))
3568 , make_ord_flag defFlag "Wno-default" (NoArg (mapM_
3569 unSetWarningFlag standardWarnings))
3570
3571 , make_ord_flag defFlag "Wcompat" (NoArg (mapM_
3572 setWarningFlag minusWcompatOpts))
3573 , make_ord_flag defFlag "Wno-compat" (NoArg (mapM_
3574 unSetWarningFlag minusWcompatOpts))
3575
3576 ------ Plugin flags ------------------------------------------------
3577 , make_ord_flag defGhcFlag "fplugin-opt" (hasArg addPluginModuleNameOption)
3578 , make_ord_flag defGhcFlag "fplugin-trustworthy"
3579 (NoArg (setGeneralFlag Opt_PluginTrustworthy))
3580 , make_ord_flag defGhcFlag "fplugin" (hasArg addPluginModuleName)
3581 , make_ord_flag defGhcFlag "fclear-plugins" (noArg clearPluginModuleNames)
3582 , make_ord_flag defGhcFlag "ffrontend-opt" (hasArg addFrontendPluginOption)
3583
3584 ------ Optimisation flags ------------------------------------------
3585 , make_dep_flag defGhcFlag "Onot" (noArgM $ setOptLevel 0 )
3586 "Use -O0 instead"
3587 , make_ord_flag defGhcFlag "O" (optIntSuffixM (\mb_n ->
3588 setOptLevel (mb_n `orElse` 1)))
3589 -- If the number is missing, use 1
3590
3591 , make_ord_flag defFlag "fbinary-blob-threshold"
3592 (intSuffix (\n d -> d { binBlobThreshold = fromIntegral n }))
3593
3594 , make_ord_flag defFlag "fmax-relevant-binds"
3595 (intSuffix (\n d -> d { maxRelevantBinds = Just n }))
3596 , make_ord_flag defFlag "fno-max-relevant-binds"
3597 (noArg (\d -> d { maxRelevantBinds = Nothing }))
3598
3599 , make_ord_flag defFlag "fmax-valid-hole-fits"
3600 (intSuffix (\n d -> d { maxValidHoleFits = Just n }))
3601 , make_ord_flag defFlag "fno-max-valid-hole-fits"
3602 (noArg (\d -> d { maxValidHoleFits = Nothing }))
3603 , make_ord_flag defFlag "fmax-refinement-hole-fits"
3604 (intSuffix (\n d -> d { maxRefHoleFits = Just n }))
3605 , make_ord_flag defFlag "fno-max-refinement-hole-fits"
3606 (noArg (\d -> d { maxRefHoleFits = Nothing }))
3607 , make_ord_flag defFlag "frefinement-level-hole-fits"
3608 (intSuffix (\n d -> d { refLevelHoleFits = Just n }))
3609 , make_ord_flag defFlag "fno-refinement-level-hole-fits"
3610 (noArg (\d -> d { refLevelHoleFits = Nothing }))
3611
3612 , make_dep_flag defGhcFlag "fllvm-pass-vectors-in-regs"
3613 (noArg id)
3614 "vectors registers are now passed in registers by default."
3615 , make_ord_flag defFlag "fmax-uncovered-patterns"
3616 (intSuffix (\n d -> d { maxUncoveredPatterns = n }))
3617 , make_ord_flag defFlag "fmax-pmcheck-models"
3618 (intSuffix (\n d -> d { maxPmCheckModels = n }))
3619 , make_ord_flag defFlag "fsimplifier-phases"
3620 (intSuffix (\n d -> d { simplPhases = n }))
3621 , make_ord_flag defFlag "fmax-simplifier-iterations"
3622 (intSuffix (\n d -> d { maxSimplIterations = n }))
3623 , (Deprecated, defFlag "fmax-pmcheck-iterations"
3624 (intSuffixM (\_ d ->
3625 do { deprecate $ "use -fmax-pmcheck-models instead"
3626 ; return d })))
3627 , make_ord_flag defFlag "fsimpl-tick-factor"
3628 (intSuffix (\n d -> d { simplTickFactor = n }))
3629 , make_ord_flag defFlag "fspec-constr-threshold"
3630 (intSuffix (\n d -> d { specConstrThreshold = Just n }))
3631 , make_ord_flag defFlag "fno-spec-constr-threshold"
3632 (noArg (\d -> d { specConstrThreshold = Nothing }))
3633 , make_ord_flag defFlag "fspec-constr-count"
3634 (intSuffix (\n d -> d { specConstrCount = Just n }))
3635 , make_ord_flag defFlag "fno-spec-constr-count"
3636 (noArg (\d -> d { specConstrCount = Nothing }))
3637 , make_ord_flag defFlag "fspec-constr-recursive"
3638 (intSuffix (\n d -> d { specConstrRecursive = n }))
3639 , make_ord_flag defFlag "fliberate-case-threshold"
3640 (intSuffix (\n d -> d { liberateCaseThreshold = Just n }))
3641 , make_ord_flag defFlag "fno-liberate-case-threshold"
3642 (noArg (\d -> d { liberateCaseThreshold = Nothing }))
3643 , make_ord_flag defFlag "drule-check"
3644 (sepArg (\s d -> d { ruleCheck = Just s }))
3645 , make_ord_flag defFlag "dinline-check"
3646 (sepArg (\s d -> d { inlineCheck = Just s }))
3647 , make_ord_flag defFlag "freduction-depth"
3648 (intSuffix (\n d -> d { reductionDepth = treatZeroAsInf n }))
3649 , make_ord_flag defFlag "fconstraint-solver-iterations"
3650 (intSuffix (\n d -> d { solverIterations = treatZeroAsInf n }))
3651 , (Deprecated, defFlag "fcontext-stack"
3652 (intSuffixM (\n d ->
3653 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
3654 ; return $ d { reductionDepth = treatZeroAsInf n } })))
3655 , (Deprecated, defFlag "ftype-function-depth"
3656 (intSuffixM (\n d ->
3657 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
3658 ; return $ d { reductionDepth = treatZeroAsInf n } })))
3659 , make_ord_flag defFlag "fstrictness-before"
3660 (intSuffix (\n d -> d { strictnessBefore = n : strictnessBefore d }))
3661 , make_ord_flag defFlag "ffloat-lam-args"
3662 (intSuffix (\n d -> d { floatLamArgs = Just n }))
3663 , make_ord_flag defFlag "ffloat-all-lams"
3664 (noArg (\d -> d { floatLamArgs = Nothing }))
3665 , make_ord_flag defFlag "fstg-lift-lams-rec-args"
3666 (intSuffix (\n d -> d { liftLamsRecArgs = Just n }))
3667 , make_ord_flag defFlag "fstg-lift-lams-rec-args-any"
3668 (noArg (\d -> d { liftLamsRecArgs = Nothing }))
3669 , make_ord_flag defFlag "fstg-lift-lams-non-rec-args"
3670 (intSuffix (\n d -> d { liftLamsRecArgs = Just n }))
3671 , make_ord_flag defFlag "fstg-lift-lams-non-rec-args-any"
3672 (noArg (\d -> d { liftLamsRecArgs = Nothing }))
3673 , make_ord_flag defFlag "fstg-lift-lams-known"
3674 (noArg (\d -> d { liftLamsKnown = True }))
3675 , make_ord_flag defFlag "fno-stg-lift-lams-known"
3676 (noArg (\d -> d { liftLamsKnown = False }))
3677 , make_ord_flag defFlag "fproc-alignment"
3678 (intSuffix (\n d -> d { cmmProcAlignment = Just n }))
3679 , make_ord_flag defFlag "fblock-layout-weights"
3680 (HasArg (\s ->
3681 upd (\d -> d { cfgWeightInfo =
3682 parseCfgWeights s (cfgWeightInfo d)})))
3683 , make_ord_flag defFlag "fhistory-size"
3684 (intSuffix (\n d -> d { historySize = n }))
3685 , make_ord_flag defFlag "funfolding-creation-threshold"
3686 (intSuffix (\n d -> d {ufCreationThreshold = n}))
3687 , make_ord_flag defFlag "funfolding-use-threshold"
3688 (intSuffix (\n d -> d {ufUseThreshold = n}))
3689 , make_ord_flag defFlag "funfolding-fun-discount"
3690 (intSuffix (\n d -> d {ufFunAppDiscount = n}))
3691 , make_ord_flag defFlag "funfolding-dict-discount"
3692 (intSuffix (\n d -> d {ufDictDiscount = n}))
3693 , make_ord_flag defFlag "funfolding-keeness-factor"
3694 (floatSuffix (\n d -> d {ufKeenessFactor = n}))
3695 , make_ord_flag defFlag "fmax-worker-args"
3696 (intSuffix (\n d -> d {maxWorkerArgs = n}))
3697 , make_ord_flag defGhciFlag "fghci-hist-size"
3698 (intSuffix (\n d -> d {ghciHistSize = n}))
3699 , make_ord_flag defGhcFlag "fmax-inline-alloc-size"
3700 (intSuffix (\n d -> d { maxInlineAllocSize = n }))
3701 , make_ord_flag defGhcFlag "fmax-inline-memcpy-insns"
3702 (intSuffix (\n d -> d { maxInlineMemcpyInsns = n }))
3703 , make_ord_flag defGhcFlag "fmax-inline-memset-insns"
3704 (intSuffix (\n d -> d { maxInlineMemsetInsns = n }))
3705 , make_ord_flag defGhcFlag "dinitial-unique"
3706 (intSuffix (\n d -> d { initialUnique = n }))
3707 , make_ord_flag defGhcFlag "dunique-increment"
3708 (intSuffix (\n d -> d { uniqueIncrement = n }))
3709
3710 ------ Profiling ----------------------------------------------------
3711
3712 -- OLD profiling flags
3713 , make_dep_flag defGhcFlag "auto-all"
3714 (noArg (\d -> d { profAuto = ProfAutoAll } ))
3715 "Use -fprof-auto instead"
3716 , make_dep_flag defGhcFlag "no-auto-all"
3717 (noArg (\d -> d { profAuto = NoProfAuto } ))
3718 "Use -fno-prof-auto instead"
3719 , make_dep_flag defGhcFlag "auto"
3720 (noArg (\d -> d { profAuto = ProfAutoExports } ))
3721 "Use -fprof-auto-exported instead"
3722 , make_dep_flag defGhcFlag "no-auto"
3723 (noArg (\d -> d { profAuto = NoProfAuto } ))
3724 "Use -fno-prof-auto instead"
3725 , make_dep_flag defGhcFlag "caf-all"
3726 (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs))
3727 "Use -fprof-cafs instead"
3728 , make_dep_flag defGhcFlag "no-caf-all"
3729 (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs))
3730 "Use -fno-prof-cafs instead"
3731
3732 -- NEW profiling flags
3733 , make_ord_flag defGhcFlag "fprof-auto"
3734 (noArg (\d -> d { profAuto = ProfAutoAll } ))
3735 , make_ord_flag defGhcFlag "fprof-auto-top"
3736 (noArg (\d -> d { profAuto = ProfAutoTop } ))
3737 , make_ord_flag defGhcFlag "fprof-auto-exported"
3738 (noArg (\d -> d { profAuto = ProfAutoExports } ))
3739 , make_ord_flag defGhcFlag "fprof-auto-calls"
3740 (noArg (\d -> d { profAuto = ProfAutoCalls } ))
3741 , make_ord_flag defGhcFlag "fno-prof-auto"
3742 (noArg (\d -> d { profAuto = NoProfAuto } ))
3743
3744 ------ Compiler flags -----------------------------------------------
3745
3746 , make_ord_flag defGhcFlag "fasm" (NoArg (setObjTarget HscAsm))
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 "fvia-C" (NoArg
3751 (deprecate $ "The -fvia-C flag does nothing; " ++
3752 "it will be removed in a future GHC release"))
3753 , make_ord_flag defGhcFlag "fllvm" (NoArg (setObjTarget HscLlvm))
3754
3755 , make_ord_flag defFlag "fno-code" (NoArg ((upd $ \d ->
3756 d { ghcLink=NoLink }) >> setTarget HscNothing))
3757 , make_ord_flag defFlag "fbyte-code"
3758 (noArgM $ \dflags -> do
3759 setTarget HscInterpreted
3760 pure $ gopt_set dflags Opt_ByteCode)
3761 , make_ord_flag defFlag "fobject-code" $ NoArg $ do
3762 dflags <- liftEwM getCmdLineState
3763 setTarget $ defaultObjectTarget dflags
3764
3765 , make_dep_flag defFlag "fglasgow-exts"
3766 (NoArg enableGlasgowExts) "Use individual extensions instead"
3767 , make_dep_flag defFlag "fno-glasgow-exts"
3768 (NoArg disableGlasgowExts) "Use individual extensions instead"
3769 , make_ord_flag defFlag "Wunused-binds" (NoArg enableUnusedBinds)
3770 , make_ord_flag defFlag "Wno-unused-binds" (NoArg disableUnusedBinds)
3771 , make_ord_flag defHiddenFlag "fwarn-unused-binds" (NoArg enableUnusedBinds)
3772 , make_ord_flag defHiddenFlag "fno-warn-unused-binds" (NoArg
3773 disableUnusedBinds)
3774
3775 ------ Safe Haskell flags -------------------------------------------
3776 , make_ord_flag defFlag "fpackage-trust" (NoArg setPackageTrust)
3777 , make_ord_flag defFlag "fno-safe-infer" (noArg (\d ->
3778 d { safeInfer = False }))
3779 , make_ord_flag defFlag "fno-safe-haskell" (NoArg (setSafeHaskell Sf_Ignore))
3780
3781 ------ position independent flags ----------------------------------
3782 , make_ord_flag defGhcFlag "fPIC" (NoArg (setGeneralFlag Opt_PIC))
3783 , make_ord_flag defGhcFlag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC))
3784 , make_ord_flag defGhcFlag "fPIE" (NoArg (setGeneralFlag Opt_PIC))
3785 , make_ord_flag defGhcFlag "fno-PIE" (NoArg (unSetGeneralFlag Opt_PIC))
3786
3787 ------ Debugging flags ----------------------------------------------
3788 , make_ord_flag defGhcFlag "g" (OptIntSuffix setDebugLevel)
3789 ]
3790 ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlagsDeps
3791 ++ map (mkFlag turnOff "no-" unSetGeneralFlag ) negatableFlagsDeps
3792 ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlagsDeps
3793 ++ map (mkFlag turnOff "dno-" unSetGeneralFlag ) dFlagsDeps
3794 ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlagsDeps
3795 ++ map (mkFlag turnOff "fno-" unSetGeneralFlag ) fFlagsDeps
3796 ++ map (mkFlag turnOn "W" setWarningFlag ) wWarningFlagsDeps
3797 ++ map (mkFlag turnOff "Wno-" unSetWarningFlag ) wWarningFlagsDeps
3798 ++ map (mkFlag turnOn "Werror=" setWErrorFlag ) wWarningFlagsDeps
3799 ++ map (mkFlag turnOn "Wwarn=" unSetFatalWarningFlag )
3800 wWarningFlagsDeps
3801 ++ map (mkFlag turnOn "Wno-error=" unSetFatalWarningFlag )
3802 wWarningFlagsDeps
3803 ++ map (mkFlag turnOn "fwarn-" setWarningFlag . hideFlag)
3804 wWarningFlagsDeps
3805 ++ map (mkFlag turnOff "fno-warn-" unSetWarningFlag . hideFlag)
3806 wWarningFlagsDeps
3807 ++ [ (NotDeprecated, unrecognisedWarning "W"),
3808 (Deprecated, unrecognisedWarning "fwarn-"),
3809 (Deprecated, unrecognisedWarning "fno-warn-") ]
3810 ++ [ make_ord_flag defFlag "Werror=compat"
3811 (NoArg (mapM_ setWErrorFlag minusWcompatOpts))
3812 , make_ord_flag defFlag "Wno-error=compat"
3813 (NoArg (mapM_ unSetFatalWarningFlag minusWcompatOpts))
3814 , make_ord_flag defFlag "Wwarn=compat"
3815 (NoArg (mapM_ unSetFatalWarningFlag minusWcompatOpts)) ]
3816 ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlagsDeps
3817 ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlagsDeps
3818 ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlagsDeps
3819 ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlagsDeps
3820 ++ map (mkFlag turnOn "X" setLanguage ) languageFlagsDeps
3821 ++ map (mkFlag turnOn "X" setSafeHaskell ) safeHaskellFlagsDeps
3822 ++ [ make_dep_flag defFlag "XGenerics"
3823 (NoArg $ return ())
3824 ("it does nothing; look into -XDefaultSignatures " ++
3825 "and -XDeriveGeneric for generic programming support.")
3826 , make_dep_flag defFlag "XNoGenerics"
3827 (NoArg $ return ())
3828 ("it does nothing; look into -XDefaultSignatures and " ++
3829 "-XDeriveGeneric for generic programming support.") ]
3830
3831 -- | This is where we handle unrecognised warning flags. We only issue a warning
3832 -- if -Wunrecognised-warning-flags is set. See #11429 for context.
3833 unrecognisedWarning :: String -> Flag (CmdLineP DynFlags)
3834 unrecognisedWarning prefix = defHiddenFlag prefix (Prefix action)
3835 where
3836 action :: String -> EwM (CmdLineP DynFlags) ()
3837 action flag = do
3838 f <- wopt Opt_WarnUnrecognisedWarningFlags <$> liftEwM getCmdLineState
3839 when f $ addFlagWarn Cmd.ReasonUnrecognisedFlag $
3840 "unrecognised warning flag: -" ++ prefix ++ flag
3841
3842 -- See Note [Supporting CLI completion]
3843 package_flags_deps :: [(Deprecation, Flag (CmdLineP DynFlags))]
3844 package_flags_deps = [
3845 ------- Packages ----------------------------------------------------
3846 make_ord_flag defFlag "package-db"
3847 (HasArg (addPkgConfRef . PkgConfFile))
3848 , make_ord_flag defFlag "clear-package-db" (NoArg clearPkgConf)
3849 , make_ord_flag defFlag "no-global-package-db" (NoArg removeGlobalPkgConf)
3850 , make_ord_flag defFlag "no-user-package-db" (NoArg removeUserPkgConf)
3851 , make_ord_flag defFlag "global-package-db"
3852 (NoArg (addPkgConfRef GlobalPkgConf))
3853 , make_ord_flag defFlag "user-package-db"
3854 (NoArg (addPkgConfRef UserPkgConf))
3855 -- backwards compat with GHC<=7.4 :
3856 , make_dep_flag defFlag "package-conf"
3857 (HasArg $ addPkgConfRef . PkgConfFile) "Use -package-db instead"
3858 , make_dep_flag defFlag "no-user-package-conf"
3859 (NoArg removeUserPkgConf) "Use -no-user-package-db instead"
3860 , make_ord_flag defGhcFlag "package-name" (HasArg $ \name -> do
3861 upd (setUnitId name))
3862 -- TODO: Since we JUST deprecated
3863 -- -this-package-key, let's keep this
3864 -- undeprecated for another cycle.
3865</