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