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