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