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