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