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