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