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