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