Remove -dtrace-level
[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 | Opt_WarnCPPUndef -- Since 8.2
623 deriving (Eq, Show, Enum)
624
625 data Language = Haskell98 | Haskell2010
626 deriving (Eq, Enum, Show)
627
628 instance Outputable Language where
629 ppr = text . show
630
631 -- | The various Safe Haskell modes
632 data SafeHaskellMode
633 = Sf_None
634 | Sf_Unsafe
635 | Sf_Trustworthy
636 | Sf_Safe
637 deriving (Eq)
638
639 instance Show SafeHaskellMode where
640 show Sf_None = "None"
641 show Sf_Unsafe = "Unsafe"
642 show Sf_Trustworthy = "Trustworthy"
643 show Sf_Safe = "Safe"
644
645 instance Outputable SafeHaskellMode where
646 ppr = text . show
647
648 -- | Contains not only a collection of 'GeneralFlag's but also a plethora of
649 -- information relating to the compilation of a single file or GHC session
650 data DynFlags = DynFlags {
651 ghcMode :: GhcMode,
652 ghcLink :: GhcLink,
653 hscTarget :: HscTarget,
654 settings :: Settings,
655 verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels]
656 optLevel :: Int, -- ^ Optimisation level
657 debugLevel :: Int, -- ^ How much debug information to produce
658 simplPhases :: Int, -- ^ Number of simplifier phases
659 maxSimplIterations :: Int, -- ^ Max simplifier iterations
660 maxPmCheckIterations :: Int, -- ^ Max no iterations for pm checking
661 ruleCheck :: Maybe String,
662 strictnessBefore :: [Int], -- ^ Additional demand analysis
663
664 parMakeCount :: Maybe Int, -- ^ The number of modules to compile in parallel
665 -- in --make mode, where Nothing ==> compile as
666 -- many in parallel as there are CPUs.
667
668 enableTimeStats :: Bool, -- ^ Enable RTS timing statistics?
669 ghcHeapSize :: Maybe Int, -- ^ The heap size to set.
670
671 maxRelevantBinds :: Maybe Int, -- ^ Maximum number of bindings from the type envt
672 -- to show in type error messages
673 maxUncoveredPatterns :: Int, -- ^ Maximum number of unmatched patterns to show
674 -- in non-exhaustiveness warnings
675 simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks
676 specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr
677 specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function
678 specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types
679 -- Not optional; otherwise ForceSpecConstr can diverge.
680 liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase
681 floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating
682 -- See CoreMonad.FloatOutSwitches
683
684 historySize :: Int, -- ^ Simplification history size
685
686 importPaths :: [FilePath],
687 mainModIs :: Module,
688 mainFunIs :: Maybe String,
689 reductionDepth :: IntWithInf, -- ^ Typechecker maximum stack depth
690 solverIterations :: IntWithInf, -- ^ Number of iterations in the constraints solver
691 -- Typically only 1 is needed
692
693 thisInstalledUnitId :: InstalledUnitId,
694 thisComponentId_ :: Maybe ComponentId,
695 thisUnitIdInsts_ :: Maybe [(ModuleName, Module)],
696
697 -- ways
698 ways :: [Way], -- ^ Way flags from the command line
699 buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof)
700 rtsBuildTag :: String, -- ^ The RTS \"way\"
701
702 -- For object splitting
703 splitInfo :: Maybe (String,Int),
704
705 -- paths etc.
706 objectDir :: Maybe String,
707 dylibInstallName :: Maybe String,
708 hiDir :: Maybe String,
709 stubDir :: Maybe String,
710 dumpDir :: Maybe String,
711
712 objectSuf :: String,
713 hcSuf :: String,
714 hiSuf :: String,
715
716 canGenerateDynamicToo :: IORef Bool,
717 dynObjectSuf :: String,
718 dynHiSuf :: String,
719
720 -- Packages.isDllName needs to know whether a call is within a
721 -- single DLL or not. Normally it does this by seeing if the call
722 -- is to the same package, but for the ghc package, we split the
723 -- package between 2 DLLs. The dllSplit tells us which sets of
724 -- modules are in which package.
725 dllSplitFile :: Maybe FilePath,
726 dllSplit :: Maybe [Set String],
727
728 outputFile :: Maybe String,
729 dynOutputFile :: Maybe String,
730 outputHi :: Maybe String,
731 dynLibLoader :: DynLibLoader,
732
733 -- | This is set by 'DriverPipeline.runPipeline' based on where
734 -- its output is going.
735 dumpPrefix :: Maybe FilePath,
736
737 -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
738 -- Set by @-ddump-file-prefix@
739 dumpPrefixForce :: Maybe FilePath,
740
741 ldInputs :: [Option],
742
743 includePaths :: [String],
744 libraryPaths :: [String],
745 frameworkPaths :: [String], -- used on darwin only
746 cmdlineFrameworks :: [String], -- ditto
747
748 rtsOpts :: Maybe String,
749 rtsOptsEnabled :: RtsOptsEnabled,
750 rtsOptsSuggestions :: Bool,
751
752 hpcDir :: String, -- ^ Path to store the .mix files
753
754 -- Plugins
755 pluginModNames :: [ModuleName],
756 pluginModNameOpts :: [(ModuleName,String)],
757 frontendPluginOpts :: [String],
758
759 -- GHC API hooks
760 hooks :: Hooks,
761
762 -- For ghc -M
763 depMakefile :: FilePath,
764 depIncludePkgDeps :: Bool,
765 depExcludeMods :: [ModuleName],
766 depSuffixes :: [String],
767
768 -- Package flags
769 extraPkgConfs :: [PkgConfRef] -> [PkgConfRef],
770 -- ^ The @-package-db@ flags given on the command line, in the order
771 -- they appeared.
772
773 ignorePackageFlags :: [IgnorePackageFlag],
774 -- ^ The @-ignore-package@ flags from the command line
775 packageFlags :: [PackageFlag],
776 -- ^ The @-package@ and @-hide-package@ flags from the command-line
777 pluginPackageFlags :: [PackageFlag],
778 -- ^ The @-plugin-package-id@ flags from command line
779 trustFlags :: [TrustFlag],
780 -- ^ The @-trust@ and @-distrust@ flags
781 packageEnv :: Maybe FilePath,
782 -- ^ Filepath to the package environment file (if overriding default)
783
784 -- Package state
785 -- NB. do not modify this field, it is calculated by
786 -- Packages.initPackages
787 pkgDatabase :: Maybe [(FilePath, [PackageConfig])],
788 pkgState :: PackageState,
789
790 -- Temporary files
791 -- These have to be IORefs, because the defaultCleanupHandler needs to
792 -- know what to clean when an exception happens
793 filesToClean :: IORef [FilePath],
794 dirsToClean :: IORef (Map FilePath FilePath),
795 filesToNotIntermediateClean :: IORef [FilePath],
796 -- The next available suffix to uniquely name a temp file, updated atomically
797 nextTempSuffix :: IORef Int,
798
799 -- Names of files which were generated from -ddump-to-file; used to
800 -- track which ones we need to truncate because it's our first run
801 -- through
802 generatedDumps :: IORef (Set FilePath),
803
804 -- hsc dynamic flags
805 dumpFlags :: IntSet,
806 generalFlags :: IntSet,
807 warningFlags :: IntSet,
808 -- Don't change this without updating extensionFlags:
809 language :: Maybe Language,
810 -- | Safe Haskell mode
811 safeHaskell :: SafeHaskellMode,
812 safeInfer :: Bool,
813 safeInferred :: Bool,
814 -- We store the location of where some extension and flags were turned on so
815 -- we can produce accurate error messages when Safe Haskell fails due to
816 -- them.
817 thOnLoc :: SrcSpan,
818 newDerivOnLoc :: SrcSpan,
819 overlapInstLoc :: SrcSpan,
820 incoherentOnLoc :: SrcSpan,
821 pkgTrustOnLoc :: SrcSpan,
822 warnSafeOnLoc :: SrcSpan,
823 warnUnsafeOnLoc :: SrcSpan,
824 trustworthyOnLoc :: SrcSpan,
825 -- Don't change this without updating extensionFlags:
826 extensions :: [OnOff LangExt.Extension],
827 -- extensionFlags should always be equal to
828 -- flattenExtensionFlags language extensions
829 -- LangExt.Extension is defined in libraries/ghc-boot so that it can be used
830 -- by template-haskell
831 extensionFlags :: IntSet,
832
833 -- Unfolding control
834 -- See Note [Discounts and thresholds] in CoreUnfold
835 ufCreationThreshold :: Int,
836 ufUseThreshold :: Int,
837 ufFunAppDiscount :: Int,
838 ufDictDiscount :: Int,
839 ufKeenessFactor :: Float,
840 ufDearOp :: Int,
841
842 maxWorkerArgs :: Int,
843
844 ghciHistSize :: Int,
845
846 -- | MsgDoc output action: use "ErrUtils" instead of this if you can
847 log_action :: LogAction,
848 flushOut :: FlushOut,
849 flushErr :: FlushErr,
850
851 haddockOptions :: Maybe String,
852
853 -- | GHCi scripts specified by -ghci-script, in reverse order
854 ghciScripts :: [String],
855
856 -- Output style options
857 pprUserLength :: Int,
858 pprCols :: Int,
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 profAuto = NoProfAuto,
1604 interactivePrint = Nothing,
1605 nextWrapperNum = panic "defaultDynFlags: No nextWrapperNum",
1606 sseVersion = Nothing,
1607 avx = False,
1608 avx2 = False,
1609 avx512cd = False,
1610 avx512er = False,
1611 avx512f = False,
1612 avx512pf = False,
1613 rtldInfo = panic "defaultDynFlags: no rtldInfo",
1614 rtccInfo = panic "defaultDynFlags: no rtccInfo",
1615
1616 maxInlineAllocSize = 128,
1617 maxInlineMemcpyInsns = 32,
1618 maxInlineMemsetInsns = 32,
1619
1620 initialUnique = 0,
1621 uniqueIncrement = 1,
1622
1623 reverseErrors = False
1624 }
1625
1626 defaultWays :: Settings -> [Way]
1627 defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
1628 then [WayDyn]
1629 else []
1630
1631 interpWays :: [Way]
1632 interpWays
1633 | dynamicGhc = [WayDyn]
1634 | rtsIsProfiled = [WayProf]
1635 | otherwise = []
1636
1637 interpreterProfiled :: DynFlags -> Bool
1638 interpreterProfiled dflags
1639 | gopt Opt_ExternalInterpreter dflags = gopt Opt_SccProfilingOn dflags
1640 | otherwise = rtsIsProfiled
1641
1642 interpreterDynamic :: DynFlags -> Bool
1643 interpreterDynamic dflags
1644 | gopt Opt_ExternalInterpreter dflags = WayDyn `elem` ways dflags
1645 | otherwise = dynamicGhc
1646
1647 --------------------------------------------------------------------------
1648
1649 type FatalMessager = String -> IO ()
1650
1651 type LogAction = DynFlags
1652 -> WarnReason
1653 -> Severity
1654 -> SrcSpan
1655 -> PprStyle
1656 -> MsgDoc
1657 -> IO ()
1658
1659 defaultFatalMessager :: FatalMessager
1660 defaultFatalMessager = hPutStrLn stderr
1661
1662 defaultLogAction :: LogAction
1663 defaultLogAction dflags reason severity srcSpan style msg
1664 = case severity of
1665 SevOutput -> printSDoc msg style
1666 SevDump -> printSDoc (msg $$ blankLine) style
1667 SevInteractive -> putStrSDoc msg style
1668 SevInfo -> printErrs msg style
1669 SevFatal -> printErrs msg style
1670 _ -> do hPutChar stderr '\n'
1671 printErrs message style
1672 -- careful (#2302): printErrs prints in UTF-8,
1673 -- whereas converting to string first and using
1674 -- hPutStr would just emit the low 8 bits of
1675 -- each unicode char.
1676 where printSDoc = defaultLogActionHPrintDoc dflags stdout
1677 printErrs = defaultLogActionHPrintDoc dflags stderr
1678 putStrSDoc = defaultLogActionHPutStrDoc dflags stdout
1679 -- Pretty print the warning flag, if any (#10752)
1680 message = mkLocMessageAnn flagMsg severity srcSpan msg
1681 flagMsg = case reason of
1682 NoReason -> Nothing
1683 Reason flag -> (\spec -> "-W" ++ flagSpecName spec ++ flagGrp flag) <$>
1684 flagSpecOf flag
1685
1686 flagGrp flag
1687 | gopt Opt_ShowWarnGroups dflags =
1688 case smallestGroups flag of
1689 [] -> ""
1690 groups -> " (in " ++ intercalate ", " (map ("-W"++) groups) ++ ")"
1691 | otherwise = ""
1692
1693 defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
1694 defaultLogActionHPrintDoc dflags h d sty
1695 = defaultLogActionHPutStrDoc dflags h (d $$ text "") sty
1696 -- Adds a newline
1697
1698 defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
1699 defaultLogActionHPutStrDoc dflags h d sty
1700 = Pretty.printDoc_ Pretty.PageMode (pprCols dflags) h doc
1701 where -- Don't add a newline at the end, so that successive
1702 -- calls to this log-action can output all on the same line
1703 doc = runSDoc d (initSDocContext dflags sty)
1704
1705 newtype FlushOut = FlushOut (IO ())
1706
1707 defaultFlushOut :: FlushOut
1708 defaultFlushOut = FlushOut $ hFlush stdout
1709
1710 newtype FlushErr = FlushErr (IO ())
1711
1712 defaultFlushErr :: FlushErr
1713 defaultFlushErr = FlushErr $ hFlush stderr
1714
1715 {-
1716 Note [Verbosity levels]
1717 ~~~~~~~~~~~~~~~~~~~~~~~
1718 0 | print errors & warnings only
1719 1 | minimal verbosity: print "compiling M ... done." for each module.
1720 2 | equivalent to -dshow-passes
1721 3 | equivalent to existing "ghc -v"
1722 4 | "ghc -v -ddump-most"
1723 5 | "ghc -v -ddump-all"
1724 -}
1725
1726 data OnOff a = On a
1727 | Off a
1728 deriving (Eq, Show)
1729
1730 instance Outputable a => Outputable (OnOff a) where
1731 ppr (On x) = text "On" <+> ppr x
1732 ppr (Off x) = text "Off" <+> ppr x
1733
1734 -- OnOffs accumulate in reverse order, so we use foldr in order to
1735 -- process them in the right order
1736 flattenExtensionFlags :: Maybe Language -> [OnOff LangExt.Extension] -> IntSet
1737 flattenExtensionFlags ml = foldr f defaultExtensionFlags
1738 where f (On f) flags = IntSet.insert (fromEnum f) flags
1739 f (Off f) flags = IntSet.delete (fromEnum f) flags
1740 defaultExtensionFlags = IntSet.fromList (map fromEnum (languageExtensions ml))
1741
1742 languageExtensions :: Maybe Language -> [LangExt.Extension]
1743
1744 languageExtensions Nothing
1745 -- Nothing => the default case
1746 = LangExt.NondecreasingIndentation -- This has been on by default for some time
1747 : delete LangExt.DatatypeContexts -- The Haskell' committee decided to
1748 -- remove datatype contexts from the
1749 -- language:
1750 -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
1751 (languageExtensions (Just Haskell2010))
1752
1753 -- NB: MonoPatBinds is no longer the default
1754
1755 languageExtensions (Just Haskell98)
1756 = [LangExt.ImplicitPrelude,
1757 LangExt.MonomorphismRestriction,
1758 LangExt.NPlusKPatterns,
1759 LangExt.DatatypeContexts,
1760 LangExt.TraditionalRecordSyntax,
1761 LangExt.NondecreasingIndentation
1762 -- strictly speaking non-standard, but we always had this
1763 -- on implicitly before the option was added in 7.1, and
1764 -- turning it off breaks code, so we're keeping it on for
1765 -- backwards compatibility. Cabal uses -XHaskell98 by
1766 -- default unless you specify another language.
1767 ]
1768
1769 languageExtensions (Just Haskell2010)
1770 = [LangExt.ImplicitPrelude,
1771 LangExt.MonomorphismRestriction,
1772 LangExt.DatatypeContexts,
1773 LangExt.TraditionalRecordSyntax,
1774 LangExt.EmptyDataDecls,
1775 LangExt.ForeignFunctionInterface,
1776 LangExt.PatternGuards,
1777 LangExt.DoAndIfThenElse,
1778 LangExt.RelaxedPolyRec]
1779
1780 -- | Test whether a 'DumpFlag' is set
1781 dopt :: DumpFlag -> DynFlags -> Bool
1782 dopt f dflags = (fromEnum f `IntSet.member` dumpFlags dflags)
1783 || (verbosity dflags >= 4 && enableIfVerbose f)
1784 where enableIfVerbose Opt_D_dump_tc_trace = False
1785 enableIfVerbose Opt_D_dump_rn_trace = False
1786 enableIfVerbose Opt_D_dump_cs_trace = False
1787 enableIfVerbose Opt_D_dump_if_trace = False
1788 enableIfVerbose Opt_D_dump_vt_trace = False
1789 enableIfVerbose Opt_D_dump_tc = False
1790 enableIfVerbose Opt_D_dump_rn = False
1791 enableIfVerbose Opt_D_dump_shape = False
1792 enableIfVerbose Opt_D_dump_rn_stats = False
1793 enableIfVerbose Opt_D_dump_hi_diffs = False
1794 enableIfVerbose Opt_D_verbose_core2core = False
1795 enableIfVerbose Opt_D_verbose_stg2stg = False
1796 enableIfVerbose Opt_D_dump_splices = False
1797 enableIfVerbose Opt_D_th_dec_file = False
1798 enableIfVerbose Opt_D_dump_rule_firings = False
1799 enableIfVerbose Opt_D_dump_rule_rewrites = False
1800 enableIfVerbose Opt_D_dump_simpl_trace = False
1801 enableIfVerbose Opt_D_dump_rtti = False
1802 enableIfVerbose Opt_D_dump_inlinings = False
1803 enableIfVerbose Opt_D_dump_core_stats = False
1804 enableIfVerbose Opt_D_dump_asm_stats = False
1805 enableIfVerbose Opt_D_dump_types = False
1806 enableIfVerbose Opt_D_dump_simpl_iterations = False
1807 enableIfVerbose Opt_D_dump_ticked = False
1808 enableIfVerbose Opt_D_dump_view_pattern_commoning = False
1809 enableIfVerbose Opt_D_dump_mod_cycles = False
1810 enableIfVerbose Opt_D_dump_mod_map = False
1811 enableIfVerbose _ = True
1812
1813 -- | Set a 'DumpFlag'
1814 dopt_set :: DynFlags -> DumpFlag -> DynFlags
1815 dopt_set dfs f = dfs{ dumpFlags = IntSet.insert (fromEnum f) (dumpFlags dfs) }
1816
1817 -- | Unset a 'DumpFlag'
1818 dopt_unset :: DynFlags -> DumpFlag -> DynFlags
1819 dopt_unset dfs f = dfs{ dumpFlags = IntSet.delete (fromEnum f) (dumpFlags dfs) }
1820
1821 -- | Test whether a 'GeneralFlag' is set
1822 gopt :: GeneralFlag -> DynFlags -> Bool
1823 gopt f dflags = fromEnum f `IntSet.member` generalFlags dflags
1824
1825 -- | Set a 'GeneralFlag'
1826 gopt_set :: DynFlags -> GeneralFlag -> DynFlags
1827 gopt_set dfs f = dfs{ generalFlags = IntSet.insert (fromEnum f) (generalFlags dfs) }
1828
1829 -- | Unset a 'GeneralFlag'
1830 gopt_unset :: DynFlags -> GeneralFlag -> DynFlags
1831 gopt_unset dfs f = dfs{ generalFlags = IntSet.delete (fromEnum f) (generalFlags dfs) }
1832
1833 -- | Test whether a 'WarningFlag' is set
1834 wopt :: WarningFlag -> DynFlags -> Bool
1835 wopt f dflags = fromEnum f `IntSet.member` warningFlags dflags
1836
1837 -- | Set a 'WarningFlag'
1838 wopt_set :: DynFlags -> WarningFlag -> DynFlags
1839 wopt_set dfs f = dfs{ warningFlags = IntSet.insert (fromEnum f) (warningFlags dfs) }
1840
1841 -- | Unset a 'WarningFlag'
1842 wopt_unset :: DynFlags -> WarningFlag -> DynFlags
1843 wopt_unset dfs f = dfs{ warningFlags = IntSet.delete (fromEnum f) (warningFlags dfs) }
1844
1845 -- | Test whether a 'LangExt.Extension' is set
1846 xopt :: LangExt.Extension -> DynFlags -> Bool
1847 xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags
1848
1849 -- | Set a 'LangExt.Extension'
1850 xopt_set :: DynFlags -> LangExt.Extension -> DynFlags
1851 xopt_set dfs f
1852 = let onoffs = On f : extensions dfs
1853 in dfs { extensions = onoffs,
1854 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
1855
1856 -- | Unset a 'LangExt.Extension'
1857 xopt_unset :: DynFlags -> LangExt.Extension -> DynFlags
1858 xopt_unset dfs f
1859 = let onoffs = Off f : extensions dfs
1860 in dfs { extensions = onoffs,
1861 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
1862
1863 lang_set :: DynFlags -> Maybe Language -> DynFlags
1864 lang_set dflags lang =
1865 dflags {
1866 language = lang,
1867 extensionFlags = flattenExtensionFlags lang (extensions dflags)
1868 }
1869
1870 -- | An internal helper to check whether to use unicode syntax for output.
1871 --
1872 -- Note: You should very likely be using 'Outputable.unicodeSyntax' instead
1873 -- of this function.
1874 useUnicodeSyntax :: DynFlags -> Bool
1875 useUnicodeSyntax = gopt Opt_PrintUnicodeSyntax
1876
1877 -- | Set the Haskell language standard to use
1878 setLanguage :: Language -> DynP ()
1879 setLanguage l = upd (`lang_set` Just l)
1880
1881 -- | Some modules have dependencies on others through the DynFlags rather than textual imports
1882 dynFlagDependencies :: DynFlags -> [ModuleName]
1883 dynFlagDependencies = pluginModNames
1884
1885 -- | Is the -fpackage-trust mode on
1886 packageTrustOn :: DynFlags -> Bool
1887 packageTrustOn = gopt Opt_PackageTrust
1888
1889 -- | Is Safe Haskell on in some way (including inference mode)
1890 safeHaskellOn :: DynFlags -> Bool
1891 safeHaskellOn dflags = safeHaskell dflags /= Sf_None || safeInferOn dflags
1892
1893 -- | Is the Safe Haskell safe language in use
1894 safeLanguageOn :: DynFlags -> Bool
1895 safeLanguageOn dflags = safeHaskell dflags == Sf_Safe
1896
1897 -- | Is the Safe Haskell safe inference mode active
1898 safeInferOn :: DynFlags -> Bool
1899 safeInferOn = safeInfer
1900
1901 -- | Test if Safe Imports are on in some form
1902 safeImportsOn :: DynFlags -> Bool
1903 safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
1904 safeHaskell dflags == Sf_Trustworthy ||
1905 safeHaskell dflags == Sf_Safe
1906
1907 -- | Set a 'Safe Haskell' flag
1908 setSafeHaskell :: SafeHaskellMode -> DynP ()
1909 setSafeHaskell s = updM f
1910 where f dfs = do
1911 let sf = safeHaskell dfs
1912 safeM <- combineSafeFlags sf s
1913 case s of
1914 Sf_Safe -> return $ dfs { safeHaskell = safeM, safeInfer = False }
1915 -- leave safe inferrence on in Trustworthy mode so we can warn
1916 -- if it could have been inferred safe.
1917 Sf_Trustworthy -> do
1918 l <- getCurLoc
1919 return $ dfs { safeHaskell = safeM, trustworthyOnLoc = l }
1920 -- leave safe inference on in Unsafe mode as well.
1921 _ -> return $ dfs { safeHaskell = safeM }
1922
1923 -- | Are all direct imports required to be safe for this Safe Haskell mode?
1924 -- Direct imports are when the code explicitly imports a module
1925 safeDirectImpsReq :: DynFlags -> Bool
1926 safeDirectImpsReq d = safeLanguageOn d
1927
1928 -- | Are all implicit imports required to be safe for this Safe Haskell mode?
1929 -- Implicit imports are things in the prelude. e.g System.IO when print is used.
1930 safeImplicitImpsReq :: DynFlags -> Bool
1931 safeImplicitImpsReq d = safeLanguageOn d
1932
1933 -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
1934 -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
1935 -- want to export this functionality from the module but do want to export the
1936 -- type constructors.
1937 combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
1938 combineSafeFlags a b | a == Sf_None = return b
1939 | b == Sf_None = return a
1940 | a == b = return a
1941 | otherwise = addErr errm >> pure a
1942 where errm = "Incompatible Safe Haskell flags! ("
1943 ++ show a ++ ", " ++ show b ++ ")"
1944
1945 -- | A list of unsafe flags under Safe Haskell. Tuple elements are:
1946 -- * name of the flag
1947 -- * function to get srcspan that enabled the flag
1948 -- * function to test if the flag is on
1949 -- * function to turn the flag off
1950 unsafeFlags, unsafeFlagsForInfer
1951 :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
1952 unsafeFlags = [ ("-XGeneralizedNewtypeDeriving", newDerivOnLoc,
1953 xopt LangExt.GeneralizedNewtypeDeriving,
1954 flip xopt_unset LangExt.GeneralizedNewtypeDeriving)
1955 , ("-XTemplateHaskell", thOnLoc,
1956 xopt LangExt.TemplateHaskell,
1957 flip xopt_unset LangExt.TemplateHaskell)
1958 ]
1959 unsafeFlagsForInfer = unsafeFlags
1960
1961
1962 -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
1963 getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
1964 -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
1965 -> [a] -- ^ Correctly ordered extracted options
1966 getOpts dflags opts = reverse (opts dflags)
1967 -- We add to the options from the front, so we need to reverse the list
1968
1969 -- | Gets the verbosity flag for the current verbosity level. This is fed to
1970 -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
1971 getVerbFlags :: DynFlags -> [String]
1972 getVerbFlags dflags
1973 | verbosity dflags >= 4 = ["-v"]
1974 | otherwise = []
1975
1976 setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir,
1977 setDynObjectSuf, setDynHiSuf,
1978 setDylibInstallName,
1979 setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode,
1980 setPgmP, addOptl, addOptc, addOptP,
1981 addCmdlineFramework, addHaddockOpts, addGhciScript,
1982 setInteractivePrint
1983 :: String -> DynFlags -> DynFlags
1984 setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce
1985 :: Maybe String -> DynFlags -> DynFlags
1986
1987 setObjectDir f d = d { objectDir = Just f}
1988 setHiDir f d = d { hiDir = Just f}
1989 setStubDir f d = d { stubDir = Just f, includePaths = f : includePaths d }
1990 -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
1991 -- \#included from the .hc file when compiling via C (i.e. unregisterised
1992 -- builds).
1993 setDumpDir f d = d { dumpDir = Just f}
1994 setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f
1995 setDylibInstallName f d = d { dylibInstallName = Just f}
1996
1997 setObjectSuf f d = d { objectSuf = f}
1998 setDynObjectSuf f d = d { dynObjectSuf = f}
1999 setHiSuf f d = d { hiSuf = f}
2000 setDynHiSuf f d = d { dynHiSuf = f}
2001 setHcSuf f d = d { hcSuf = f}
2002
2003 setOutputFile f d = d { outputFile = f}
2004 setDynOutputFile f d = d { dynOutputFile = f}
2005 setOutputHi f d = d { outputHi = f}
2006
2007 thisComponentId :: DynFlags -> ComponentId
2008 thisComponentId dflags =
2009 case thisComponentId_ dflags of
2010 Just cid -> cid
2011 Nothing ->
2012 case thisUnitIdInsts_ dflags of
2013 Just _ ->
2014 throwGhcException $ CmdLineError ("Use of -instantiated-with requires -this-component-id")
2015 Nothing -> ComponentId (unitIdFS (thisPackage dflags))
2016
2017 thisUnitIdInsts :: DynFlags -> [(ModuleName, Module)]
2018 thisUnitIdInsts dflags =
2019 case thisUnitIdInsts_ dflags of
2020 Just insts -> insts
2021 Nothing -> []
2022
2023 thisPackage :: DynFlags -> UnitId
2024 thisPackage dflags =
2025 case thisUnitIdInsts_ dflags of
2026 Nothing -> default_uid
2027 Just insts
2028 | all (\(x,y) -> mkHoleModule x == y) insts
2029 -> newUnitId (thisComponentId dflags) insts
2030 | otherwise
2031 -> default_uid
2032 where
2033 default_uid = DefiniteUnitId (DefUnitId (thisInstalledUnitId dflags))
2034
2035 parseUnitIdInsts :: String -> [(ModuleName, Module)]
2036 parseUnitIdInsts str = case filter ((=="").snd) (readP_to_S parse str) of
2037 [(r, "")] -> r
2038 _ -> throwGhcException $ CmdLineError ("Can't parse -instantiated-with: " ++ str)
2039 where parse = sepBy parseEntry (R.char ',')
2040 parseEntry = do
2041 n <- parseModuleName
2042 _ <- R.char '='
2043 m <- parseModuleId
2044 return (n, m)
2045
2046 setUnitIdInsts :: String -> DynFlags -> DynFlags
2047 setUnitIdInsts s d =
2048 d { thisUnitIdInsts_ = Just (parseUnitIdInsts s) }
2049
2050 setComponentId :: String -> DynFlags -> DynFlags
2051 setComponentId s d =
2052 d { thisComponentId_ = Just (ComponentId (fsLit s)) }
2053
2054 addPluginModuleName :: String -> DynFlags -> DynFlags
2055 addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
2056
2057 addPluginModuleNameOption :: String -> DynFlags -> DynFlags
2058 addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
2059 where (m, rest) = break (== ':') optflag
2060 option = case rest of
2061 [] -> "" -- should probably signal an error
2062 (_:plug_opt) -> plug_opt -- ignore the ':' from break
2063
2064 addFrontendPluginOption :: String -> DynFlags -> DynFlags
2065 addFrontendPluginOption s d = d { frontendPluginOpts = s : frontendPluginOpts d }
2066
2067 parseDynLibLoaderMode f d =
2068 case splitAt 8 f of
2069 ("deploy", "") -> d { dynLibLoader = Deployable }
2070 ("sysdep", "") -> d { dynLibLoader = SystemDependent }
2071 _ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f))
2072
2073 setDumpPrefixForce f d = d { dumpPrefixForce = f}
2074
2075 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
2076 -- Config.hs should really use Option.
2077 setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)})
2078 addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s})
2079 addOptc f = alterSettings (\s -> s { sOpt_c = f : sOpt_c s})
2080 addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s})
2081
2082
2083 setDepMakefile :: FilePath -> DynFlags -> DynFlags
2084 setDepMakefile f d = d { depMakefile = f }
2085
2086 setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
2087 setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
2088
2089 addDepExcludeMod :: String -> DynFlags -> DynFlags
2090 addDepExcludeMod m d
2091 = d { depExcludeMods = mkModuleName m : depExcludeMods d }
2092
2093 addDepSuffix :: FilePath -> DynFlags -> DynFlags
2094 addDepSuffix s d = d { depSuffixes = s : depSuffixes d }
2095
2096 addCmdlineFramework f d = d { cmdlineFrameworks = f : cmdlineFrameworks d}
2097
2098 addHaddockOpts f d = d { haddockOptions = Just f}
2099
2100 addGhciScript f d = d { ghciScripts = f : ghciScripts d}
2101
2102 setInteractivePrint f d = d { interactivePrint = Just f}
2103
2104 -- -----------------------------------------------------------------------------
2105 -- Command-line options
2106
2107 -- | When invoking external tools as part of the compilation pipeline, we
2108 -- pass these a sequence of options on the command-line. Rather than
2109 -- just using a list of Strings, we use a type that allows us to distinguish
2110 -- between filepaths and 'other stuff'. The reason for this is that
2111 -- this type gives us a handle on transforming filenames, and filenames only,
2112 -- to whatever format they're expected to be on a particular platform.
2113 data Option
2114 = FileOption -- an entry that _contains_ filename(s) / filepaths.
2115 String -- a non-filepath prefix that shouldn't be
2116 -- transformed (e.g., "/out=")
2117 String -- the filepath/filename portion
2118 | Option String
2119 deriving ( Eq )
2120
2121 showOpt :: Option -> String
2122 showOpt (FileOption pre f) = pre ++ f
2123 showOpt (Option s) = s
2124
2125 -----------------------------------------------------------------------------
2126 -- Setting the optimisation level
2127
2128 updOptLevel :: Int -> DynFlags -> DynFlags
2129 -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
2130 updOptLevel n dfs
2131 = dfs2{ optLevel = final_n }
2132 where
2133 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
2134 dfs1 = foldr (flip gopt_unset) dfs remove_gopts
2135 dfs2 = foldr (flip gopt_set) dfs1 extra_gopts
2136
2137 extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
2138 remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
2139
2140 {- **********************************************************************
2141 %* *
2142 DynFlags parser
2143 %* *
2144 %********************************************************************* -}
2145
2146 -- -----------------------------------------------------------------------------
2147 -- Parsing the dynamic flags.
2148
2149
2150 -- | Parse dynamic flags from a list of command line arguments. Returns the
2151 -- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
2152 -- Throws a 'UsageError' if errors occurred during parsing (such as unknown
2153 -- flags or missing arguments).
2154 parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String]
2155 -> m (DynFlags, [Located String], [Located String])
2156 -- ^ Updated 'DynFlags', left-over arguments, and
2157 -- list of warnings.
2158 parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True
2159
2160
2161 -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
2162 -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db).
2163 -- Used to parse flags set in a modules pragma.
2164 parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String]
2165 -> m (DynFlags, [Located String], [Located String])
2166 -- ^ Updated 'DynFlags', left-over arguments, and
2167 -- list of warnings.
2168 parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False
2169
2170
2171 -- | Parses the dynamically set flags for GHC. This is the most general form of
2172 -- the dynamic flag parser that the other methods simply wrap. It allows
2173 -- saying which flags are valid flags and indicating if we are parsing
2174 -- arguments from the command line or from a file pragma.
2175 parseDynamicFlagsFull :: MonadIO m
2176 => [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against
2177 -> Bool -- ^ are the arguments from the command line?
2178 -> DynFlags -- ^ current dynamic flags
2179 -> [Located String] -- ^ arguments to parse
2180 -> m (DynFlags, [Located String], [Located String])
2181 parseDynamicFlagsFull activeFlags cmdline dflags0 args = do
2182 let ((leftover, errs, warns), dflags1)
2183 = runCmdLine (processArgs activeFlags args) dflags0
2184
2185 -- See Note [Handling errors when parsing commandline flags]
2186 unless (null errs) $ liftIO $ throwGhcExceptionIO $
2187 errorsToGhcException . map (showPpr dflags0 . getLoc &&& unLoc) $ errs
2188
2189 -- check for disabled flags in safe haskell
2190 let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1
2191 dflags3 = updateWays dflags2
2192 theWays = ways dflags3
2193
2194 unless (allowed_combination theWays) $ liftIO $
2195 throwGhcExceptionIO (CmdLineError ("combination not supported: " ++
2196 intercalate "/" (map wayDesc theWays)))
2197
2198 let chooseOutput
2199 | isJust (outputFile dflags3) -- Only iff user specified -o ...
2200 , not (isJust (dynOutputFile dflags3)) -- but not -dyno
2201 = return $ dflags3 { dynOutputFile = Just $ dynOut (fromJust $ outputFile dflags3) }
2202 | otherwise
2203 = return dflags3
2204 where
2205 dynOut = flip addExtension (dynObjectSuf dflags3) . dropExtension
2206 dflags4 <- ifGeneratingDynamicToo dflags3 chooseOutput (return dflags3)
2207
2208 let (dflags5, consistency_warnings) = makeDynFlagsConsistent dflags4
2209
2210 dflags6 <- case dllSplitFile dflags5 of
2211 Nothing -> return (dflags5 { dllSplit = Nothing })
2212 Just f ->
2213 case dllSplit dflags5 of
2214 Just _ ->
2215 -- If dllSplit is out of date then it would have
2216 -- been set to Nothing. As it's a Just, it must be
2217 -- up-to-date.
2218 return dflags5
2219 Nothing ->
2220 do xs <- liftIO $ readFile f
2221 let ss = map (Set.fromList . words) (lines xs)
2222 return $ dflags5 { dllSplit = Just ss }
2223
2224 -- Set timer stats & heap size
2225 when (enableTimeStats dflags6) $ liftIO enableTimingStats
2226 case (ghcHeapSize dflags6) of
2227 Just x -> liftIO (setHeapSize x)
2228 _ -> return ()
2229
2230 liftIO $ setUnsafeGlobalDynFlags dflags6
2231
2232 return (dflags6, leftover, consistency_warnings ++ sh_warns ++ warns)
2233
2234 updateWays :: DynFlags -> DynFlags
2235 updateWays dflags
2236 = let theWays = sort $ nub $ ways dflags
2237 in dflags {
2238 ways = theWays,
2239 buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays),
2240 rtsBuildTag = mkBuildTag theWays
2241 }
2242
2243 -- | Check (and potentially disable) any extensions that aren't allowed
2244 -- in safe mode.
2245 --
2246 -- The bool is to indicate if we are parsing command line flags (false means
2247 -- file pragma). This allows us to generate better warnings.
2248 safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
2249 safeFlagCheck _ dflags | safeLanguageOn dflags = (dflagsUnset, warns)
2250 where
2251 -- Handle illegal flags under safe language.
2252 (dflagsUnset, warns) = foldl check_method (dflags, []) unsafeFlags
2253
2254 check_method (df, warns) (str,loc,test,fix)
2255 | test df = (fix df, warns ++ safeFailure (loc df) str)
2256 | otherwise = (df, warns)
2257
2258 safeFailure loc str
2259 = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring "
2260 ++ str]
2261
2262 safeFlagCheck cmdl dflags =
2263 case (safeInferOn dflags) of
2264 True | safeFlags -> (dflags', warn)
2265 True -> (dflags' { safeInferred = False }, warn)
2266 False -> (dflags', warn)
2267
2268 where
2269 -- dynflags and warn for when -fpackage-trust by itself with no safe
2270 -- haskell flag
2271 (dflags', warn)
2272 | safeHaskell dflags == Sf_None && not cmdl && packageTrustOn dflags
2273 = (gopt_unset dflags Opt_PackageTrust, pkgWarnMsg)
2274 | otherwise = (dflags, [])
2275
2276 pkgWarnMsg = [L (pkgTrustOnLoc dflags') $
2277 "-fpackage-trust ignored;" ++
2278 " must be specified with a Safe Haskell flag"]
2279
2280 -- Have we inferred Unsafe? See Note [HscMain . Safe Haskell Inference]
2281 safeFlags = all (\(_,_,t,_) -> not $ t dflags) unsafeFlagsForInfer
2282
2283
2284 {- **********************************************************************
2285 %* *
2286 DynFlags specifications
2287 %* *
2288 %********************************************************************* -}
2289
2290 -- | All dynamic flags option strings without the deprecated ones.
2291 -- These are the user facing strings for enabling and disabling options.
2292 allNonDeprecatedFlags :: [String]
2293 allNonDeprecatedFlags = allFlagsDeps False
2294
2295 -- | All flags with possibility to filter deprecated ones
2296 allFlagsDeps :: Bool -> [String]
2297 allFlagsDeps keepDeprecated = [ '-':flagName flag
2298 | (deprecated, flag) <- flagsAllDeps
2299 , ok (flagOptKind flag)
2300 , keepDeprecated || not (isDeprecated deprecated)]
2301 where ok (PrefixPred _ _) = False
2302 ok _ = True
2303 isDeprecated Deprecated = True
2304 isDeprecated _ = False
2305
2306 {-
2307 - Below we export user facing symbols for GHC dynamic flags for use with the
2308 - GHC API.
2309 -}
2310
2311 -- All dynamic flags present in GHC.
2312 flagsAll :: [Flag (CmdLineP DynFlags)]
2313 flagsAll = map snd flagsAllDeps
2314
2315 -- All dynamic flags present in GHC with deprecation information.
2316 flagsAllDeps :: [(Deprecation, Flag (CmdLineP DynFlags))]
2317 flagsAllDeps = package_flags_deps ++ dynamic_flags_deps
2318
2319
2320 -- All dynamic flags, minus package flags, present in GHC.
2321 flagsDynamic :: [Flag (CmdLineP DynFlags)]
2322 flagsDynamic = map snd dynamic_flags_deps
2323
2324 -- ALl package flags present in GHC.
2325 flagsPackage :: [Flag (CmdLineP DynFlags)]
2326 flagsPackage = map snd package_flags_deps
2327
2328 ----------------Helpers to make flags and keep deprecation information----------
2329
2330 type FlagMaker m = String -> OptKind m -> Flag m
2331 type DynFlagMaker = FlagMaker (CmdLineP DynFlags)
2332 data Deprecation = NotDeprecated | Deprecated deriving (Eq, Ord)
2333
2334 -- Make a non-deprecated flag
2335 make_ord_flag :: DynFlagMaker -> String -> OptKind (CmdLineP DynFlags)
2336 -> (Deprecation, Flag (CmdLineP DynFlags))
2337 make_ord_flag fm name kind = (NotDeprecated, fm name kind)
2338
2339 -- Make a deprecated flag
2340 make_dep_flag :: DynFlagMaker -> String -> OptKind (CmdLineP DynFlags) -> String
2341 -> (Deprecation, Flag (CmdLineP DynFlags))
2342 make_dep_flag fm name kind message = (Deprecated,
2343 fm name $ add_dep_message kind message)
2344
2345 add_dep_message :: OptKind (CmdLineP DynFlags) -> String
2346 -> OptKind (CmdLineP DynFlags)
2347 add_dep_message (NoArg f) message = NoArg $ f >> deprecate message
2348 add_dep_message (HasArg f) message = HasArg $ \s -> f s >> deprecate message
2349 add_dep_message (SepArg f) message = SepArg $ \s -> f s >> deprecate message
2350 add_dep_message (Prefix f) message = Prefix $ \s -> f s >> deprecate message
2351 add_dep_message (OptPrefix f) message =
2352 OptPrefix $ \s -> f s >> deprecate message
2353 add_dep_message (OptIntSuffix f) message =
2354 OptIntSuffix $ \oi -> f oi >> deprecate message
2355 add_dep_message (IntSuffix f) message =
2356 IntSuffix $ \i -> f i >> deprecate message
2357 add_dep_message (FloatSuffix f) message =
2358 FloatSuffix $ \fl -> f fl >> deprecate message
2359 add_dep_message (PassFlag f) message =
2360 PassFlag $ \s -> f s >> deprecate message
2361 add_dep_message (AnySuffix f) message =
2362 AnySuffix $ \s -> f s >> deprecate message
2363 add_dep_message (PrefixPred pred f) message =
2364 PrefixPred pred $ \s -> f s >> deprecate message
2365 add_dep_message (AnySuffixPred pred f) message =
2366 AnySuffixPred pred $ \s -> f s >> deprecate message
2367
2368 ----------------------- The main flags themselves ------------------------------
2369 -- See Note [Updating flag description in the User's Guide]
2370 -- See Note [Supporting CLI completion]
2371 dynamic_flags_deps :: [(Deprecation, Flag (CmdLineP DynFlags))]
2372 dynamic_flags_deps = [
2373 make_dep_flag defFlag "n" (NoArg $ return ())
2374 "The -n flag is deprecated and no longer has any effect"
2375 , make_ord_flag defFlag "cpp" (NoArg (setExtensionFlag LangExt.Cpp))
2376 , make_ord_flag defFlag "F" (NoArg (setGeneralFlag Opt_Pp))
2377 , (Deprecated, defFlag "#include"
2378 (HasArg (\_s ->
2379 addWarn ("-#include and INCLUDE pragmas are " ++
2380 "deprecated: They no longer have any effect"))))
2381 , make_ord_flag defFlag "v" (OptIntSuffix setVerbosity)
2382
2383 , make_ord_flag defGhcFlag "j" (OptIntSuffix
2384 (\n -> case n of
2385 Just n
2386 | n > 0 -> upd (\d -> d { parMakeCount = Just n })
2387 | otherwise -> addErr "Syntax: -j[n] where n > 0"
2388 Nothing -> upd (\d -> d { parMakeCount = Nothing })))
2389 -- When the number of parallel builds
2390 -- is omitted, it is the same
2391 -- as specifing that the number of
2392 -- parallel builds is equal to the
2393 -- result of getNumProcessors
2394 , make_ord_flag defFlag "instantiated-with" (sepArg setUnitIdInsts)
2395 , make_ord_flag defFlag "this-component-id" (sepArg setComponentId)
2396
2397 -- RTS options -------------------------------------------------------------
2398 , make_ord_flag defFlag "H" (HasArg (\s -> upd (\d ->
2399 d { ghcHeapSize = Just $ fromIntegral (decodeSize s)})))
2400
2401 , make_ord_flag defFlag "Rghc-timing" (NoArg (upd (\d ->
2402 d { enableTimeStats = True })))
2403
2404 ------- ways ---------------------------------------------------------------
2405 , make_ord_flag defGhcFlag "prof" (NoArg (addWay WayProf))
2406 , make_ord_flag defGhcFlag "eventlog" (NoArg (addWay WayEventLog))
2407 , make_dep_flag defGhcFlag "smp"
2408 (NoArg $ addWay WayThreaded) "Use -threaded instead"
2409 , make_ord_flag defGhcFlag "debug" (NoArg (addWay WayDebug))
2410 , make_ord_flag defGhcFlag "threaded" (NoArg (addWay WayThreaded))
2411
2412 , make_ord_flag defGhcFlag "ticky"
2413 (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug))
2414
2415 -- -ticky enables ticky-ticky code generation, and also implies -debug which
2416 -- is required to get the RTS ticky support.
2417
2418 ----- Linker --------------------------------------------------------
2419 , make_ord_flag defGhcFlag "static" (NoArg removeWayDyn)
2420 , make_ord_flag defGhcFlag "dynamic" (NoArg (addWay WayDyn))
2421 , make_ord_flag defGhcFlag "rdynamic" $ noArg $
2422 #ifdef linux_HOST_OS
2423 addOptl "-rdynamic"
2424 #elif defined (mingw32_HOST_OS)
2425 addOptl "-Wl,--export-all-symbols"
2426 #else
2427 -- ignored for compat w/ gcc:
2428 id
2429 #endif
2430 , make_ord_flag defGhcFlag "relative-dynlib-paths"
2431 (NoArg (setGeneralFlag Opt_RelativeDynlibPaths))
2432
2433 ------- Specific phases --------------------------------------------
2434 -- need to appear before -pgmL to be parsed as LLVM flags.
2435 , make_ord_flag defFlag "pgmlo"
2436 (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
2437 , make_ord_flag defFlag "pgmlc"
2438 (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
2439 , make_ord_flag defFlag "pgmi"
2440 (hasArg (\f -> alterSettings (\s -> s { sPgm_i = f})))
2441 , make_ord_flag defFlag "pgmL"
2442 (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
2443 , make_ord_flag defFlag "pgmP"
2444 (hasArg setPgmP)
2445 , make_ord_flag defFlag "pgmF"
2446 (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
2447 , make_ord_flag defFlag "pgmc"
2448 (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])})))
2449 , make_ord_flag defFlag "pgms"
2450 (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])})))
2451 , make_ord_flag defFlag "pgma"
2452 (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
2453 , make_ord_flag defFlag "pgml"
2454 (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
2455 , make_ord_flag defFlag "pgmdll"
2456 (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
2457 , make_ord_flag defFlag "pgmwindres"
2458 (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
2459 , make_ord_flag defFlag "pgmlibtool"
2460 (hasArg (\f -> alterSettings (\s -> s { sPgm_libtool = f})))
2461
2462 -- need to appear before -optl/-opta to be parsed as LLVM flags.
2463 , make_ord_flag defFlag "optlo"
2464 (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
2465 , make_ord_flag defFlag "optlc"
2466 (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
2467 , make_ord_flag defFlag "opti"
2468 (hasArg (\f -> alterSettings (\s -> s { sOpt_i = f : sOpt_i s})))
2469 , make_ord_flag defFlag "optL"
2470 (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
2471 , make_ord_flag defFlag "optP"
2472 (hasArg addOptP)
2473 , make_ord_flag defFlag "optF"
2474 (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
2475 , make_ord_flag defFlag "optc"
2476 (hasArg addOptc)
2477 , make_ord_flag defFlag "opta"
2478 (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
2479 , make_ord_flag defFlag "optl"
2480 (hasArg addOptl)
2481 , make_ord_flag defFlag "optwindres"
2482 (hasArg (\f ->
2483 alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
2484
2485 , make_ord_flag defGhcFlag "split-objs"
2486 (NoArg (if can_split
2487 then setGeneralFlag Opt_SplitObjs
2488 else addWarn "ignoring -fsplit-objs"))
2489
2490 , make_ord_flag defGhcFlag "split-sections"
2491 (noArgM (\dflags -> do
2492 if platformHasSubsectionsViaSymbols (targetPlatform dflags)
2493 then do addErr $
2494 "-split-sections is not useful on this platform " ++
2495 "since it always uses subsections via symbols."
2496 return dflags
2497 else return (gopt_set dflags Opt_SplitSections)))
2498
2499 -------- ghc -M -----------------------------------------------------
2500 , make_ord_flag defGhcFlag "dep-suffix" (hasArg addDepSuffix)
2501 , make_ord_flag defGhcFlag "dep-makefile" (hasArg setDepMakefile)
2502 , make_ord_flag defGhcFlag "include-pkg-deps"
2503 (noArg (setDepIncludePkgDeps True))
2504 , make_ord_flag defGhcFlag "exclude-module" (hasArg addDepExcludeMod)
2505
2506 -------- Linking ----------------------------------------------------
2507 , make_ord_flag defGhcFlag "no-link"
2508 (noArg (\d -> d { ghcLink=NoLink }))
2509 , make_ord_flag defGhcFlag "shared"
2510 (noArg (\d -> d { ghcLink=LinkDynLib }))
2511 , make_ord_flag defGhcFlag "staticlib"
2512 (noArg (\d -> d { ghcLink=LinkStaticLib }))
2513 , make_ord_flag defGhcFlag "dynload" (hasArg parseDynLibLoaderMode)
2514 , make_ord_flag defGhcFlag "dylib-install-name" (hasArg setDylibInstallName)
2515 -- -dll-split is an internal flag, used only during the GHC build
2516 , make_ord_flag defHiddenFlag "dll-split"
2517 (hasArg (\f d -> d { dllSplitFile = Just f, dllSplit = Nothing }))
2518
2519 ------- Libraries ---------------------------------------------------
2520 , make_ord_flag defFlag "L" (Prefix addLibraryPath)
2521 , make_ord_flag defFlag "l" (hasArg (addLdInputs . Option . ("-l" ++)))
2522
2523 ------- Frameworks --------------------------------------------------
2524 -- -framework-path should really be -F ...
2525 , make_ord_flag defFlag "framework-path" (HasArg addFrameworkPath)
2526 , make_ord_flag defFlag "framework" (hasArg addCmdlineFramework)
2527
2528 ------- Output Redirection ------------------------------------------
2529 , make_ord_flag defGhcFlag "odir" (hasArg setObjectDir)
2530 , make_ord_flag defGhcFlag "o" (sepArg (setOutputFile . Just))
2531 , make_ord_flag defGhcFlag "dyno"
2532 (sepArg (setDynOutputFile . Just))
2533 , make_ord_flag defGhcFlag "ohi"
2534 (hasArg (setOutputHi . Just ))
2535 , make_ord_flag defGhcFlag "osuf" (hasArg setObjectSuf)
2536 , make_ord_flag defGhcFlag "dynosuf" (hasArg setDynObjectSuf)
2537 , make_ord_flag defGhcFlag "hcsuf" (hasArg setHcSuf)
2538 , make_ord_flag defGhcFlag "hisuf" (hasArg setHiSuf)
2539 , make_ord_flag defGhcFlag "dynhisuf" (hasArg setDynHiSuf)
2540 , make_ord_flag defGhcFlag "hidir" (hasArg setHiDir)
2541 , make_ord_flag defGhcFlag "tmpdir" (hasArg setTmpDir)
2542 , make_ord_flag defGhcFlag "stubdir" (hasArg setStubDir)
2543 , make_ord_flag defGhcFlag "dumpdir" (hasArg setDumpDir)
2544 , make_ord_flag defGhcFlag "outputdir" (hasArg setOutputDir)
2545 , make_ord_flag defGhcFlag "ddump-file-prefix"
2546 (hasArg (setDumpPrefixForce . Just))
2547
2548 , make_ord_flag defGhcFlag "dynamic-too"
2549 (NoArg (setGeneralFlag Opt_BuildDynamicToo))
2550
2551 ------- Keeping temporary files -------------------------------------
2552 -- These can be singular (think ghc -c) or plural (think ghc --make)
2553 , make_ord_flag defGhcFlag "keep-hc-file"
2554 (NoArg (setGeneralFlag Opt_KeepHcFiles))
2555 , make_ord_flag defGhcFlag "keep-hc-files"
2556 (NoArg (setGeneralFlag Opt_KeepHcFiles))
2557 , make_ord_flag defGhcFlag "keep-s-file"
2558 (NoArg (setGeneralFlag Opt_KeepSFiles))
2559 , make_ord_flag defGhcFlag "keep-s-files"
2560 (NoArg (setGeneralFlag Opt_KeepSFiles))
2561 , make_ord_flag defGhcFlag "keep-llvm-file"
2562 (NoArg $ setObjTarget HscLlvm >> setGeneralFlag Opt_KeepLlvmFiles)
2563 , make_ord_flag defGhcFlag "keep-llvm-files"
2564 (NoArg $ setObjTarget HscLlvm >> setGeneralFlag Opt_KeepLlvmFiles)
2565 -- This only makes sense as plural
2566 , make_ord_flag defGhcFlag "keep-tmp-files"
2567 (NoArg (setGeneralFlag Opt_KeepTmpFiles))
2568 , make_ord_flag defGhcFlag "keep-hi-file"
2569 (NoArg (setGeneralFlag Opt_KeepHiFiles))
2570 , make_ord_flag defGhcFlag "no-keep-hi-file"
2571 (NoArg (unSetGeneralFlag Opt_KeepHiFiles))
2572 , make_ord_flag defGhcFlag "keep-hi-files"
2573 (NoArg (setGeneralFlag Opt_KeepHiFiles))
2574 , make_ord_flag defGhcFlag "no-keep-hi-files"
2575 (NoArg (unSetGeneralFlag Opt_KeepHiFiles))
2576 , make_ord_flag defGhcFlag "keep-o-file"
2577 (NoArg (setGeneralFlag Opt_KeepOFiles))
2578 , make_ord_flag defGhcFlag "no-keep-o-file"
2579 (NoArg (unSetGeneralFlag Opt_KeepOFiles))
2580 , make_ord_flag defGhcFlag "keep-o-files"
2581 (NoArg (setGeneralFlag Opt_KeepOFiles))
2582 , make_ord_flag defGhcFlag "no-keep-o-files"
2583 (NoArg (unSetGeneralFlag Opt_KeepOFiles))
2584
2585 ------- Miscellaneous ----------------------------------------------
2586 , make_ord_flag defGhcFlag "no-auto-link-packages"
2587 (NoArg (unSetGeneralFlag Opt_AutoLinkPackages))
2588 , make_ord_flag defGhcFlag "no-hs-main"
2589 (NoArg (setGeneralFlag Opt_NoHsMain))
2590 , make_ord_flag defGhcFlag "with-rtsopts"
2591 (HasArg setRtsOpts)
2592 , make_ord_flag defGhcFlag "rtsopts"
2593 (NoArg (setRtsOptsEnabled RtsOptsAll))
2594 , make_ord_flag defGhcFlag "rtsopts=all"
2595 (NoArg (setRtsOptsEnabled RtsOptsAll))
2596 , make_ord_flag defGhcFlag "rtsopts=some"
2597 (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
2598 , make_ord_flag defGhcFlag "rtsopts=none"
2599 (NoArg (setRtsOptsEnabled RtsOptsNone))
2600 , make_ord_flag defGhcFlag "no-rtsopts"
2601 (NoArg (setRtsOptsEnabled RtsOptsNone))
2602 , make_ord_flag defGhcFlag "no-rtsopts-suggestions"
2603 (noArg (\d -> d {rtsOptsSuggestions = False}))
2604
2605 , make_ord_flag defGhcFlag "main-is" (SepArg setMainIs)
2606 , make_ord_flag defGhcFlag "haddock" (NoArg (setGeneralFlag Opt_Haddock))
2607 , make_ord_flag defGhcFlag "haddock-opts" (hasArg addHaddockOpts)
2608 , make_ord_flag defGhcFlag "hpcdir" (SepArg setOptHpcDir)
2609 , make_ord_flag defGhciFlag "ghci-script" (hasArg addGhciScript)
2610 , make_ord_flag defGhciFlag "interactive-print" (hasArg setInteractivePrint)
2611 , make_ord_flag defGhcFlag "ticky-allocd"
2612 (NoArg (setGeneralFlag Opt_Ticky_Allocd))
2613 , make_ord_flag defGhcFlag "ticky-LNE"
2614 (NoArg (setGeneralFlag Opt_Ticky_LNE))
2615 , make_ord_flag defGhcFlag "ticky-dyn-thunk"
2616 (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk))
2617 ------- recompilation checker --------------------------------------
2618 , make_dep_flag defGhcFlag "recomp"
2619 (NoArg $ unSetGeneralFlag Opt_ForceRecomp)
2620 "Use -fno-force-recomp instead"
2621 , make_dep_flag defGhcFlag "no-recomp"
2622 (NoArg $ setGeneralFlag Opt_ForceRecomp) "Use -fforce-recomp instead"
2623 , make_ord_flag defFlag "freverse-errors"
2624 (noArg (\d -> d {reverseErrors = True} ))
2625 , make_ord_flag defFlag "fno-reverse-errors"
2626 (noArg (\d -> d {reverseErrors = False} ))
2627
2628 ------ HsCpp opts ---------------------------------------------------
2629 , make_ord_flag defFlag "D" (AnySuffix (upd . addOptP))
2630 , make_ord_flag defFlag "U" (AnySuffix (upd . addOptP))
2631
2632 ------- Include/Import Paths ----------------------------------------
2633 , make_ord_flag defFlag "I" (Prefix addIncludePath)
2634 , make_ord_flag defFlag "i" (OptPrefix addImportPath)
2635
2636 ------ Output style options -----------------------------------------
2637 , make_ord_flag defFlag "dppr-user-length" (intSuffix (\n d ->
2638 d { pprUserLength = n }))
2639 , make_ord_flag defFlag "dppr-cols" (intSuffix (\n d ->
2640 d { pprCols = n }))
2641 -- Suppress all that is suppressable in core dumps.
2642 -- Except for uniques, as some simplifier phases introduce new variables that
2643 -- have otherwise identical names.
2644 , make_ord_flag defGhcFlag "dsuppress-all"
2645 (NoArg $ do setGeneralFlag Opt_SuppressCoercions
2646 setGeneralFlag Opt_SuppressVarKinds
2647 setGeneralFlag Opt_SuppressModulePrefixes
2648 setGeneralFlag Opt_SuppressTypeApplications
2649 setGeneralFlag Opt_SuppressIdInfo
2650 setGeneralFlag Opt_SuppressTypeSignatures)
2651
2652 ------ Debugging ----------------------------------------------------
2653 , make_ord_flag defGhcFlag "dstg-stats"
2654 (NoArg (setGeneralFlag Opt_StgStats))
2655
2656 , make_ord_flag defGhcFlag "ddump-cmm"
2657 (setDumpFlag Opt_D_dump_cmm)
2658 , make_ord_flag defGhcFlag "ddump-cmm-from-stg"
2659 (setDumpFlag Opt_D_dump_cmm_from_stg)
2660 , make_ord_flag defGhcFlag "ddump-cmm-raw"
2661 (setDumpFlag Opt_D_dump_cmm_raw)
2662 , make_ord_flag defGhcFlag "ddump-cmm-verbose"
2663 (setDumpFlag Opt_D_dump_cmm_verbose)
2664 , make_ord_flag defGhcFlag "ddump-cmm-cfg"
2665 (setDumpFlag Opt_D_dump_cmm_cfg)
2666 , make_ord_flag defGhcFlag "ddump-cmm-cbe"
2667 (setDumpFlag Opt_D_dump_cmm_cbe)
2668 , make_ord_flag defGhcFlag "ddump-cmm-switch"
2669 (setDumpFlag Opt_D_dump_cmm_switch)
2670 , make_ord_flag defGhcFlag "ddump-cmm-proc"
2671 (setDumpFlag Opt_D_dump_cmm_proc)
2672 , make_ord_flag defGhcFlag "ddump-cmm-sp"
2673 (setDumpFlag Opt_D_dump_cmm_sp)
2674 , make_ord_flag defGhcFlag "ddump-cmm-sink"
2675 (setDumpFlag Opt_D_dump_cmm_sink)
2676 , make_ord_flag defGhcFlag "ddump-cmm-caf"
2677 (setDumpFlag Opt_D_dump_cmm_caf)
2678 , make_ord_flag defGhcFlag "ddump-cmm-procmap"
2679 (setDumpFlag Opt_D_dump_cmm_procmap)
2680 , make_ord_flag defGhcFlag "ddump-cmm-split"
2681 (setDumpFlag Opt_D_dump_cmm_split)
2682 , make_ord_flag defGhcFlag "ddump-cmm-info"
2683 (setDumpFlag Opt_D_dump_cmm_info)
2684 , make_ord_flag defGhcFlag "ddump-cmm-cps"
2685 (setDumpFlag Opt_D_dump_cmm_cps)
2686 , make_ord_flag defGhcFlag "ddump-core-stats"
2687 (setDumpFlag Opt_D_dump_core_stats)
2688 , make_ord_flag defGhcFlag "ddump-asm"
2689 (setDumpFlag Opt_D_dump_asm)
2690 , make_ord_flag defGhcFlag "ddump-asm-native"
2691 (setDumpFlag Opt_D_dump_asm_native)
2692 , make_ord_flag defGhcFlag "ddump-asm-liveness"
2693 (setDumpFlag Opt_D_dump_asm_liveness)
2694 , make_ord_flag defGhcFlag "ddump-asm-regalloc"
2695 (setDumpFlag Opt_D_dump_asm_regalloc)
2696 , make_ord_flag defGhcFlag "ddump-asm-conflicts"
2697 (setDumpFlag Opt_D_dump_asm_conflicts)
2698 , make_ord_flag defGhcFlag "ddump-asm-regalloc-stages"
2699 (setDumpFlag Opt_D_dump_asm_regalloc_stages)
2700 , make_ord_flag defGhcFlag "ddump-asm-stats"
2701 (setDumpFlag Opt_D_dump_asm_stats)
2702 , make_ord_flag defGhcFlag "ddump-asm-expanded"
2703 (setDumpFlag Opt_D_dump_asm_expanded)
2704 , make_ord_flag defGhcFlag "ddump-llvm"
2705 (NoArg $ setObjTarget HscLlvm >> setDumpFlag' Opt_D_dump_llvm)
2706 , make_ord_flag defGhcFlag "ddump-deriv"
2707 (setDumpFlag Opt_D_dump_deriv)
2708 , make_ord_flag defGhcFlag "ddump-ds"
2709 (setDumpFlag Opt_D_dump_ds)
2710 , make_ord_flag defGhcFlag "ddump-foreign"
2711 (setDumpFlag Opt_D_dump_foreign)
2712 , make_ord_flag defGhcFlag "ddump-inlinings"
2713 (setDumpFlag Opt_D_dump_inlinings)
2714 , make_ord_flag defGhcFlag "ddump-rule-firings"
2715 (setDumpFlag Opt_D_dump_rule_firings)
2716 , make_ord_flag defGhcFlag "ddump-rule-rewrites"
2717 (setDumpFlag Opt_D_dump_rule_rewrites)
2718 , make_ord_flag defGhcFlag "ddump-simpl-trace"
2719 (setDumpFlag Opt_D_dump_simpl_trace)
2720 , make_ord_flag defGhcFlag "ddump-occur-anal"
2721 (setDumpFlag Opt_D_dump_occur_anal)
2722 , make_ord_flag defGhcFlag "ddump-parsed"
2723 (setDumpFlag Opt_D_dump_parsed)
2724 , make_ord_flag defGhcFlag "ddump-rn"
2725 (setDumpFlag Opt_D_dump_rn)
2726 , make_ord_flag defGhcFlag "ddump-simpl"
2727 (setDumpFlag Opt_D_dump_simpl)
2728 , make_ord_flag defGhcFlag "ddump-simpl-iterations"
2729 (setDumpFlag Opt_D_dump_simpl_iterations)
2730 , make_ord_flag defGhcFlag "ddump-spec"
2731 (setDumpFlag Opt_D_dump_spec)
2732 , make_ord_flag defGhcFlag "ddump-prep"
2733 (setDumpFlag Opt_D_dump_prep)
2734 , make_ord_flag defGhcFlag "ddump-stg"
2735 (setDumpFlag Opt_D_dump_stg)
2736 , make_ord_flag defGhcFlag "ddump-call-arity"
2737 (setDumpFlag Opt_D_dump_call_arity)
2738 , make_ord_flag defGhcFlag "ddump-stranal"
2739 (setDumpFlag Opt_D_dump_stranal)
2740 , make_ord_flag defGhcFlag "ddump-str-signatures"
2741 (setDumpFlag Opt_D_dump_str_signatures)
2742 , make_ord_flag defGhcFlag "ddump-tc"
2743 (setDumpFlag Opt_D_dump_tc)
2744 , make_ord_flag defGhcFlag "ddump-types"
2745 (setDumpFlag Opt_D_dump_types)
2746 , make_ord_flag defGhcFlag "ddump-rules"
2747 (setDumpFlag Opt_D_dump_rules)
2748 , make_ord_flag defGhcFlag "ddump-cse"
2749 (setDumpFlag Opt_D_dump_cse)
2750 , make_ord_flag defGhcFlag "ddump-worker-wrapper"
2751 (setDumpFlag Opt_D_dump_worker_wrapper)
2752 , make_ord_flag defGhcFlag "ddump-rn-trace"
2753 (setDumpFlag Opt_D_dump_rn_trace)
2754 , make_ord_flag defGhcFlag "ddump-shape"
2755 (setDumpFlag Opt_D_dump_shape)
2756 , make_ord_flag defGhcFlag "ddump-if-trace"
2757 (setDumpFlag Opt_D_dump_if_trace)
2758 , make_ord_flag defGhcFlag "ddump-cs-trace"
2759 (setDumpFlag Opt_D_dump_cs_trace)
2760 , make_ord_flag defGhcFlag "ddump-tc-trace"
2761 (NoArg (do setDumpFlag' Opt_D_dump_tc_trace
2762 setDumpFlag' Opt_D_dump_cs_trace))
2763 , make_ord_flag defGhcFlag "ddump-vt-trace"
2764 (setDumpFlag Opt_D_dump_vt_trace)
2765 , make_ord_flag defGhcFlag "ddump-splices"
2766 (setDumpFlag Opt_D_dump_splices)
2767 , make_ord_flag defGhcFlag "dth-dec-file"
2768 (setDumpFlag Opt_D_th_dec_file)
2769
2770 , make_ord_flag defGhcFlag "ddump-rn-stats"
2771 (setDumpFlag Opt_D_dump_rn_stats)
2772 , make_ord_flag defGhcFlag "ddump-opt-cmm"
2773 (setDumpFlag Opt_D_dump_opt_cmm)
2774 , make_ord_flag defGhcFlag "ddump-simpl-stats"
2775 (setDumpFlag Opt_D_dump_simpl_stats)
2776 , make_ord_flag defGhcFlag "ddump-bcos"
2777 (setDumpFlag Opt_D_dump_BCOs)
2778 , make_ord_flag defGhcFlag "dsource-stats"
2779 (setDumpFlag Opt_D_source_stats)
2780 , make_ord_flag defGhcFlag "dverbose-core2core"
2781 (NoArg $ setVerbosity (Just 2) >> setVerboseCore2Core)
2782 , make_ord_flag defGhcFlag "dverbose-stg2stg"
2783 (setDumpFlag Opt_D_verbose_stg2stg)
2784 , make_ord_flag defGhcFlag "ddump-hi"
2785 (setDumpFlag Opt_D_dump_hi)
2786 , make_ord_flag defGhcFlag "ddump-minimal-imports"
2787 (NoArg (setGeneralFlag Opt_D_dump_minimal_imports))
2788 , make_ord_flag defGhcFlag "ddump-vect"
2789 (setDumpFlag Opt_D_dump_vect)
2790 , make_ord_flag defGhcFlag "ddump-hpc"
2791 (setDumpFlag Opt_D_dump_ticked) -- back compat
2792 , make_ord_flag defGhcFlag "ddump-ticked"
2793 (setDumpFlag Opt_D_dump_ticked)
2794 , make_ord_flag defGhcFlag "ddump-mod-cycles"
2795 (setDumpFlag Opt_D_dump_mod_cycles)
2796 , make_ord_flag defGhcFlag "ddump-mod-map"
2797 (setDumpFlag Opt_D_dump_mod_map)
2798 , make_ord_flag defGhcFlag "ddump-view-pattern-commoning"
2799 (setDumpFlag Opt_D_dump_view_pattern_commoning)
2800 , make_ord_flag defGhcFlag "ddump-to-file"
2801 (NoArg (setGeneralFlag Opt_DumpToFile))
2802 , make_ord_flag defGhcFlag "ddump-hi-diffs"
2803 (setDumpFlag Opt_D_dump_hi_diffs)
2804 , make_ord_flag defGhcFlag "ddump-rtti"
2805 (setDumpFlag Opt_D_dump_rtti)
2806 , make_ord_flag defGhcFlag "dcore-lint"
2807 (NoArg (setGeneralFlag Opt_DoCoreLinting))
2808 , make_ord_flag defGhcFlag "dstg-lint"
2809 (NoArg (setGeneralFlag Opt_DoStgLinting))
2810 , make_ord_flag defGhcFlag "dcmm-lint"
2811 (NoArg (setGeneralFlag Opt_DoCmmLinting))
2812 , make_ord_flag defGhcFlag "dasm-lint"
2813 (NoArg (setGeneralFlag Opt_DoAsmLinting))
2814 , make_ord_flag defGhcFlag "dannot-lint"
2815 (NoArg (setGeneralFlag Opt_DoAnnotationLinting))
2816 , make_ord_flag defGhcFlag "dshow-passes"
2817 (NoArg $ forceRecompile >> (setVerbosity $ Just 2))
2818 , make_ord_flag defGhcFlag "dfaststring-stats"
2819 (NoArg (setGeneralFlag Opt_D_faststring_stats))
2820 , make_ord_flag defGhcFlag "dno-llvm-mangler"
2821 (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag
2822 , make_ord_flag defGhcFlag "ddump-debug" (setDumpFlag Opt_D_dump_debug)
2823
2824 ------ Machine dependant (-m<blah>) stuff ---------------------------
2825
2826 , make_ord_flag defGhcFlag "msse" (noArg (\d ->
2827 d { sseVersion = Just SSE1 }))
2828 , make_ord_flag defGhcFlag "msse2" (noArg (\d ->
2829 d { sseVersion = Just SSE2 }))
2830 , make_ord_flag defGhcFlag "msse3" (noArg (\d ->
2831 d { sseVersion = Just SSE3 }))
2832 , make_ord_flag defGhcFlag "msse4" (noArg (\d ->
2833 d { sseVersion = Just SSE4 }))
2834 , make_ord_flag defGhcFlag "msse4.2" (noArg (\d ->
2835 d { sseVersion = Just SSE42 }))
2836 , make_ord_flag defGhcFlag "mavx" (noArg (\d -> d { avx = True }))
2837 , make_ord_flag defGhcFlag "mavx2" (noArg (\d -> d { avx2 = True }))
2838 , make_ord_flag defGhcFlag "mavx512cd" (noArg (\d ->
2839 d { avx512cd = True }))
2840 , make_ord_flag defGhcFlag "mavx512er" (noArg (\d ->
2841 d { avx512er = True }))
2842 , make_ord_flag defGhcFlag "mavx512f" (noArg (\d -> d { avx512f = True }))
2843 , make_ord_flag defGhcFlag "mavx512pf" (noArg (\d ->
2844 d { avx512pf = True }))
2845
2846 ------ Warning opts -------------------------------------------------
2847 , make_ord_flag defFlag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
2848 , make_ord_flag defFlag "Werror" (NoArg (setGeneralFlag Opt_WarnIsError))
2849 , make_ord_flag defFlag "Wwarn" (NoArg (unSetGeneralFlag Opt_WarnIsError))
2850 , make_dep_flag defFlag "Wnot" (NoArg (upd (\d ->
2851 d {warningFlags = IntSet.empty})))
2852 "Use -w or -Wno-everything instead"
2853 , make_ord_flag defFlag "w" (NoArg (upd (\d ->
2854 d {warningFlags = IntSet.empty})))
2855
2856 -- New-style uniform warning sets
2857 --
2858 -- Note that -Weverything > -Wall > -Wextra > -Wdefault > -Wno-everything
2859 , make_ord_flag defFlag "Weverything" (NoArg (mapM_
2860 setWarningFlag minusWeverythingOpts))
2861 , make_ord_flag defFlag "Wno-everything"
2862 (NoArg (upd (\d -> d {warningFlags = IntSet.empty})))
2863
2864 , make_ord_flag defFlag "Wall" (NoArg (mapM_
2865 setWarningFlag minusWallOpts))
2866 , make_ord_flag defFlag "Wno-all" (NoArg (mapM_
2867 unSetWarningFlag minusWallOpts))
2868
2869 , make_ord_flag defFlag "Wextra" (NoArg (mapM_
2870 setWarningFlag minusWOpts))
2871 , make_ord_flag defFlag "Wno-extra" (NoArg (mapM_
2872 unSetWarningFlag minusWOpts))
2873
2874 , make_ord_flag defFlag "Wdefault" (NoArg (mapM_
2875 setWarningFlag standardWarnings))
2876 , make_ord_flag defFlag "Wno-default" (NoArg (mapM_
2877 unSetWarningFlag standardWarnings))
2878
2879 , make_ord_flag defFlag "Wcompat" (NoArg (mapM_
2880 setWarningFlag minusWcompatOpts))
2881 , make_ord_flag defFlag "Wno-compat" (NoArg (mapM_
2882 unSetWarningFlag minusWcompatOpts))
2883
2884 ------ Plugin flags ------------------------------------------------
2885 , make_ord_flag defGhcFlag "fplugin-opt" (hasArg addPluginModuleNameOption)
2886 , make_ord_flag defGhcFlag "fplugin" (hasArg addPluginModuleName)
2887 , make_ord_flag defGhcFlag "ffrontend-opt" (hasArg addFrontendPluginOption)
2888
2889 ------ Optimisation flags ------------------------------------------
2890 , make_ord_flag defGhcFlag "O" (noArgM (setOptLevel 1))
2891 , make_dep_flag defGhcFlag "Onot" (noArgM $ setOptLevel 0 )
2892 "Use -O0 instead"
2893 , make_ord_flag defGhcFlag "Odph" (noArgM setDPHOpt)
2894 , make_ord_flag defGhcFlag "O" (optIntSuffixM (\mb_n ->
2895 setOptLevel (mb_n `orElse` 1)))
2896 -- If the number is missing, use 1
2897
2898
2899 , make_ord_flag defFlag "fmax-relevant-binds"
2900 (intSuffix (\n d -> d { maxRelevantBinds = Just n }))
2901 , make_ord_flag defFlag "fno-max-relevant-binds"
2902 (noArg (\d -> d { maxRelevantBinds = Nothing }))
2903 , make_ord_flag defFlag "fmax-uncovered-patterns"
2904 (intSuffix (\n d -> d { maxUncoveredPatterns = n }))
2905 , make_ord_flag defFlag "fsimplifier-phases"
2906 (intSuffix (\n d -> d { simplPhases = n }))
2907 , make_ord_flag defFlag "fmax-simplifier-iterations"
2908 (intSuffix (\n d -> d { maxSimplIterations = n }))
2909 , make_ord_flag defFlag "fmax-pmcheck-iterations"
2910 (intSuffix (\n d -> d{ maxPmCheckIterations = n }))
2911 , make_ord_flag defFlag "fsimpl-tick-factor"
2912 (intSuffix (\n d -> d { simplTickFactor = n }))
2913 , make_ord_flag defFlag "fspec-constr-threshold"
2914 (intSuffix (\n d -> d { specConstrThreshold = Just n }))
2915 , make_ord_flag defFlag "fno-spec-constr-threshold"
2916 (noArg (\d -> d { specConstrThreshold = Nothing }))
2917 , make_ord_flag defFlag "fspec-constr-count"
2918 (intSuffix (\n d -> d { specConstrCount = Just n }))
2919 , make_ord_flag defFlag "fno-spec-constr-count"
2920 (noArg (\d -> d { specConstrCount = Nothing }))
2921 , make_ord_flag defFlag "fspec-constr-recursive"
2922 (intSuffix (\n d -> d { specConstrRecursive = n }))
2923 , make_ord_flag defFlag "fliberate-case-threshold"
2924 (intSuffix (\n d -> d { liberateCaseThreshold = Just n }))
2925 , make_ord_flag defFlag "fno-liberate-case-threshold"
2926 (noArg (\d -> d { liberateCaseThreshold = Nothing }))
2927 , make_ord_flag defFlag "frule-check"
2928 (sepArg (\s d -> d { ruleCheck = Just s }))
2929 , make_ord_flag defFlag "freduction-depth"
2930 (intSuffix (\n d -> d { reductionDepth = treatZeroAsInf n }))
2931 , make_ord_flag defFlag "fconstraint-solver-iterations"
2932 (intSuffix (\n d -> d { solverIterations = treatZeroAsInf n }))
2933 , (Deprecated, defFlag "fcontext-stack"
2934 (intSuffixM (\n d ->
2935 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
2936 ; return $ d { reductionDepth = treatZeroAsInf n } })))
2937 , (Deprecated, defFlag "ftype-function-depth"
2938 (intSuffixM (\n d ->
2939 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
2940 ; return $ d { reductionDepth = treatZeroAsInf n } })))
2941 , make_ord_flag defFlag "fstrictness-before"
2942 (intSuffix (\n d -> d { strictnessBefore = n : strictnessBefore d }))
2943 , make_ord_flag defFlag "ffloat-lam-args"
2944 (intSuffix (\n d -> d { floatLamArgs = Just n }))
2945 , make_ord_flag defFlag "ffloat-all-lams"
2946 (noArg (\d -> d { floatLamArgs = Nothing }))
2947 , make_ord_flag defFlag "fhistory-size"
2948 (intSuffix (\n d -> d { historySize = n }))
2949 , make_ord_flag defFlag "funfolding-creation-threshold"
2950 (intSuffix (\n d -> d {ufCreationThreshold = n}))
2951 , make_ord_flag defFlag "funfolding-use-threshold"
2952 (intSuffix (\n d -> d {ufUseThreshold = n}))
2953 , make_ord_flag defFlag "funfolding-fun-discount"
2954 (intSuffix (\n d -> d {ufFunAppDiscount = n}))
2955 , make_ord_flag defFlag "funfolding-dict-discount"
2956 (intSuffix (\n d -> d {ufDictDiscount = n}))
2957 , make_ord_flag defFlag "funfolding-keeness-factor"
2958 (floatSuffix (\n d -> d {ufKeenessFactor = n}))
2959 , make_ord_flag defFlag "fmax-worker-args"
2960 (intSuffix (\n d -> d {maxWorkerArgs = n}))
2961 , make_ord_flag defGhciFlag "fghci-hist-size"
2962 (intSuffix (\n d -> d {ghciHistSize = n}))
2963 , make_ord_flag defGhcFlag "fmax-inline-alloc-size"
2964 (intSuffix (\n d -> d { maxInlineAllocSize = n }))
2965 , make_ord_flag defGhcFlag "fmax-inline-memcpy-insns"
2966 (intSuffix (\n d -> d { maxInlineMemcpyInsns = n }))
2967 , make_ord_flag defGhcFlag "fmax-inline-memset-insns"
2968 (intSuffix (\n d -> d { maxInlineMemsetInsns = n }))
2969 , make_ord_flag defGhcFlag "dinitial-unique"
2970 (intSuffix (\n d -> d { initialUnique = n }))
2971 , make_ord_flag defGhcFlag "dunique-increment"
2972 (intSuffix (\n d -> d { uniqueIncrement = n }))
2973
2974 ------ Profiling ----------------------------------------------------
2975
2976 -- OLD profiling flags
2977 , make_dep_flag defGhcFlag "auto-all"
2978 (noArg (\d -> d { profAuto = ProfAutoAll } ))
2979 "Use -fprof-auto instead"
2980 , make_dep_flag defGhcFlag "no-auto-all"
2981 (noArg (\d -> d { profAuto = NoProfAuto } ))
2982 "Use -fno-prof-auto instead"
2983 , make_dep_flag defGhcFlag "auto"
2984 (noArg (\d -> d { profAuto = ProfAutoExports } ))
2985 "Use -fprof-auto-exported instead"
2986 , make_dep_flag defGhcFlag "no-auto"
2987 (noArg (\d -> d { profAuto = NoProfAuto } ))
2988 "Use -fno-prof-auto instead"
2989 , make_dep_flag defGhcFlag "caf-all"
2990 (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs))
2991 "Use -fprof-cafs instead"
2992 , make_dep_flag defGhcFlag "no-caf-all"
2993 (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs))
2994 "Use -fno-prof-cafs instead"
2995
2996 -- NEW profiling flags
2997 , make_ord_flag defGhcFlag "fprof-auto"
2998 (noArg (\d -> d { profAuto = ProfAutoAll } ))
2999 , make_ord_flag defGhcFlag "fprof-auto-top"
3000 (noArg (\d -> d { profAuto = ProfAutoTop } ))
3001 , make_ord_flag defGhcFlag "fprof-auto-exported"
3002 (noArg (\d -> d { profAuto = ProfAutoExports } ))
3003 , make_ord_flag defGhcFlag "fprof-auto-calls"
3004 (noArg (\d -> d { profAuto = ProfAutoCalls } ))
3005 , make_ord_flag defGhcFlag "fno-prof-auto"
3006 (noArg (\d -> d { profAuto = NoProfAuto } ))
3007
3008 ------ Compiler flags -----------------------------------------------
3009
3010 , make_ord_flag defGhcFlag "fasm" (NoArg (setObjTarget HscAsm))
3011 , make_ord_flag defGhcFlag "fvia-c" (NoArg
3012 (addWarn $ "The -fvia-c flag does nothing; " ++
3013 "it will be removed in a future GHC release"))
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 "fllvm" (NoArg (setObjTarget HscLlvm))
3018
3019 , make_ord_flag defFlag "fno-code" (NoArg ((upd $ \d ->
3020 d { ghcLink=NoLink }) >> setTarget HscNothing))
3021 , make_ord_flag defFlag "fbyte-code" (NoArg (setTarget HscInterpreted))
3022 , make_ord_flag defFlag "fobject-code" (NoArg (setTargetWithPlatform
3023 defaultHscTarget))
3024 , make_dep_flag defFlag "fglasgow-exts"
3025 (NoArg enableGlasgowExts) "Use individual extensions instead"
3026 , make_dep_flag defFlag "fno-glasgow-exts"
3027 (NoArg disableGlasgowExts) "Use individual extensions instead"
3028 , make_ord_flag defFlag "Wunused-binds" (NoArg enableUnusedBinds)
3029 , make_ord_flag defFlag "Wno-unused-binds" (NoArg disableUnusedBinds)
3030 , make_ord_flag defHiddenFlag "fwarn-unused-binds" (NoArg enableUnusedBinds)
3031 , make_ord_flag defHiddenFlag "fno-warn-unused-binds" (NoArg
3032 disableUnusedBinds)
3033
3034 ------ Safe Haskell flags -------------------------------------------
3035 , make_ord_flag defFlag "fpackage-trust" (NoArg setPackageTrust)
3036 , make_ord_flag defFlag "fno-safe-infer" (noArg (\d ->
3037 d { safeInfer = False }))
3038 , make_ord_flag defGhcFlag "fPIC" (NoArg (setGeneralFlag Opt_PIC))
3039 , make_ord_flag defGhcFlag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC))
3040
3041 ------ Debugging flags ----------------------------------------------
3042 , make_ord_flag defGhcFlag "g" (OptIntSuffix setDebugLevel)
3043 ]
3044 ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlagsDeps
3045 ++ map (mkFlag turnOff "no-" unSetGeneralFlag ) negatableFlagsDeps
3046 ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlagsDeps
3047 ++ map (mkFlag turnOff "dno-" unSetGeneralFlag ) dFlagsDeps
3048 ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlagsDeps
3049 ++ map (mkFlag turnOff "fno-" unSetGeneralFlag ) fFlagsDeps
3050 ++ map (mkFlag turnOn "W" setWarningFlag ) wWarningFlagsDeps
3051 ++ map (mkFlag turnOff "Wno-" unSetWarningFlag ) wWarningFlagsDeps
3052 ++ map (mkFlag turnOn "fwarn-" setWarningFlag . hideFlag)
3053 wWarningFlagsDeps
3054 ++ map (mkFlag turnOff "fno-warn-" unSetWarningFlag . hideFlag)
3055 wWarningFlagsDeps
3056 ++ [ (NotDeprecated, unrecognisedWarning "W"),
3057 (Deprecated, unrecognisedWarning "fwarn-"),
3058 (Deprecated, unrecognisedWarning "fno-warn-") ]
3059 ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlagsDeps
3060 ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlagsDeps
3061 ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlagsDeps
3062 ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlagsDeps
3063 ++ map (mkFlag turnOn "X" setLanguage ) languageFlagsDeps
3064 ++ map (mkFlag turnOn "X" setSafeHaskell ) safeHaskellFlagsDeps
3065 ++ [ make_dep_flag defFlag "XGenerics"
3066 (NoArg $ return ())
3067 ("it does nothing; look into -XDefaultSignatures " ++
3068 "and -XDeriveGeneric for generic programming support.")
3069 , make_dep_flag defFlag "XNoGenerics"
3070 (NoArg $ return ())
3071 ("it does nothing; look into -XDefaultSignatures and " ++
3072 "-XDeriveGeneric for generic programming support.") ]
3073
3074 -- | This is where we handle unrecognised warning flags. We only issue a warning
3075 -- if -Wunrecognised-warning-flags is set. See Trac #11429 for context.
3076 unrecognisedWarning :: String -> Flag (CmdLineP DynFlags)
3077 unrecognisedWarning prefix = defHiddenFlag prefix (Prefix action)
3078 where
3079 action :: String -> EwM (CmdLineP DynFlags) ()
3080 action flag = do
3081 f <- wopt Opt_WarnUnrecognisedWarningFlags <$> liftEwM getCmdLineState
3082 when f $ addWarn $ "unrecognised warning flag: -" ++ prefix ++ flag
3083
3084 -- See Note [Supporting CLI completion]
3085 package_flags_deps :: [(Deprecation, Flag (CmdLineP DynFlags))]
3086 package_flags_deps = [
3087 ------- Packages ----------------------------------------------------
3088 make_ord_flag defFlag "package-db"
3089 (HasArg (addPkgConfRef . PkgConfFile))
3090 , make_ord_flag defFlag "clear-package-db" (NoArg clearPkgConf)
3091 , make_ord_flag defFlag "no-global-package-db" (NoArg removeGlobalPkgConf)
3092 , make_ord_flag defFlag "no-user-package-db" (NoArg removeUserPkgConf)
3093 , make_ord_flag defFlag "global-package-db"
3094 (NoArg (addPkgConfRef GlobalPkgConf))
3095 , make_ord_flag defFlag "user-package-db"
3096 (NoArg (addPkgConfRef UserPkgConf))
3097 -- backwards compat with GHC<=7.4 :
3098 , make_dep_flag defFlag "package-conf"
3099 (HasArg $ addPkgConfRef . PkgConfFile) "Use -package-db instead"
3100 , make_dep_flag defFlag "no-user-package-conf"
3101 (NoArg removeUserPkgConf) "Use -no-user-package-db instead"
3102 , make_ord_flag defGhcFlag "package-name" (HasArg $ \name -> do
3103 upd (setUnitId name))
3104 -- TODO: Since we JUST deprecated
3105 -- -this-package-key, let's keep this
3106 -- undeprecated for another cycle.
3107 -- Deprecate this eventually.
3108 -- deprecate "Use -this-unit-id instead")
3109 , make_dep_flag defGhcFlag "this-package-key" (HasArg $ upd . setUnitId)
3110 "Use -this-unit-id instead"
3111 , make_ord_flag defGhcFlag "this-unit-id" (hasArg setUnitId)
3112 , make_ord_flag defFlag "package" (HasArg exposePackage)
3113 , make_ord_flag defFlag "plugin-package-id" (HasArg exposePluginPackageId)
3114 , make_ord_flag defFlag "plugin-package" (HasArg exposePluginPackage)
3115 , make_ord_flag defFlag "package-id" (HasArg exposePackageId)
3116 , make_ord_flag defFlag "hide-package" (HasArg hidePackage)
3117 , make_ord_flag defFlag "hide-all-packages"
3118 (NoArg (setGeneralFlag Opt_HideAllPackages))
3119 , make_ord_flag defFlag "hide-all-plugin-packages"
3120 (NoArg (setGeneralFlag Opt_HideAllPluginPackages))
3121 , make_ord_flag defFlag "package-env" (HasArg setPackageEnv)
3122 , make_ord_flag defFlag "ignore-package" (HasArg ignorePackage)
3123 , make_dep_flag defFlag "syslib" (HasArg exposePackage) "Use -package instead"
3124 , make_ord_flag defFlag "distrust-all-packages"
3125 (NoArg (setGeneralFlag Opt_DistrustAllPackages))
3126 , make_ord_flag defFlag "trust" (HasArg trustPackage)
3127 , make_ord_flag defFlag "distrust" (HasArg distrustPackage)
3128 ]
3129 where
3130 setPackageEnv env = upd $ \s -> s { packageEnv = Just env }
3131
3132 -- | Make a list of flags for shell completion.
3133 -- Filter all available flags into two groups, for interactive GHC vs all other.
3134 flagsForCompletion :: Bool -> [String]
3135 flagsForCompletion isInteractive
3136 = [ '-':flagName flag
3137 | flag <- flagsAll
3138 , modeFilter (flagGhcMode flag)
3139 ]
3140 where
3141 modeFilter AllModes = True
3142 modeFilter OnlyGhci = isInteractive
3143 modeFilter OnlyGhc = not isInteractive
3144 modeFilter HiddenFlag = False
3145
3146 type TurnOnFlag = Bool -- True <=> we are turning the flag on
3147 -- False <=> we are turning the flag off
3148 turnOn :: TurnOnFlag; turnOn = True
3149 turnOff :: TurnOnFlag; turnOff = False
3150
3151 data FlagSpec flag
3152 = FlagSpec
3153 { flagSpecName :: String -- ^ Flag in string form
3154 , flagSpecFlag :: flag -- ^ Flag in internal form
3155 , flagSpecAction :: (TurnOnFlag -> DynP ())
3156 -- ^ Extra action to run when the flag is found
3157 -- Typically, emit a warning or error
3158 , flagSpecGhcMode :: GhcFlagMode
3159 -- ^ In which ghc mode the flag has effect
3160 }
3161
3162 -- | Define a new flag.
3163 flagSpec :: String -> flag -> (Deprecation, FlagSpec flag)
3164 flagSpec name flag = flagSpec' name flag nop
3165
3166 -- | Define a new flag with an effect.
3167 flagSpec' :: String -> flag -> (TurnOnFlag -> DynP ())
3168 -> (Deprecation, FlagSpec flag)
3169 flagSpec' name flag act = (NotDeprecated, FlagSpec name flag act AllModes)
3170
3171 -- | Define a new deprecated flag with an effect.
3172 depFlagSpecOp :: String -> flag -> (TurnOnFlag -> DynP ()) -> String
3173 -> (Deprecation, FlagSpec flag)
3174 depFlagSpecOp name flag act dep =
3175 (Deprecated, snd (flagSpec' name flag (\f -> act f >> deprecate dep)))
3176
3177 -- | Define a new deprecated flag.
3178 depFlagSpec :: String -> flag -> String
3179 -> (Deprecation, FlagSpec flag)
3180 depFlagSpec name flag dep = depFlagSpecOp name flag nop dep
3181
3182 -- | Define a new deprecated flag with an effect where the deprecation message
3183 -- depends on the flag value
3184 depFlagSpecOp' :: String
3185 -> flag
3186 -> (TurnOnFlag -> DynP ())
3187 -> (TurnOnFlag -> String)
3188 -> (Deprecation, FlagSpec flag)
3189 depFlagSpecOp' name flag act dep =
3190 (Deprecated, FlagSpec name flag (\f -> act f >> (deprecate $ dep f))
3191 AllModes)
3192
3193 -- | Define a new deprecated flag where the deprecation message
3194 -- depends on the flag value
3195 depFlagSpec' :: String
3196 -> flag
3197 -> (TurnOnFlag -> String)
3198 -> (Deprecation, FlagSpec flag)
3199 depFlagSpec' name flag dep = depFlagSpecOp' name flag nop dep
3200
3201
3202 -- | Define a new deprecated flag where the deprecation message
3203 -- is shown depending on the flag value
3204 depFlagSpecCond :: String
3205 -> flag
3206 -> (TurnOnFlag -> Bool)
3207 -> String
3208 -> (Deprecation, FlagSpec flag)
3209 depFlagSpecCond name flag cond dep =
3210 (Deprecated, FlagSpec name flag (\f -> when (cond f) $ deprecate dep)
3211 AllModes)
3212
3213 -- | Define a new flag for GHCi.
3214 flagGhciSpec :: String -> flag -> (Deprecation, FlagSpec flag)
3215 flagGhciSpec name flag = flagGhciSpec' name flag nop
3216
3217 -- | Define a new flag for GHCi with an effect.
3218 flagGhciSpec' :: String -> flag -> (TurnOnFlag -> DynP ())
3219 -> (Deprecation, FlagSpec flag)
3220 flagGhciSpec' name flag act = (NotDeprecated, FlagSpec name flag act OnlyGhci)
3221
3222 -- | Define a new flag invisible to CLI completion.
3223 flagHiddenSpec :: String -> flag -> (Deprecation, FlagSpec flag)
3224 flagHiddenSpec name flag = flagHiddenSpec' name flag nop
3225
3226 -- | Define a new flag invisible to CLI completion with an effect.
3227 flagHiddenSpec' :: String -> flag -> (TurnOnFlag -> DynP ())
3228 -> (Deprecation, FlagSpec flag)
3229 flagHiddenSpec' name flag act = (NotDeprecated, FlagSpec name flag act
3230 HiddenFlag)
3231
3232 -- | Hide a 'FlagSpec' from being displayed in @--show-options@.
3233 --
3234 -- This is for example useful for flags that are obsolete, but should not
3235 -- (yet) be deprecated for compatibility reasons.
3236 hideFlag :: (Deprecation, FlagSpec a) -> (Deprecation, FlagSpec a)
3237 hideFlag (dep, fs) = (dep, fs { flagSpecGhcMode = HiddenFlag })
3238
3239 mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on
3240 -> String -- ^ The flag prefix
3241 -> (flag -> DynP ()) -- ^ What to do when the flag is found
3242 -> (Deprecation, FlagSpec flag) -- ^ Specification of
3243 -- this particular flag
3244 -> (Deprecation, Flag (CmdLineP DynFlags))
3245 mkFlag turn_on flagPrefix f (dep, (FlagSpec name flag extra_action mode))
3246 = (dep,
3247 Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on)) mode)
3248
3249 deprecatedForExtension :: String -> TurnOnFlag -> String
3250 deprecatedForExtension lang turn_on
3251 = "use -X" ++ flag ++
3252 " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead"
3253 where
3254 flag | turn_on = lang
3255 | otherwise = "No" ++ lang
3256
3257 useInstead :: String -> TurnOnFlag -> String
3258 useInstead flag turn_on
3259 = "Use -f" ++ no ++ flag ++ " instead"
3260 where
3261 no = if turn_on then "" else "no-"
3262
3263 nop :: TurnOnFlag -> DynP ()
3264 nop _ = return ()
3265
3266 -- | Find the 'FlagSpec' for a 'WarningFlag'.
3267 flagSpecOf :: WarningFlag -> Maybe (FlagSpec WarningFlag)
3268 flagSpecOf flag = listToMaybe $ filter check wWarningFlags
3269 where
3270 check fs = flagSpecFlag fs == flag
3271
3272 -- | These @-W\<blah\>@ flags can all be reversed with @-Wno-\<blah\>@
3273 wWarningFlags :: [FlagSpec WarningFlag]
3274 wWarningFlags = map snd (sortBy (comparing fst) wWarningFlagsDeps)
3275
3276 wWarningFlagsDeps :: [(Deprecation, FlagSpec WarningFlag)]
3277 wWarningFlagsDeps = [
3278 -- See Note [Updating flag description in the User's Guide]
3279 -- See Note [Supporting CLI completion]
3280 -- Please keep the list of flags below sorted alphabetically
3281 flagSpec "alternative-layout-rule-transitional"
3282 Opt_WarnAlternativeLayoutRuleTransitional,
3283 depFlagSpec "amp" Opt_WarnAMP
3284 "it has no effect",
3285 depFlagSpec "auto-orphans" Opt_WarnAutoOrphans
3286 "it has no effect",
3287 flagSpec "cpp-undef" Opt_WarnCPPUndef,
3288 flagSpec "deferred-type-errors" Opt_WarnDeferredTypeErrors,
3289 flagSpec "deferred-out-of-scope-variables"
3290 Opt_WarnDeferredOutOfScopeVariables,
3291 flagSpec "deprecations" Opt_WarnWarningsDeprecations,
3292 flagSpec "deprecated-flags" Opt_WarnDeprecatedFlags,
3293 flagSpec "deriving-typeable" Opt_WarnDerivingTypeable,
3294 flagSpec "dodgy-exports" Opt_WarnDodgyExports,
3295 flagSpec "dodgy-foreign-imports" Opt_WarnDodgyForeignImports,
3296 flagSpec "dodgy-imports" Opt_WarnDodgyImports,
3297 flagSpec "empty-enumerations" Opt_WarnEmptyEnumerations,
3298 depFlagSpec "context-quantification" Opt_WarnContextQuantification
3299 "it is subsumed by an error message that cannot be disabled",
3300 depFlagSpec "duplicate-constraints" Opt_WarnDuplicateConstraints
3301 "it is subsumed by -Wredundant-constraints",
3302 flagSpec "redundant-constraints" Opt_WarnRedundantConstraints,
3303 flagSpec "duplicate-exports" Opt_WarnDuplicateExports,
3304 flagSpec "hi-shadowing" Opt_WarnHiShadows,
3305 flagSpec "implicit-prelude" Opt_WarnImplicitPrelude,
3306 flagSpec "incomplete-patterns" Opt_WarnIncompletePatterns,
3307 flagSpec "incomplete-record-updates" Opt_WarnIncompletePatternsRecUpd,
3308 flagSpec "incomplete-uni-patterns" Opt_WarnIncompleteUniPatterns,
3309 flagSpec "inline-rule-shadowing" Opt_WarnInlineRuleShadowing,
3310 flagSpec "identities" Opt_WarnIdentities,
3311 flagSpec "missing-fields" Opt_WarnMissingFields,
3312 flagSpec "missing-import-lists" Opt_WarnMissingImportList,
3313 depFlagSpec "missing-local-sigs" Opt_WarnMissingLocalSignatures
3314 "it is replaced by -Wmissing-local-signatures",
3315 flagSpec "missing-local-signatures" Opt_WarnMissingLocalSignatures,
3316 flagSpec "missing-methods" Opt_WarnMissingMethods,
3317 flagSpec "missing-monadfail-instances" Opt_WarnMissingMonadFailInstances,
3318 flagSpec "semigroup" Opt_WarnSemigroup,
3319 flagSpec "missing-signatures" Opt_WarnMissingSignatures,
3320 depFlagSpec "missing-exported-sigs" Opt_WarnMissingExportedSignatures
3321 "it is replaced by -Wmissing-exported-signatures",
3322 flagSpec "missing-exported-signatures" Opt_WarnMissingExportedSignatures,
3323 flagSpec "monomorphism-restriction" Opt_WarnMonomorphism,
3324 flagSpec "name-shadowing" Opt_WarnNameShadowing,
3325 flagSpec "noncanonical-monad-instances"
3326 Opt_WarnNonCanonicalMonadInstances,
3327 flagSpec "noncanonical-monadfail-instances"
3328 Opt_WarnNonCanonicalMonadFailInstances,
3329 flagSpec "noncanonical-monoid-instances"
3330 Opt_WarnNonCanonicalMonoidInstances,
3331 flagSpec "orphans" Opt_WarnOrphans,
3332 flagSpec "overflowed-literals" Opt_WarnOverflowedLiterals,
3333 flagSpec "overlapping-patterns" Opt_WarnOverlappingPatterns,
3334 flagSpec "missed-specialisations" Opt_WarnMissedSpecs,
3335 flagSpec "missed-specializations" Opt_WarnMissedSpecs,
3336 flagSpec "all-missed-specialisations" Opt_WarnAllMissedSpecs,
3337 flagSpec "all-missed-specializations" Opt_WarnAllMissedSpecs,
3338 flagSpec' "safe" Opt_WarnSafe setWarnSafe,
3339 flagSpec "trustworthy-safe" Opt_WarnTrustworthySafe,
3340 flagSpec "tabs" Opt_WarnTabs,
3341 flagSpec "type-defaults" Opt_WarnTypeDefaults,
3342 flagSpec "typed-holes" Opt_WarnTypedHoles,
3343 flagSpec "partial-type-signatures" Opt_WarnPartialTypeSignatures,
3344 flagSpec "unrecognised-pragmas" Opt_WarnUnrecognisedPragmas,
3345 flagSpec' "unsafe" Opt_WarnUnsafe setWarnUnsafe,
3346 flagSpec "unsupported-calling-conventions"
3347 Opt_WarnUnsupportedCallingConventions,
3348 flagSpec "unsupported-llvm-version" Opt_WarnUnsupportedLlvmVersion,
3349 flagSpec "unticked-promoted-constructors"
3350 Opt_WarnUntickedPromotedConstructors,
3351 flagSpec "unused-do-bind" Opt_WarnUnusedDoBind,
3352 flagSpec "unused-foralls" Opt_WarnUnusedForalls,
3353 flagSpec "unused-imports" Opt_WarnUnusedImports,
3354 flagSpec "unused-local-binds" Opt_WarnUnusedLocalBinds,
3355 flagSpec "unused-matches" Opt_WarnUnusedMatches,
3356 flagSpec "unused-pattern-binds" Opt_WarnUnusedPatternBinds,
3357 flagSpec "unused-top-binds" Opt_WarnUnusedTopBinds,
3358 flagSpec "unused-type-patterns" Opt_WarnUnusedTypePatterns,
3359 flagSpec "warnings-deprecations" Opt_WarnWarningsDeprecations,
3360 flagSpec "wrong-do-bind" Opt_WarnWrongDoBind,
3361 flagSpec "missing-pattern-synonym-signatures"
3362 Opt_WarnMissingPatternSynonymSignatures,
3363 flagSpec "simplifiable-class-constraints" Opt_WarnSimplifiableClassConstraints,
3364 flagSpec "unrecognised-warning-flags" Opt_WarnUnrecognisedWarningFlags ]
3365
3366 -- | These @-\<blah\>@ flags can all be reversed with @-no-\<blah\>@
3367 negatableFlagsDeps :: [(Deprecation, FlagSpec GeneralFlag)]
3368 negatableFlagsDeps = [
3369 flagGhciSpec "ignore-dot-ghci" Opt_IgnoreDotGhci ]
3370
3371 -- | These @-d\<blah\>@ flags can all be reversed with @-dno-\<blah\>@
3372 dFlagsDeps :: [(Deprecation, FlagSpec GeneralFlag)]
3373 dFlagsDeps = [
3374 -- See Note [Updating flag description in the User's Guide]
3375 -- See Note [Supporting CLI completion]
3376 -- Please keep the list of flags below sorted alphabetically
3377 flagSpec "ppr-case-as-let" Opt_PprCaseAsLet,
3378 flagSpec "ppr-ticks" Opt_PprShowTicks,
3379 flagSpec "suppress-coercions" Opt_SuppressCoercions,
3380 flagSpec "suppress-idinfo" Opt_SuppressIdInfo,
3381 flagSpec "suppress-unfoldings" Opt_SuppressUnfoldings,
3382 flagSpec "suppress-module-prefixes" Opt_SuppressModulePrefixes,
3383 flagSpec "suppress-type-applications" Opt_SuppressTypeApplications,
3384 flagSpec "suppress-type-signatures" Opt_SuppressTypeSignatures,
3385 flagSpec "suppress-uniques" Opt_SuppressUniques,
3386 flagSpec "suppress-var-kinds" Opt_SuppressVarKinds]
3387
3388 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
3389 fFlags :: [FlagSpec GeneralFlag]
3390 fFlags = map snd fFlagsDeps
3391
3392 fFlagsDeps :: [(Deprecation, FlagSpec GeneralFlag)]
3393 fFlagsDeps = [
3394 -- See Note [Updating flag description in the User's Guide]
3395 -- See Note [Supporting CLI completion]
3396 -- Please keep the list of flags below sorted alphabetically
3397 flagGhciSpec "break-on-error" Opt_BreakOnError,
3398 flagGhciSpec "break-on-exception" Opt_BreakOnException,
3399 flagSpec "building-cabal-package" Opt_BuildingCabalPackage,
3400 flagSpec "call-arity" Opt_CallArity,
3401 flagSpec "case-merge" Opt_CaseMerge,
3402 flagSpec "cmm-elim-common-blocks" Opt_CmmElimCommonBlocks,
3403 flagSpec "cmm-sink" Opt_CmmSink,
3404 flagSpec "cse" Opt_CSE,
3405 flagSpec "cpr-anal" Opt_CprAnal,
3406 flagSpec "defer-type-errors" Opt_DeferTypeErrors,
3407 flagSpec "defer-typed-holes" Opt_DeferTypedHoles,
3408 flagSpec "defer-out-of-scope-variables" Opt_DeferOutOfScopeVariables,
3409 flagSpec "dicts-cheap" Opt_DictsCheap,
3410 flagSpec "dicts-strict" Opt_DictsStrict,
3411 flagSpec "dmd-tx-dict-sel" Opt_DmdTxDictSel,
3412 flagSpec "do-eta-reduction" Opt_DoEtaReduction,
3413 flagSpec "do-lambda-eta-expansion" Opt_DoLambdaEtaExpansion,
3414 flagSpec "eager-blackholing" Opt_EagerBlackHoling,
3415 flagSpec "embed-manifest" Opt_EmbedManifest,
3416 flagSpec "enable-rewrite-rules" Opt_EnableRewriteRules,
3417 flagSpec "error-spans" Opt_ErrorSpans,
3418 flagSpec "excess-precision" Opt_ExcessPrecision,
3419 flagSpec "expose-all-unfoldings" Opt_ExposeAllUnfoldings,
3420 flagSpec "external-interpreter" Opt_ExternalInterpreter,
3421 flagSpec "flat-cache" Opt_FlatCache,
3422 flagSpec "float-in" Opt_FloatIn,
3423 flagSpec "force-recomp" Opt_ForceRecomp,
3424 flagSpec "full-laziness" Opt_FullLaziness,
3425 flagSpec "fun-to-thunk" Opt_FunToThunk,
3426 flagSpec "gen-manifest" Opt_GenManifest,
3427 flagSpec "ghci-history" Opt_GhciHistory,
3428 flagGhciSpec "local-ghci-history" Opt_LocalGhciHistory,
3429 flagSpec "ghci-sandbox" Opt_GhciSandbox,
3430 flagSpec "helpful-errors" Opt_HelpfulErrors,
3431 flagSpec "hpc" Opt_Hpc,
3432 flagSpec "ignore-asserts" Opt_IgnoreAsserts,
3433 flagSpec "ignore-interface-pragmas" Opt_IgnoreInterfacePragmas,
3434 flagGhciSpec "implicit-import-qualified" Opt_ImplicitImportQualified,
3435 flagSpec "irrefutable-tuples" Opt_IrrefutableTuples,
3436 flagSpec "kill-absence" Opt_KillAbsence,
3437 flagSpec "kill-one-shot" Opt_KillOneShot,
3438 flagSpec "late-dmd-anal" Opt_LateDmdAnal,
3439 flagSpec "liberate-case" Opt_LiberateCase,
3440 flagHiddenSpec "llvm-pass-vectors-in-regs" Opt_LlvmPassVectorsInRegisters,
3441 flagHiddenSpec "llvm-tbaa" Opt_LlvmTBAA,
3442 flagHiddenSpec "llvm-fill-undef-with-garbage" Opt_LlvmFillUndefWithGarbage,
3443 flagSpec "loopification" Opt_Loopification,
3444 flagSpec "omit-interface-pragmas" Opt_OmitInterfacePragmas,
3445 flagSpec "omit-yields" Opt_OmitYields,
3446 flagSpec "optimal-applicative-do" Opt_OptimalApplicativeDo,
3447 flagSpec "pedantic-bottoms" Opt_PedanticBottoms,
3448 flagSpec "pre-inlining" Opt_SimplPreInlining,
3449 flagGhciSpec "print-bind-contents" Opt_PrintBindContents,
3450 flagGhciSpec "print-bind-result" Opt_PrintBindResult,
3451 flagGhciSpec "print-evld-with-show" Opt_PrintEvldWithShow,
3452 flagSpec "print-explicit-foralls" Opt_PrintExplicitForalls,
3453 flagSpec "print-explicit-kinds" Opt_PrintExplicitKinds,
3454 flagSpec "print-explicit-coercions" Opt_PrintExplicitCoercions,
3455 flagSpec "print-explicit-runtime-reps" Opt_PrintExplicitRuntimeReps,
3456 flagSpec "print-equality-relations" Opt_PrintEqualityRelations,
3457 flagSpec "print-unicode-syntax" Opt_PrintUnicodeSyntax,
3458 flagSpec "print-expanded-synonyms" Opt_PrintExpandedSynonyms,
3459 flagSpec "print-potential-instances" Opt_PrintPotentialInstances,
3460 flagSpec "print-typechecker-elaboration" Opt_PrintTypecheckerElaboration,
3461 flagSpec "prof-cafs" Opt_AutoSccsOnIndividualCafs,
3462 flagSpec "prof-count-entries" Opt_ProfCountEntries,
3463 flagSpec "regs-graph" Opt_RegsGraph,
3464 flagSpec "regs-iterative" Opt_RegsIterative,
3465 depFlagSpec' "rewrite-rules" Opt_EnableRewriteRules
3466 (useInstead "enable-rewrite-rules"),
3467 flagSpec "shared-implib" Opt_SharedImplib,
3468 flagSpec "spec-constr" Opt_SpecConstr,
3469 flagSpec "specialise" Opt_Specialise,
3470 flagSpec "specialize" Opt_Specialise,
3471 flagSpec "specialise-aggressively" Opt_SpecialiseAggressively,
3472 flagSpec "specialize-aggressively" Opt_SpecialiseAggressively,
3473 flagSpec "cross-module-specialise" Opt_CrossModuleSpecialise,
3474 flagSpec "cross-module-specialize" Opt_CrossModuleSpecialise,
3475 flagSpec "static-argument-transformation" Opt_StaticArgumentTransformation,
3476 flagSpec "strictness" Opt_Strictness,
3477 flagSpec "use-rpaths" Opt_RPath,
3478 flagSpec "write-interface" Opt_WriteInterface,
3479 flagSpec "unbox-small-strict-fields" Opt_UnboxSmallStrictFields,
3480 flagSpec "unbox-strict-fields" Opt_UnboxStrictFields,
3481 flagSpec "vectorisation-avoidance" Opt_VectorisationAvoidance,
3482 flagSpec "vectorise" Opt_Vectorise,
3483 flagSpec "version-macros" Opt_VersionMacros,
3484 flagSpec "worker-wrapper" Opt_WorkerWrapper,
3485 flagSpec "show-warning-groups" Opt_ShowWarnGroups
3486 ]
3487
3488 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
3489 fLangFlags :: [FlagSpec LangExt.Extension]
3490 fLangFlags = map snd fLangFlagsDeps
3491
3492 fLangFlagsDeps :: [(Deprecation, FlagSpec LangExt.Extension)]
3493 fLangFlagsDeps = [
3494 -- See Note [Updating flag description in the User's Guide]
3495 -- See Note [Supporting CLI completion]
3496 depFlagSpecOp' "th" LangExt.TemplateHaskell
3497 checkTemplateHaskellOk
3498 (deprecatedForExtension "TemplateHaskell"),
3499 depFlagSpec' "fi" LangExt.ForeignFunctionInterface
3500 (deprecatedForExtension "ForeignFunctionInterface"),
3501 depFlagSpec' "ffi" LangExt.ForeignFunctionInterface
3502 (deprecatedForExtension "ForeignFunctionInterface"),
3503 depFlagSpec' "arrows" LangExt.Arrows
3504 (deprecatedForExtension "Arrows"),
3505 depFlagSpec' "implicit-prelude" LangExt.ImplicitPrelude
3506 (deprecatedForExtension "ImplicitPrelude"),
3507 depFlagSpec' "bang-patterns" LangExt.BangPatterns
3508 (deprecatedForExtension "BangPatterns"),
3509 depFlagSpec' "monomorphism-restriction" LangExt.MonomorphismRestriction
3510 (deprecatedForExtension "MonomorphismRestriction"),
3511 depFlagSpec' "mono-pat-binds" LangExt.MonoPatBinds
3512 (deprecatedForExtension "MonoPatBinds"),
3513 depFlagSpec' "extended-default-rules" LangExt.ExtendedDefaultRules
3514 (deprecatedForExtension "ExtendedDefaultRules"),
3515 depFlagSpec' "implicit-params" LangExt.ImplicitParams
3516 (deprecatedForExtension "ImplicitParams"),
3517 depFlagSpec' "scoped-type-variables" LangExt.ScopedTypeVariables
3518 (deprecatedForExtension "ScopedTypeVariables"),
3519 depFlagSpec' "parr" LangExt.ParallelArrays
3520 (deprecatedForExtension "ParallelArrays"),
3521 depFlagSpec' "PArr" LangExt.ParallelArrays
3522 (deprecatedForExtension "ParallelArrays"),
3523 depFlagSpec' "allow-overlapping-instances" LangExt.OverlappingInstances
3524 (deprecatedForExtension "OverlappingInstances"),
3525 depFlagSpec' "allow-undecidable-instances" LangExt.UndecidableInstances
3526 (deprecatedForExtension "UndecidableInstances"),
3527 depFlagSpec' "allow-incoherent-instances" LangExt.IncoherentInstances
3528 (deprecatedForExtension "IncoherentInstances")
3529 ]
3530
3531 supportedLanguages :: [String]
3532 supportedLanguages = map (flagSpecName . snd) languageFlagsDeps
3533
3534 supportedLanguageOverlays :: [String]
3535 supportedLanguageOverlays = map (flagSpecName . snd) safeHaskellFlagsDeps
3536
3537 supportedExtensions :: [String]
3538 supportedExtensions = concatMap toFlagSpecNamePair xFlags
3539 where
3540 toFlagSpecNamePair flg
3541 #ifndef GHCI
3542 -- make sure that `ghc --supported-extensions` omits
3543 -- "TemplateHaskell" when it's known to be unsupported. See also
3544 -- GHC #11102 for rationale
3545 | flagSpecFlag flg == LangExt.TemplateHaskell = [noName]
3546 #endif
3547 | otherwise = [name, noName]
3548 where
3549 noName = "No" ++ name
3550 name = flagSpecName flg
3551
3552 supportedLanguagesAndExtensions :: [String]
3553 supportedLanguagesAndExtensions =
3554 supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions
3555
3556 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
3557 languageFlagsDeps :: [(Deprecation, FlagSpec Language)]
3558 languageFlagsDeps = [
3559 flagSpec "Haskell98" Haskell98,
3560 flagSpec "Haskell2010" Haskell2010
3561 ]
3562
3563 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
3564 -- They are used to place hard requirements on what GHC Haskell language
3565 -- features can be used.
3566 safeHaskellFlagsDeps :: [(Deprecation, FlagSpec SafeHaskellMode)]
3567 safeHaskellFlagsDeps = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe]
3568 where mkF flag = flagSpec (show flag) flag
3569
3570 -- | These -X<blah> flags can all be reversed with -XNo<blah>
3571 xFlags :: [FlagSpec LangExt.Extension]
3572 xFlags = map snd xFlagsDeps
3573
3574 xFlagsDeps :: [(Deprecation, FlagSpec LangExt.Extension)]
3575 xFlagsDeps = [
3576 -- See Note [Updating flag description in the User's Guide]
3577 -- See Note [Supporting CLI completion]
3578 -- See Note [Adding a language extension]
3579 -- Please keep the list of flags below sorted alphabetically
3580 flagSpec "AllowAmbiguousTypes" LangExt.AllowAmbiguousTypes,
3581 flagSpec "AlternativeLayoutRule" LangExt.AlternativeLayoutRule,
3582 flagSpec "AlternativeLayoutRuleTransitional"
3583 LangExt.AlternativeLayoutRuleTransitional,
3584 flagSpec "Arrows" LangExt.Arrows,
3585 flagSpec "AutoDeriveTypeable" LangExt.AutoDeriveTypeable,
3586 flagSpec "BangPatterns" LangExt.BangPatterns,
3587 flagSpec "BinaryLiterals" LangExt.BinaryLiterals,
3588 flagSpec "CApiFFI" LangExt.CApiFFI,
3589 flagSpec "CPP" LangExt.Cpp,
3590 flagSpec "ConstrainedClassMethods" LangExt.ConstrainedClassMethods,
3591 flagSpec "ConstraintKinds" LangExt.ConstraintKinds,
3592 flagSpec "DataKinds" LangExt.DataKinds,
3593 depFlagSpecCond "DatatypeContexts" LangExt.DatatypeContexts
3594 id
3595 ("It was widely considered a misfeature, " ++
3596 "and has been removed from the Haskell language."),
3597 flagSpec "DefaultSignatures" LangExt.DefaultSignatures,
3598 flagSpec "DeriveAnyClass" LangExt.DeriveAnyClass,
3599 flagSpec "DeriveDataTypeable" LangExt.DeriveDataTypeable,
3600 flagSpec "DeriveFoldable" LangExt.DeriveFoldable,
3601 flagSpec "DeriveFunctor" LangExt.DeriveFunctor,
3602 flagSpec "DeriveGeneric" LangExt.DeriveGeneric,
3603 flagSpec "DeriveLift" LangExt.DeriveLift,
3604 flagSpec "DeriveTraversable" LangExt.DeriveTraversable,
3605 flagSpec "DerivingStrategies" LangExt.DerivingStrategies,
3606 flagSpec "DisambiguateRecordFields" LangExt.DisambiguateRecordFields,
3607 flagSpec "DoAndIfThenElse" LangExt.DoAndIfThenElse,
3608 depFlagSpec' "DoRec" LangExt.RecursiveDo
3609 (deprecatedForExtension "RecursiveDo"),
3610 flagSpec "DuplicateRecordFields" LangExt.DuplicateRecordFields,
3611 flagSpec "EmptyCase" LangExt.EmptyCase,
3612 flagSpec "EmptyDataDecls" LangExt.EmptyDataDecls,
3613 flagSpec "ExistentialQuantification" LangExt.ExistentialQuantification,
3614 flagSpec "ExplicitForAll" LangExt.ExplicitForAll,
3615 flagSpec "ExplicitNamespaces" LangExt.ExplicitNamespaces,
3616 flagSpec "ExtendedDefaultRules" LangExt.ExtendedDefaultRules,
3617 flagSpec "FlexibleContexts" LangExt.FlexibleContexts,
3618 flagSpec "FlexibleInstances" LangExt.FlexibleInstances,
3619 flagSpec "ForeignFunctionInterface" LangExt.ForeignFunctionInterface,
3620 flagSpec "FunctionalDependencies" LangExt.FunctionalDependencies,
3621 flagSpec "GADTSyntax" LangExt.GADTSyntax,
3622 flagSpec "GADTs" LangExt.GADTs,
3623 flagSpec "GHCForeignImportPrim" LangExt.GHCForeignImportPrim,
3624 flagSpec' "GeneralizedNewtypeDeriving" LangExt.GeneralizedNewtypeDeriving
3625 setGenDeriving,
3626 flagSpec "ImplicitParams" LangExt.ImplicitParams,
3627 flagSpec "ImplicitPrelude" LangExt.ImplicitPrelude,
3628 flagSpec "ImpredicativeTypes" LangExt.ImpredicativeTypes,
3629 flagSpec' "IncoherentInstances" LangExt.IncoherentInstances
3630 setIncoherentInsts,
3631 flagSpec "TypeFamilyDependencies" LangExt.TypeFamilyDependencies,
3632 flagSpec "InstanceSigs" LangExt.InstanceSigs,
3633 flagSpec "ApplicativeDo" LangExt.ApplicativeDo,
3634 flagSpec "InterruptibleFFI" LangExt.InterruptibleFFI,
3635 flagSpec "JavaScriptFFI" LangExt.JavaScriptFFI,
3636 flagSpec "KindSignatures" LangExt.KindSignatures,
3637 flagSpec "LambdaCase" LangExt.LambdaCase,
3638 flagSpec "LiberalTypeSynonyms" LangExt.LiberalTypeSynonyms,
3639 flagSpec "MagicHash" LangExt.MagicHash,
3640 flagSpec "MonadComprehensions" LangExt.MonadComprehensions,
3641 flagSpec "MonadFailDesugaring" LangExt.MonadFailDesugaring,
3642 flagSpec "MonoLocalBinds" LangExt.MonoLocalBinds,
3643 depFlagSpecCond "MonoPatBinds" LangExt.MonoPatBinds
3644 id
3645 "Experimental feature now removed; has no effect",
3646 flagSpec "MonomorphismRestriction" LangExt.MonomorphismRestriction,
3647 flagSpec "MultiParamTypeClasses" LangExt.MultiParamTypeClasses,
3648 flagSpec "MultiWayIf" LangExt.MultiWayIf,
3649 flagSpec "NPlusKPatterns" LangExt.NPlusKPatterns,
3650 flagSpec "NamedFieldPuns" LangExt.RecordPuns,
3651 flagSpec "NamedWildCards" LangExt.NamedWildCards,
3652 flagSpec "NegativeLiterals" LangExt.NegativeLiterals,
3653 flagSpec "NondecreasingIndentation" LangExt.NondecreasingIndentation,
3654 depFlagSpec' "NullaryTypeClasses" LangExt.NullaryTypeClasses
3655 (deprecatedForExtension "MultiParamTypeClasses"),
3656 flagSpec "NumDecimals" LangExt.NumDecimals,
3657 depFlagSpecOp "OverlappingInstances" LangExt.OverlappingInstances
3658 setOverlappingInsts
3659 "instead use per-instance pragmas OVERLAPPING/OVERLAPPABLE/OVERLAPS",
3660 flagSpec "OverloadedLabels" LangExt.OverloadedLabels,
3661 flagSpec "OverloadedLists" LangExt.OverloadedLists,
3662 flagSpec "OverloadedStrings" LangExt.OverloadedStrings,
3663 flagSpec "PackageImports" LangExt.PackageImports,
3664 flagSpec "ParallelArrays" LangExt.ParallelArrays,
3665 flagSpec "ParallelListComp" LangExt.ParallelListComp,
3666 flagSpec "PartialTypeSignatures" LangExt.PartialTypeSignatures,
3667 flagSpec "PatternGuards" LangExt.PatternGuards,
3668 depFlagSpec' "PatternSignatures" LangExt.ScopedTypeVariables
3669 (deprecatedForExtension "ScopedTypeVariables"),
3670 flagSpec "PatternSynonyms" LangExt.PatternSynonyms,
3671 flagSpec "PolyKinds" LangExt.PolyKinds,
3672 flagSpec "PolymorphicComponents" LangExt.RankNTypes,
3673 flagSpec "PostfixOperators" LangExt.PostfixOperators,
3674 flagSpec "QuasiQuotes" LangExt.QuasiQuotes,
3675 flagSpec "Rank2Types" LangExt.RankNTypes,
3676 flagSpec "RankNTypes" LangExt.RankNTypes,
3677 flagSpec "RebindableSyntax" LangExt.RebindableSyntax,
3678 depFlagSpec' "RecordPuns" LangExt.RecordPuns
3679 (deprecatedForExtension "NamedFieldPuns"),
3680 flagSpec "RecordWildCards" LangExt.RecordWildCards,
3681 flagSpec "RecursiveDo" LangExt.RecursiveDo,
3682 flagSpec "RelaxedLayout" LangExt.RelaxedLayout,
3683 depFlagSpecCond "RelaxedPolyRec" LangExt.RelaxedPolyRec
3684 not
3685 "You can't turn off RelaxedPolyRec any more",
3686 flagSpec "RoleAnnotations" LangExt.RoleAnnotations,
3687 flagSpec "ScopedTypeVariables" LangExt.ScopedTypeVariables,
3688 flagSpec "StandaloneDeriving" LangExt.StandaloneDeriving,
3689 flagSpec "StaticPointers" LangExt.StaticPointers,
3690 flagSpec "Strict" LangExt.Strict,
3691 flagSpec "StrictData" LangExt.StrictData,
3692 flagSpec' "TemplateHaskell" LangExt.TemplateHaskell
3693 checkTemplateHaskellOk,
3694 flagSpec "TemplateHaskellQuotes" LangExt.TemplateHaskellQuotes,
3695 flagSpec "TraditionalRecordSyntax" LangExt.TraditionalRecordSyntax,
3696 flagSpec "TransformListComp" LangExt.TransformListComp,
3697 flagSpec "TupleSections" LangExt.TupleSections,
3698 flagSpec "TypeApplications" LangExt.TypeApplications,
3699 flagSpec "TypeInType" LangExt.TypeInType,
3700 flagSpec "TypeFamilies" LangExt.TypeFamilies,
3701 flagSpec "TypeOperators" LangExt.TypeOperators,
3702 flagSpec "TypeSynonymInstances" LangExt.TypeSynonymInstances,
3703 flagSpec "UnboxedTuples" LangExt.UnboxedTuples,
3704 flagSpec "UnboxedSums" LangExt.UnboxedSums,
3705 flagSpec "UndecidableInstances" LangExt.UndecidableInstances,
3706 flagSpec "UndecidableSuperClasses" LangExt.UndecidableSuperClasses,
3707 flagSpec "UnicodeSyntax" LangExt.UnicodeSyntax,
3708 flagSpec "UnliftedFFITypes" LangExt.UnliftedFFITypes,
3709 flagSpec "ViewPatterns" LangExt.ViewPatterns
3710 ]
3711
3712 defaultFlags :: Settings -> [GeneralFlag]
3713 defaultFlags settings
3714 -- See Note [Updating flag description in the User's Guide]
3715 = [ Opt_AutoLinkPackages,
3716 Opt_EmbedManifest,
3717 Opt_FlatCache,
3718 Opt_GenManifest,
3719 Opt_GhciHistory,
3720 Opt_GhciSandbox,
3721 Opt_HelpfulErrors,
3722 Opt_KeepHiFiles,
3723 Opt_KeepOFiles,
3724 Opt_OmitYields,
3725 Opt_PrintBindContents,
3726 Opt_ProfCountEntries,
3727 Opt_RPath,
3728 Opt_SharedImplib,
3729 Opt_SimplPreInlining,
3730 Opt_VersionMacros
3731 ]
3732
3733 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
3734 -- The default -O0 options
3735
3736 ++ default_PIC platform
3737
3738 ++ concatMap (wayGeneralFlags platform) (defaultWays settings)
3739
3740 where platform = sTargetPlatform settings
3741
3742 default_PIC :: Platform -> [GeneralFlag]
3743 default_PIC platform =
3744 case (platformOS platform, platformArch platform) of
3745 (OSDarwin, ArchX86_64) -> [Opt_PIC]
3746 (OSOpenBSD, ArchX86_64) -> [Opt_PIC] -- Due to PIE support in
3747 -- OpenBSD since 5.3 release
3748 -- (1 May 2013) we need to
3749 -- always generate PIC. See
3750 -- #10597 for more
3751 -- information.
3752 _ -> []
3753
3754 -- General flags that are switched on/off when other general flags are switched
3755 -- on
3756 impliedGFlags :: [(GeneralFlag, TurnOnFlag, GeneralFlag)]
3757 impliedGFlags = [(Opt_DeferTypeErrors, turnOn, Opt_DeferTypedHoles)
3758 ,(Opt_DeferTypeErrors, turnOn, Opt_DeferOutOfScopeVariables)
3759 ,(Opt_Strictness, turnOn, Opt_WorkerWrapper)
3760 ]
3761
3762 -- General flags that are switched on/off when other general flags are switched
3763 -- off
3764 impliedOffGFlags :: [(GeneralFlag, TurnOnFlag, GeneralFlag)]
3765 impliedOffGFlags = [(Opt_Strictness, turnOff, Opt_WorkerWrapper)]
3766
3767 impliedXFlags :: [(LangExt.Extension, TurnOnFlag, LangExt.Extension)]
3768 impliedXFlags
3769 -- See Note [Updating flag description in the User's Guide]
3770 = [ (LangExt.RankNTypes, turnOn, LangExt.ExplicitForAll)
3771 , (LangExt.ScopedTypeVariables, turnOn, LangExt.ExplicitForAll)
3772 , (LangExt.LiberalTypeSynonyms, turnOn, LangExt.ExplicitForAll)
3773 , (LangExt.ExistentialQuantification,