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