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