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