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