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