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