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