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