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