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