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