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