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