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