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