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