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