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