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