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