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