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