Prefer #if defined to #ifdef
[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 ) where
159
160 #include "HsVersions.h"
161
162 import Platform
163 import PlatformConstants
164 import Module
165 import PackageConfig
166 import {-# SOURCE #-} Hooks
167 import {-# SOURCE #-} PrelNames ( mAIN )
168 import {-# SOURCE #-} Packages (PackageState, emptyPackageState)
169 import DriverPhases ( Phase(..), phaseInputExt )
170 import Config
171 import CmdLineParser
172 import Constants
173 import Panic
174 import qualified PprColour as Col
175 import Util
176 import Maybes
177 import MonadUtils
178 import qualified Pretty
179 import SrcLoc
180 import BasicTypes ( IntWithInf, treatZeroAsInf )
181 import FastString
182 import Outputable
183 import Foreign.C ( CInt(..) )
184 import System.IO.Unsafe ( unsafeDupablePerformIO )
185 import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessageAnn
186 , getCaretDiagnostic, dumpSDoc )
187 import Json
188 import SysTools.Terminal ( stderrSupportsAnsiColors )
189
190 import System.IO.Unsafe ( unsafePerformIO )
191 import Data.IORef
192 import Control.Arrow ((&&&))
193 import Control.Monad
194 import Control.Monad.Trans.Class
195 import Control.Monad.Trans.Writer
196 import Control.Monad.Trans.Reader
197 import Control.Monad.Trans.Except
198 import Control.Exception (throwIO)
199
200 import Data.Ord
201 import Data.Bits
202 import Data.Char
203 import Data.Int
204 import Data.List
205 import Data.Map (Map)
206 import qualified Data.Map as Map
207 import Data.Set (Set)
208 import qualified Data.Set as Set
209 import Data.Word
210 import System.FilePath
211 import System.Directory
212 import System.Environment (getEnv, lookupEnv)
213 import System.IO
214 import System.IO.Error
215 import Text.ParserCombinators.ReadP hiding (char)
216 import Text.ParserCombinators.ReadP as R
217
218 import EnumSet (EnumSet)
219 import qualified EnumSet
220
221 import GHC.Foreign (withCString, peekCString)
222 import qualified GHC.LanguageExtensions as LangExt
223
224 import Foreign (Ptr) -- needed for 2nd stage
225
226 -- Note [Updating flag description in the User's Guide]
227 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
228 --
229 -- If you modify anything in this file please make sure that your changes are
230 -- described in the User's Guide. Usually at least two sections need to be
231 -- updated:
232 --
233 -- * Flag Reference section generated from the modules in
234 -- utils/mkUserGuidePart/Options
235 --
236 -- * Flag description in docs/users_guide/using.rst provides a detailed
237 -- explanation of flags' usage.
238
239 -- Note [Supporting CLI completion]
240 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
241 --
242 -- The command line interface completion (in for example bash) is an easy way
243 -- for the developer to learn what flags are available from GHC.
244 -- GHC helps by separating which flags are available when compiling with GHC,
245 -- and which flags are available when using GHCi.
246 -- A flag is assumed to either work in both these modes, or only in one of them.
247 -- When adding or changing a flag, please consider for which mode the flag will
248 -- have effect, and annotate it accordingly. For Flags use defFlag, defGhcFlag,
249 -- defGhciFlag, and for FlagSpec use flagSpec or flagGhciSpec.
250
251 -- Note [Adding a language extension]
252 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
253 --
254 -- There are a few steps to adding (or removing) a language extension,
255 --
256 -- * Adding the extension to GHC.LanguageExtensions
257 --
258 -- The Extension type in libraries/ghc-boot-th/GHC/LanguageExtensions/Type.hs
259 -- is the canonical list of language extensions known by GHC.
260 --
261 -- * Adding a flag to DynFlags.xFlags
262 --
263 -- This is fairly self-explanatory. The name should be concise, memorable,
264 -- and consistent with any previous implementations of the similar idea in
265 -- other Haskell compilers.
266 --
267 -- * Adding the flag to the documentation
268 --
269 -- This is the same as any other flag. See
270 -- Note [Updating flag description in the User's Guide]
271 --
272 -- * Adding the flag to Cabal
273 --
274 -- The Cabal library has its own list of all language extensions supported
275 -- by all major compilers. This is the list that user code being uploaded
276 -- to Hackage is checked against to ensure language extension validity.
277 -- Consequently, it is very important that this list remains up-to-date.
278 --
279 -- To this end, there is a testsuite test (testsuite/tests/driver/T4437.hs)
280 -- whose job it is to ensure these GHC's extensions are consistent with
281 -- Cabal.
282 --
283 -- The recommended workflow is,
284 --
285 -- 1. Temporarily add your new language extension to the
286 -- expectedGhcOnlyExtensions list in T4437 to ensure the test doesn't
287 -- break while Cabal is updated.
288 --
289 -- 2. After your GHC change is accepted, submit a Cabal pull request adding
290 -- your new extension to Cabal's list (found in
291 -- Cabal/Language/Haskell/Extension.hs).
292 --
293 -- 3. After your Cabal change is accepted, let the GHC developers know so
294 -- they can update the Cabal submodule and remove the extensions from
295 -- expectedGhcOnlyExtensions.
296 --
297 -- * Adding the flag to the GHC Wiki
298 --
299 -- There is a change log tracking language extension additions and removals
300 -- on the GHC wiki: https://ghc.haskell.org/trac/ghc/wiki/LanguagePragmaHistory
301 --
302 -- See Trac #4437 and #8176.
303
304 -- -----------------------------------------------------------------------------
305 -- DynFlags
306
307 data DumpFlag
308 -- See Note [Updating flag description in the User's Guide]
309
310 -- debugging flags
311 = Opt_D_dump_cmm
312 | Opt_D_dump_cmm_from_stg
313 | Opt_D_dump_cmm_raw
314 | Opt_D_dump_cmm_verbose
315 -- All of the cmm subflags (there are a lot!) automatically
316 -- enabled if you run -ddump-cmm-verbose
317 -- Each flag corresponds to exact stage of Cmm pipeline.
318 | Opt_D_dump_cmm_cfg
319 | Opt_D_dump_cmm_cbe
320 | Opt_D_dump_cmm_switch
321 | Opt_D_dump_cmm_proc
322 | Opt_D_dump_cmm_sp
323 | Opt_D_dump_cmm_sink
324 | Opt_D_dump_cmm_caf
325 | Opt_D_dump_cmm_procmap
326 | Opt_D_dump_cmm_split
327 | Opt_D_dump_cmm_info
328 | Opt_D_dump_cmm_cps
329 -- end cmm subflags
330 | Opt_D_dump_asm
331 | Opt_D_dump_asm_native
332 | Opt_D_dump_asm_liveness
333 | Opt_D_dump_asm_regalloc
334 | Opt_D_dump_asm_regalloc_stages
335 | Opt_D_dump_asm_conflicts
336 | Opt_D_dump_asm_stats
337 | Opt_D_dump_asm_expanded
338 | Opt_D_dump_llvm
339 | Opt_D_dump_core_stats
340 | Opt_D_dump_deriv
341 | Opt_D_dump_ds
342 | Opt_D_dump_foreign
343 | Opt_D_dump_inlinings
344 | Opt_D_dump_rule_firings
345 | Opt_D_dump_rule_rewrites
346 | Opt_D_dump_simpl_trace
347 | Opt_D_dump_occur_anal
348 | Opt_D_dump_parsed
349 | Opt_D_dump_parsed_ast
350 | Opt_D_dump_rn
351 | Opt_D_dump_rn_ast
352 | Opt_D_dump_shape
353 | Opt_D_dump_simpl
354 | Opt_D_dump_simpl_iterations
355 | Opt_D_dump_spec
356 | Opt_D_dump_prep
357 | Opt_D_dump_stg
358 | Opt_D_dump_call_arity
359 | Opt_D_dump_stranal
360 | Opt_D_dump_str_signatures
361 | Opt_D_dump_tc
362 | Opt_D_dump_tc_ast
363 | Opt_D_dump_types
364 | Opt_D_dump_rules
365 | Opt_D_dump_cse
366 | Opt_D_dump_worker_wrapper
367 | Opt_D_dump_rn_trace
368 | Opt_D_dump_rn_stats
369 | Opt_D_dump_opt_cmm
370 | Opt_D_dump_simpl_stats
371 | Opt_D_dump_cs_trace -- Constraint solver in type checker
372 | Opt_D_dump_tc_trace
373 | Opt_D_dump_ec_trace -- Pattern match exhaustiveness checker
374 | Opt_D_dump_if_trace
375 | Opt_D_dump_vt_trace
376 | Opt_D_dump_splices
377 | Opt_D_th_dec_file
378 | Opt_D_dump_BCOs
379 | Opt_D_dump_vect
380 | Opt_D_dump_ticked
381 | Opt_D_dump_rtti
382 | Opt_D_source_stats
383 | Opt_D_verbose_stg2stg
384 | Opt_D_dump_hi
385 | Opt_D_dump_hi_diffs
386 | Opt_D_dump_mod_cycles
387 | Opt_D_dump_mod_map
388 | Opt_D_dump_view_pattern_commoning
389 | Opt_D_verbose_core2core
390 | Opt_D_dump_debug
391 | Opt_D_dump_json
392 | Opt_D_ppr_debug
393 | Opt_D_no_debug_output
394 deriving (Eq, Show, Enum)
395
396 -- | Enumerates the simple on-or-off dynamic flags
397 data GeneralFlag
398 -- See Note [Updating flag description in the User's Guide]
399
400 = Opt_DumpToFile -- ^ Append dump output to files instead of stdout.
401 | Opt_D_faststring_stats
402 | Opt_D_dump_minimal_imports
403 | Opt_DoCoreLinting
404 | Opt_DoStgLinting
405 | Opt_DoCmmLinting
406 | Opt_DoAsmLinting
407 | Opt_DoAnnotationLinting
408 | Opt_NoLlvmMangler -- hidden flag
409
410 | Opt_WarnIsError -- -Werror; makes warnings fatal
411 | Opt_ShowWarnGroups -- Show the group a warning belongs to
412 | Opt_HideSourcePaths -- Hide module source/object paths
413
414 | Opt_PrintExplicitForalls
415 | Opt_PrintExplicitKinds
416 | Opt_PrintExplicitCoercions
417 | Opt_PrintExplicitRuntimeReps
418 | Opt_PrintEqualityRelations
419 | Opt_PrintUnicodeSyntax
420 | Opt_PrintExpandedSynonyms
421 | Opt_PrintPotentialInstances
422 | Opt_PrintTypecheckerElaboration
423
424 -- optimisation opts
425 | Opt_CallArity
426 | Opt_Strictness
427 | Opt_LateDmdAnal
428 | Opt_KillAbsence
429 | Opt_KillOneShot
430 | Opt_FullLaziness
431 | Opt_FloatIn
432 | Opt_Specialise
433 | Opt_SpecialiseAggressively
434 | Opt_CrossModuleSpecialise
435 | Opt_StaticArgumentTransformation
436 | Opt_CSE
437 | Opt_StgCSE
438 | Opt_LiberateCase
439 | Opt_SpecConstr
440 | Opt_SpecConstrKeen
441 | Opt_DoLambdaEtaExpansion
442 | Opt_IgnoreAsserts
443 | Opt_DoEtaReduction
444 | Opt_CaseMerge
445 | Opt_CaseFolding -- Constant folding through case-expressions
446 | Opt_UnboxStrictFields
447 | Opt_UnboxSmallStrictFields
448 | Opt_DictsCheap
449 | Opt_EnableRewriteRules -- Apply rewrite rules during simplification
450 | Opt_Vectorise
451 | Opt_VectorisationAvoidance
452 | Opt_RegsGraph -- do graph coloring register allocation
453 | Opt_RegsIterative -- do iterative coalescing graph coloring register allocation
454 | Opt_PedanticBottoms -- Be picky about how we treat bottom
455 | Opt_LlvmTBAA -- Use LLVM TBAA infastructure for improving AA (hidden flag)
456 | Opt_LlvmPassVectorsInRegisters -- Pass SIMD vectors in registers (requires a patched LLVM) (hidden flag)
457 | Opt_LlvmFillUndefWithGarbage -- Testing for undef bugs (hidden flag)
458 | Opt_IrrefutableTuples
459 | Opt_CmmSink
460 | Opt_CmmElimCommonBlocks
461 | Opt_OmitYields
462 | Opt_FunToThunk -- allow WwLib.mkWorkerArgs to remove all value lambdas
463 | Opt_DictsStrict -- be strict in argument dictionaries
464 | Opt_DmdTxDictSel -- use a special demand transformer for dictionary selectors
465 | Opt_Loopification -- See Note [Self-recursive tail calls]
466 | Opt_CprAnal
467 | Opt_WorkerWrapper
468 | Opt_SolveConstantDicts
469
470 -- Interface files
471 | Opt_IgnoreInterfacePragmas
472 | Opt_OmitInterfacePragmas
473 | Opt_ExposeAllUnfoldings
474 | Opt_WriteInterface -- forces .hi files to be written even with -fno-code
475
476 -- profiling opts
477 | Opt_AutoSccsOnIndividualCafs
478 | Opt_ProfCountEntries
479
480 -- misc opts
481 | Opt_Pp
482 | Opt_ForceRecomp
483 | Opt_ExcessPrecision
484 | Opt_EagerBlackHoling
485 | Opt_NoHsMain
486 | Opt_SplitObjs
487 | Opt_SplitSections
488 | Opt_StgStats
489 | Opt_HideAllPackages
490 | Opt_HideAllPluginPackages
491 | Opt_PrintBindResult
492 | Opt_Haddock
493 | Opt_HaddockOptions
494 | Opt_BreakOnException
495 | Opt_BreakOnError
496 | Opt_PrintEvldWithShow
497 | Opt_PrintBindContents
498 | Opt_GenManifest
499 | Opt_EmbedManifest
500 | Opt_SharedImplib
501 | Opt_BuildingCabalPackage
502 | Opt_IgnoreDotGhci
503 | Opt_GhciSandbox
504 | Opt_GhciHistory
505 | Opt_LocalGhciHistory
506 | Opt_HelpfulErrors
507 | Opt_DeferTypeErrors
508 | Opt_DeferTypedHoles
509 | Opt_DeferOutOfScopeVariables
510 | Opt_PIC
511 | Opt_SccProfilingOn
512 | Opt_Ticky
513 | Opt_Ticky_Allocd
514 | Opt_Ticky_LNE
515 | Opt_Ticky_Dyn_Thunk
516 | Opt_RPath
517 | Opt_RelativeDynlibPaths
518 | Opt_Hpc
519 | Opt_FlatCache
520 | Opt_ExternalInterpreter
521 | Opt_OptimalApplicativeDo
522 | Opt_VersionMacros
523 | Opt_WholeArchiveHsLibs
524
525 -- PreInlining is on by default. The option is there just to see how
526 -- bad things get if you turn it off!
527 | Opt_SimplPreInlining
528
529 -- output style opts
530 | Opt_ErrorSpans -- Include full span info in error messages,
531 -- instead of just the start position.
532 | Opt_DiagnosticsShowCaret -- Show snippets of offending code
533 | Opt_PprCaseAsLet
534 | Opt_PprShowTicks
535 | Opt_ShowHoleConstraints
536
537 -- Suppress all coercions, them replacing with '...'
538 | Opt_SuppressCoercions
539 | Opt_SuppressVarKinds
540 -- Suppress module id prefixes on variables.
541 | Opt_SuppressModulePrefixes
542 -- Suppress type applications.
543 | Opt_SuppressTypeApplications
544 -- Suppress info such as arity and unfoldings on identifiers.
545 | Opt_SuppressIdInfo
546 -- Suppress separate type signatures in core, but leave types on
547 -- lambda bound vars
548 | Opt_SuppressUnfoldings
549 -- Suppress the details of even stable unfoldings
550 | Opt_SuppressTypeSignatures
551 -- Suppress unique ids on variables.
552 -- Except for uniques, as some simplifier phases introduce new
553 -- variables that have otherwise identical names.
554 | Opt_SuppressUniques
555 | Opt_SuppressTicks -- Replaces Opt_PprShowTicks
556
557 -- temporary flags
558 | Opt_AutoLinkPackages
559 | Opt_ImplicitImportQualified
560
561 -- keeping stuff
562 | Opt_KeepHiDiffs
563 | Opt_KeepHcFiles
564 | Opt_KeepSFiles
565 | Opt_KeepTmpFiles
566 | Opt_KeepRawTokenStream
567 | Opt_KeepLlvmFiles
568 | Opt_KeepHiFiles
569 | Opt_KeepOFiles
570
571 | Opt_BuildDynamicToo
572
573 -- safe haskell flags
574 | Opt_DistrustAllPackages
575 | Opt_PackageTrust
576
577 | Opt_G_NoStateHack
578 | Opt_G_NoOptCoercion
579 deriving (Eq, Show, Enum)
580
581 -- | Used when outputting warnings: if a reason is given, it is
582 -- displayed. If a warning isn't controlled by a flag, this is made
583 -- explicit at the point of use.
584 data WarnReason = NoReason | Reason !WarningFlag
585 deriving Show
586
587 instance Outputable WarnReason where
588 ppr = text . show
589
590 instance ToJson WarnReason where
591 json NoReason = JSNull
592 json (Reason wf) = JSString (show wf)
593
594 data WarningFlag =
595 -- See Note [Updating flag description in the User's Guide]
596 Opt_WarnDuplicateExports
597 | Opt_WarnDuplicateConstraints
598 | Opt_WarnRedundantConstraints
599 | Opt_WarnHiShadows
600 | Opt_WarnImplicitPrelude
601 | Opt_WarnIncompletePatterns
602 | Opt_WarnIncompleteUniPatterns
603 | Opt_WarnIncompletePatternsRecUpd
604 | Opt_WarnOverflowedLiterals
605 | Opt_WarnEmptyEnumerations
606 | Opt_WarnMissingFields
607 | Opt_WarnMissingImportList
608 | Opt_WarnMissingMethods
609 | Opt_WarnMissingSignatures
610 | Opt_WarnMissingLocalSignatures
611 | Opt_WarnNameShadowing
612 | Opt_WarnOverlappingPatterns
613 | Opt_WarnTypeDefaults
614 | Opt_WarnMonomorphism
615 | Opt_WarnUnusedTopBinds
616 | Opt_WarnUnusedLocalBinds
617 | Opt_WarnUnusedPatternBinds
618 | Opt_WarnUnusedImports
619 | Opt_WarnUnusedMatches
620 | Opt_WarnUnusedTypePatterns
621 | Opt_WarnUnusedForalls
622 | Opt_WarnWarningsDeprecations
623 | Opt_WarnDeprecatedFlags
624 | Opt_WarnAMP -- Introduced in GHC 7.8, obsolete since 7.10
625 | Opt_WarnMissingMonadFailInstances -- since 8.0
626 | Opt_WarnSemigroup -- since 8.0
627 | Opt_WarnDodgyExports
628 | Opt_WarnDodgyImports
629 | Opt_WarnOrphans
630 | Opt_WarnAutoOrphans
631 | Opt_WarnIdentities
632 | Opt_WarnTabs
633 | Opt_WarnUnrecognisedPragmas
634 | Opt_WarnDodgyForeignImports
635 | Opt_WarnUnusedDoBind
636 | Opt_WarnWrongDoBind
637 | Opt_WarnAlternativeLayoutRuleTransitional
638 | Opt_WarnUnsafe
639 | Opt_WarnSafe
640 | Opt_WarnTrustworthySafe
641 | Opt_WarnMissedSpecs
642 | Opt_WarnAllMissedSpecs
643 | Opt_WarnUnsupportedCallingConventions
644 | Opt_WarnUnsupportedLlvmVersion
645 | Opt_WarnInlineRuleShadowing
646 | Opt_WarnTypedHoles
647 | Opt_WarnPartialTypeSignatures
648 | Opt_WarnMissingExportedSignatures
649 | Opt_WarnUntickedPromotedConstructors
650 | Opt_WarnDerivingTypeable
651 | Opt_WarnDeferredTypeErrors
652 | Opt_WarnDeferredOutOfScopeVariables
653 | Opt_WarnNonCanonicalMonadInstances -- since 8.0
654 | Opt_WarnNonCanonicalMonadFailInstances -- since 8.0
655 | Opt_WarnNonCanonicalMonoidInstances -- since 8.0
656 | Opt_WarnMissingPatternSynonymSignatures -- since 8.0
657 | Opt_WarnUnrecognisedWarningFlags -- since 8.0
658 | Opt_WarnSimplifiableClassConstraints -- Since 8.2
659 | Opt_WarnCPPUndef -- Since 8.2
660 | Opt_WarnUnbangedStrictPatterns -- Since 8.2
661 | Opt_WarnMissingHomeModules -- Since 8.2
662 deriving (Eq, Show, Enum)
663
664 data Language = Haskell98 | Haskell2010
665 deriving (Eq, Enum, Show)
666
667 instance Outputable Language where
668 ppr = text . show
669
670 -- | The various Safe Haskell modes
671 data SafeHaskellMode
672 = Sf_None
673 | Sf_Unsafe
674 | Sf_Trustworthy
675 | Sf_Safe
676 deriving (Eq)
677
678 instance Show SafeHaskellMode where
679 show Sf_None = "None"
680 show Sf_Unsafe = "Unsafe"
681 show Sf_Trustworthy = "Trustworthy"
682 show Sf_Safe = "Safe"
683
684 instance Outputable SafeHaskellMode where
685 ppr = text . show
686
687 -- | Contains not only a collection of 'GeneralFlag's but also a plethora of
688 -- information relating to the compilation of a single file or GHC session
689 data DynFlags = DynFlags {
690 ghcMode :: GhcMode,
691 ghcLink :: GhcLink,
692 hscTarget :: HscTarget,
693 settings :: Settings,
694 verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels]
695 optLevel :: Int, -- ^ Optimisation level
696 debugLevel :: Int, -- ^ How much debug information to produce
697 simplPhases :: Int, -- ^ Number of simplifier phases
698 maxSimplIterations :: Int, -- ^ Max simplifier iterations
699 maxPmCheckIterations :: Int, -- ^ Max no iterations for pm checking
700 ruleCheck :: Maybe String,
701 strictnessBefore :: [Int], -- ^ Additional demand analysis
702
703 parMakeCount :: Maybe Int, -- ^ The number of modules to compile in parallel
704 -- in --make mode, where Nothing ==> compile as
705 -- many in parallel as there are CPUs.
706
707 enableTimeStats :: Bool, -- ^ Enable RTS timing statistics?
708 ghcHeapSize :: Maybe Int, -- ^ The heap size to set.
709
710 maxRelevantBinds :: Maybe Int, -- ^ Maximum number of bindings from the type envt
711 -- to show in type error messages
712 maxValidSubstitutions :: Maybe Int, -- ^ Maximum number of substitutions
713 -- to show in type error messages
714 maxUncoveredPatterns :: Int, -- ^ Maximum number of unmatched patterns to show
715 -- in non-exhaustiveness warnings
716 simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks
717 specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr
718 specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function
719 specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types
720 -- Not optional; otherwise ForceSpecConstr can diverge.
721 liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase
722 floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating
723 -- See CoreMonad.FloatOutSwitches
724
725 historySize :: Int, -- ^ Simplification history size
726
727 importPaths :: [FilePath],
728 mainModIs :: Module,
729 mainFunIs :: Maybe String,
730 reductionDepth :: IntWithInf, -- ^ Typechecker maximum stack depth
731 solverIterations :: IntWithInf, -- ^ Number of iterations in the constraints solver
732 -- Typically only 1 is needed
733
734 thisInstalledUnitId :: InstalledUnitId,
735 thisComponentId_ :: Maybe ComponentId,
736 thisUnitIdInsts_ :: Maybe [(ModuleName, Module)],
737
738 -- ways
739 ways :: [Way], -- ^ Way flags from the command line
740 buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof)
741 rtsBuildTag :: String, -- ^ The RTS \"way\"
742
743 -- For object splitting
744 splitInfo :: Maybe (String,Int),
745
746 -- paths etc.
747 objectDir :: Maybe String,
748 dylibInstallName :: Maybe String,
749 hiDir :: Maybe String,
750 stubDir :: Maybe String,
751 dumpDir :: Maybe String,
752
753 objectSuf :: String,
754 hcSuf :: String,
755 hiSuf :: String,
756
757 canGenerateDynamicToo :: IORef Bool,
758 dynObjectSuf :: String,
759 dynHiSuf :: String,
760
761 -- Packages.isDllName needs to know whether a call is within a
762 -- single DLL or not. Normally it does this by seeing if the call
763 -- is to the same package, but for the ghc package, we split the
764 -- package between 2 DLLs. The dllSplit tells us which sets of
765 -- modules are in which package.
766 dllSplitFile :: Maybe FilePath,
767 dllSplit :: Maybe [Set String],
768
769 outputFile :: Maybe String,
770 dynOutputFile :: Maybe String,
771 outputHi :: Maybe String,
772 dynLibLoader :: DynLibLoader,
773
774 -- | This is set by 'DriverPipeline.runPipeline' based on where
775 -- its output is going.
776 dumpPrefix :: Maybe FilePath,
777
778 -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
779 -- Set by @-ddump-file-prefix@
780 dumpPrefixForce :: Maybe FilePath,
781
782 ldInputs :: [Option],
783
784 includePaths :: [String],
785 libraryPaths :: [String],
786 frameworkPaths :: [String], -- used on darwin only
787 cmdlineFrameworks :: [String], -- ditto
788
789 rtsOpts :: Maybe String,
790 rtsOptsEnabled :: RtsOptsEnabled,
791 rtsOptsSuggestions :: Bool,
792
793 hpcDir :: String, -- ^ Path to store the .mix files
794
795 -- Plugins
796 pluginModNames :: [ModuleName],
797 pluginModNameOpts :: [(ModuleName,String)],
798 frontendPluginOpts :: [String],
799
800 -- GHC API hooks
801 hooks :: Hooks,
802
803 -- For ghc -M
804 depMakefile :: FilePath,
805 depIncludePkgDeps :: Bool,
806 depExcludeMods :: [ModuleName],
807 depSuffixes :: [String],
808
809 -- Package flags
810 packageDBFlags :: [PackageDBFlag],
811 -- ^ The @-package-db@ flags given on the command line, In
812 -- *reverse* order that they're specified on the command line.
813 -- This is intended to be applied with the list of "initial"
814 -- package databases derived from @GHC_PACKAGE_PATH@; see
815 -- 'getPackageConfRefs'.
816
817 ignorePackageFlags :: [IgnorePackageFlag],
818 -- ^ The @-ignore-package@ flags from the command line.
819 -- In *reverse* order that they're specified on the command line.
820 packageFlags :: [PackageFlag],
821 -- ^ The @-package@ and @-hide-package@ flags from the command-line.
822 -- In *reverse* order that they're specified on the command line.
823 pluginPackageFlags :: [PackageFlag],
824 -- ^ The @-plugin-package-id@ flags from command line.
825 -- In *reverse* order that they're specified on the command line.
826 trustFlags :: [TrustFlag],
827 -- ^ The @-trust@ and @-distrust@ flags.
828 -- In *reverse* order that they're specified on the command line.
829 packageEnv :: Maybe FilePath,
830 -- ^ Filepath to the package environment file (if overriding default)
831
832 -- Package state
833 -- NB. do not modify this field, it is calculated by
834 -- Packages.initPackages
835 pkgDatabase :: Maybe [(FilePath, [PackageConfig])],
836 pkgState :: PackageState,
837
838 -- Temporary files
839 -- These have to be IORefs, because the defaultCleanupHandler needs to
840 -- know what to clean when an exception happens
841 filesToClean :: IORef [FilePath],
842 dirsToClean :: IORef (Map FilePath FilePath),
843 filesToNotIntermediateClean :: IORef [FilePath],
844 -- The next available suffix to uniquely name a temp file, updated atomically
845 nextTempSuffix :: IORef Int,
846
847 -- Names of files which were generated from -ddump-to-file; used to
848 -- track which ones we need to truncate because it's our first run
849 -- through
850 generatedDumps :: IORef (Set FilePath),
851
852 -- hsc dynamic flags
853 dumpFlags :: EnumSet DumpFlag,
854 generalFlags :: EnumSet GeneralFlag,
855 warningFlags :: EnumSet WarningFlag,
856 fatalWarningFlags :: EnumSet WarningFlag,
857 -- Don't change this without updating extensionFlags:
858 language :: Maybe Language,
859 -- | Safe Haskell mode
860 safeHaskell :: SafeHaskellMode,
861 safeInfer :: Bool,
862 safeInferred :: Bool,
863 -- We store the location of where some extension and flags were turned on so
864 -- we can produce accurate error messages when Safe Haskell fails due to
865 -- them.
866 thOnLoc :: SrcSpan,
867 newDerivOnLoc :: SrcSpan,
868 overlapInstLoc :: SrcSpan,
869 incoherentOnLoc :: SrcSpan,
870 pkgTrustOnLoc :: SrcSpan,
871 warnSafeOnLoc :: SrcSpan,
872 warnUnsafeOnLoc :: SrcSpan,
873 trustworthyOnLoc :: SrcSpan,
874 -- Don't change this without updating extensionFlags:
875 extensions :: [OnOff LangExt.Extension],
876 -- extensionFlags should always be equal to
877 -- flattenExtensionFlags language extensions
878 -- LangExt.Extension is defined in libraries/ghc-boot so that it can be used
879 -- by template-haskell
880 extensionFlags :: EnumSet LangExt.Extension,
881
882 -- Unfolding control
883 -- See Note [Discounts and thresholds] in CoreUnfold
884 ufCreationThreshold :: Int,
885 ufUseThreshold :: Int,
886 ufFunAppDiscount :: Int,
887 ufDictDiscount :: Int,
888 ufKeenessFactor :: Float,
889 ufDearOp :: Int,
890 ufVeryAggressive :: Bool,
891
892 maxWorkerArgs :: Int,
893
894 ghciHistSize :: Int,
895
896 -- | MsgDoc output action: use "ErrUtils" instead of this if you can
897 initLogAction :: IO (Maybe LogOutput),
898 log_action :: LogAction,
899 log_finaliser :: LogFinaliser,
900 flushOut :: FlushOut,
901 flushErr :: FlushErr,
902
903 haddockOptions :: Maybe String,
904
905 -- | GHCi scripts specified by -ghci-script, in reverse order
906 ghciScripts :: [String],
907
908 -- Output style options
909 pprUserLength :: Int,
910 pprCols :: Int,
911
912 useUnicode :: Bool,
913 useColor :: OverridingBool,
914 canUseColor :: Bool,
915 colScheme :: Col.Scheme,
916
917 -- | what kind of {-# SCC #-} to add automatically
918 profAuto :: ProfAuto,
919
920 interactivePrint :: Maybe String,
921
922 nextWrapperNum :: IORef (ModuleEnv Int),
923
924 -- | Machine dependent flags (-m<blah> stuff)
925 sseVersion :: Maybe SseVersion,
926 avx :: Bool,
927 avx2 :: Bool,
928 avx512cd :: Bool, -- Enable AVX-512 Conflict Detection Instructions.
929 avx512er :: Bool, -- Enable AVX-512 Exponential and Reciprocal Instructions.
930 avx512f :: Bool, -- Enable AVX-512 instructions.
931 avx512pf :: Bool, -- Enable AVX-512 PreFetch Instructions.
932
933 -- | Run-time linker information (what options we need, etc.)
934 rtldInfo :: IORef (Maybe LinkerInfo),
935
936 -- | Run-time compiler information
937 rtccInfo :: IORef (Maybe CompilerInfo),
938
939 -- Constants used to control the amount of optimization done.
940
941 -- | Max size, in bytes, of inline array allocations.
942 maxInlineAllocSize :: Int,
943
944 -- | Only inline memcpy if it generates no more than this many
945 -- pseudo (roughly: Cmm) instructions.
946 maxInlineMemcpyInsns :: Int,
947
948 -- | Only inline memset if it generates no more than this many
949 -- pseudo (roughly: Cmm) instructions.
950 maxInlineMemsetInsns :: Int,
951
952 -- | Reverse the order of error messages in GHC/GHCi
953 reverseErrors :: Bool,
954
955 -- | Limit the maximum number of errors to show
956 maxErrors :: Maybe Int,
957
958 -- | Unique supply configuration for testing build determinism
959 initialUnique :: Int,
960 uniqueIncrement :: Int
961 }
962
963 class HasDynFlags m where
964 getDynFlags :: m DynFlags
965
966 {- It would be desirable to have the more generalised
967
968 instance (MonadTrans t, Monad m, HasDynFlags m) => HasDynFlags (t m) where
969 getDynFlags = lift getDynFlags
970
971 instance definition. However, that definition would overlap with the
972 `HasDynFlags (GhcT m)` instance. Instead we define instances for a
973 couple of common Monad transformers explicitly. -}
974
975 instance (Monoid a, Monad m, HasDynFlags m) => HasDynFlags (WriterT a m) where
976 getDynFlags = lift getDynFlags
977
978 instance (Monad m, HasDynFlags m) => HasDynFlags (ReaderT a m) where
979 getDynFlags = lift getDynFlags
980
981 instance (Monad m, HasDynFlags m) => HasDynFlags (MaybeT m) where
982 getDynFlags = lift getDynFlags
983
984 instance (Monad m, HasDynFlags m) => HasDynFlags (ExceptT e m) where
985 getDynFlags = lift getDynFlags
986
987 class ContainsDynFlags t where
988 extractDynFlags :: t -> DynFlags
989
990 data ProfAuto
991 = NoProfAuto -- ^ no SCC annotations added
992 | ProfAutoAll -- ^ top-level and nested functions are annotated
993 | ProfAutoTop -- ^ top-level functions annotated only
994 | ProfAutoExports -- ^ exported functions annotated only
995 | ProfAutoCalls -- ^ annotate call-sites
996 deriving (Eq,Enum)
997
998 data Settings = Settings {
999 sTargetPlatform :: Platform, -- Filled in by SysTools
1000 sGhcUsagePath :: FilePath, -- Filled in by SysTools
1001 sGhciUsagePath :: FilePath, -- ditto
1002 sTopDir :: FilePath,
1003 sTmpDir :: String, -- no trailing '/'
1004 sProgramName :: String,
1005 sProjectVersion :: String,
1006 -- You shouldn't need to look things up in rawSettings directly.
1007 -- They should have their own fields instead.
1008 sRawSettings :: [(String, String)],
1009 sExtraGccViaCFlags :: [String],
1010 sSystemPackageConfig :: FilePath,
1011 sLdSupportsCompactUnwind :: Bool,
1012 sLdSupportsBuildId :: Bool,
1013 sLdSupportsFilelist :: Bool,
1014 sLdIsGnuLd :: Bool,
1015 sGccSupportsNoPie :: Bool,
1016 -- commands for particular phases
1017 sPgm_L :: String,
1018 sPgm_P :: (String,[Option]),
1019 sPgm_F :: String,
1020 sPgm_c :: (String,[Option]),
1021 sPgm_s :: (String,[Option]),
1022 sPgm_a :: (String,[Option]),
1023 sPgm_l :: (String,[Option]),
1024 sPgm_dll :: (String,[Option]),
1025 sPgm_T :: String,
1026 sPgm_windres :: String,
1027 sPgm_libtool :: String,
1028 sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser
1029 sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler
1030 sPgm_i :: String,
1031 -- options for particular phases
1032 sOpt_L :: [String],
1033 sOpt_P :: [String],
1034 sOpt_F :: [String],
1035 sOpt_c :: [String],
1036 sOpt_a :: [String],
1037 sOpt_l :: [String],
1038 sOpt_windres :: [String],
1039 sOpt_lo :: [String], -- LLVM: llvm optimiser
1040 sOpt_lc :: [String], -- LLVM: llc static compiler
1041 sOpt_i :: [String], -- iserv options
1042
1043 sPlatformConstants :: PlatformConstants
1044 }
1045
1046 targetPlatform :: DynFlags -> Platform
1047 targetPlatform dflags = sTargetPlatform (settings dflags)
1048 programName :: DynFlags -> String
1049 programName dflags = sProgramName (settings dflags)
1050 projectVersion :: DynFlags -> String
1051 projectVersion dflags = sProjectVersion (settings dflags)
1052 ghcUsagePath :: DynFlags -> FilePath
1053 ghcUsagePath dflags = sGhcUsagePath (settings dflags)
1054 ghciUsagePath :: DynFlags -> FilePath
1055 ghciUsagePath dflags = sGhciUsagePath (settings dflags)
1056 topDir :: DynFlags -> FilePath
1057 topDir dflags = sTopDir (settings dflags)
1058 tmpDir :: DynFlags -> String
1059 tmpDir dflags = sTmpDir (settings dflags)
1060 rawSettings :: DynFlags -> [(String, String)]
1061 rawSettings dflags = sRawSettings (settings dflags)
1062 extraGccViaCFlags :: DynFlags -> [String]
1063 extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags)
1064 systemPackageConfig :: DynFlags -> FilePath
1065 systemPackageConfig dflags = sSystemPackageConfig (settings dflags)
1066 pgm_L :: DynFlags -> String
1067 pgm_L dflags = sPgm_L (settings dflags)
1068 pgm_P :: DynFlags -> (String,[Option])
1069 pgm_P dflags = sPgm_P (settings dflags)
1070 pgm_F :: DynFlags -> String
1071 pgm_F dflags = sPgm_F (settings dflags)
1072 pgm_c :: DynFlags -> (String,[Option])
1073 pgm_c dflags = sPgm_c (settings dflags)
1074 pgm_s :: DynFlags -> (String,[Option])
1075 pgm_s dflags = sPgm_s (settings dflags)
1076 pgm_a :: DynFlags -> (String,[Option])
1077 pgm_a dflags = sPgm_a (settings dflags)
1078 pgm_l :: DynFlags -> (String,[Option])
1079 pgm_l dflags = sPgm_l (settings dflags)
1080 pgm_dll :: DynFlags -> (String,[Option])
1081 pgm_dll dflags = sPgm_dll (settings dflags)
1082 pgm_T :: DynFlags -> String
1083 pgm_T dflags = sPgm_T (settings dflags)
1084 pgm_windres :: DynFlags -> String
1085 pgm_windres dflags = sPgm_windres (settings dflags)
1086 pgm_libtool :: DynFlags -> String
1087 pgm_libtool dflags = sPgm_libtool (settings dflags)
1088 pgm_lo :: DynFlags -> (String,[Option])
1089 pgm_lo dflags = sPgm_lo (settings dflags)
1090 pgm_lc :: DynFlags -> (String,[Option])
1091 pgm_lc dflags = sPgm_lc (settings dflags)
1092 pgm_i :: DynFlags -> String
1093 pgm_i dflags = sPgm_i (settings dflags)
1094 opt_L :: DynFlags -> [String]
1095 opt_L dflags = sOpt_L (settings dflags)
1096 opt_P :: DynFlags -> [String]
1097 opt_P dflags = concatMap (wayOptP (targetPlatform dflags)) (ways dflags)
1098 ++ sOpt_P (settings dflags)
1099 opt_F :: DynFlags -> [String]
1100 opt_F dflags = sOpt_F (settings dflags)
1101 opt_c :: DynFlags -> [String]
1102 opt_c dflags = concatMap (wayOptc (targetPlatform dflags)) (ways dflags)
1103 ++ sOpt_c (settings dflags)
1104 opt_a :: DynFlags -> [String]
1105 opt_a dflags = sOpt_a (settings dflags)
1106 opt_l :: DynFlags -> [String]
1107 opt_l dflags = concatMap (wayOptl (targetPlatform dflags)) (ways dflags)
1108 ++ sOpt_l (settings dflags)
1109 opt_windres :: DynFlags -> [String]
1110 opt_windres dflags = sOpt_windres (settings dflags)
1111 opt_lo :: DynFlags -> [String]
1112 opt_lo dflags = sOpt_lo (settings dflags)
1113 opt_lc :: DynFlags -> [String]
1114 opt_lc dflags = sOpt_lc (settings dflags)
1115 opt_i :: DynFlags -> [String]
1116 opt_i dflags = sOpt_i (settings dflags)
1117
1118 -- | The directory for this version of ghc in the user's app directory
1119 -- (typically something like @~/.ghc/x86_64-linux-7.6.3@)
1120 --
1121 versionedAppDir :: DynFlags -> MaybeT IO FilePath
1122 versionedAppDir dflags = do
1123 -- Make sure we handle the case the HOME isn't set (see #11678)
1124 appdir <- tryMaybeT $ getAppUserDataDirectory (programName dflags)
1125 return $ appdir </> versionedFilePath dflags
1126
1127 -- | A filepath like @x86_64-linux-7.6.3@ with the platform string to use when
1128 -- constructing platform-version-dependent files that need to co-exist.
1129 --
1130 versionedFilePath :: DynFlags -> FilePath
1131 versionedFilePath dflags = TARGET_ARCH
1132 ++ '-':TARGET_OS
1133 ++ '-':projectVersion dflags
1134 -- NB: This functionality is reimplemented in Cabal, so if you
1135 -- change it, be sure to update Cabal.
1136
1137 -- | The target code type of the compilation (if any).
1138 --
1139 -- Whenever you change the target, also make sure to set 'ghcLink' to
1140 -- something sensible.
1141 --
1142 -- 'HscNothing' can be used to avoid generating any output, however, note
1143 -- that:
1144 --
1145 -- * If a program uses Template Haskell the typechecker may try to run code
1146 -- from an imported module. This will fail if no code has been generated
1147 -- for this module. You can use 'GHC.needsTemplateHaskell' to detect
1148 -- whether this might be the case and choose to either switch to a
1149 -- different target or avoid typechecking such modules. (The latter may be
1150 -- preferable for security reasons.)
1151 --
1152 data HscTarget
1153 = HscC -- ^ Generate C code.
1154 | HscAsm -- ^ Generate assembly using the native code generator.
1155 | HscLlvm -- ^ Generate assembly using the llvm code generator.
1156 | HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory')
1157 | HscNothing -- ^ Don't generate any code. See notes above.
1158 deriving (Eq, Show)
1159
1160 -- | Will this target result in an object file on the disk?
1161 isObjectTarget :: HscTarget -> Bool
1162 isObjectTarget HscC = True
1163 isObjectTarget HscAsm = True
1164 isObjectTarget HscLlvm = True
1165 isObjectTarget _ = False
1166
1167 -- | Does this target retain *all* top-level bindings for a module,
1168 -- rather than just the exported bindings, in the TypeEnv and compiled
1169 -- code (if any)? In interpreted mode we do this, so that GHCi can
1170 -- call functions inside a module. In HscNothing mode we also do it,
1171 -- so that Haddock can get access to the GlobalRdrEnv for a module
1172 -- after typechecking it.
1173 targetRetainsAllBindings :: HscTarget -> Bool
1174 targetRetainsAllBindings HscInterpreted = True
1175 targetRetainsAllBindings HscNothing = True
1176 targetRetainsAllBindings _ = False
1177
1178 -- | The 'GhcMode' tells us whether we're doing multi-module
1179 -- compilation (controlled via the "GHC" API) or one-shot
1180 -- (single-module) compilation. This makes a difference primarily to
1181 -- the "Finder": in one-shot mode we look for interface files for
1182 -- imported modules, but in multi-module mode we look for source files
1183 -- in order to check whether they need to be recompiled.
1184 data GhcMode
1185 = CompManager -- ^ @\-\-make@, GHCi, etc.
1186 | OneShot -- ^ @ghc -c Foo.hs@
1187 | MkDepend -- ^ @ghc -M@, see "Finder" for why we need this
1188 deriving Eq
1189
1190 instance Outputable GhcMode where
1191 ppr CompManager = text "CompManager"
1192 ppr OneShot = text "OneShot"
1193 ppr MkDepend = text "MkDepend"
1194
1195 isOneShot :: GhcMode -> Bool
1196 isOneShot OneShot = True
1197 isOneShot _other = False
1198
1199 -- | What to do in the link step, if there is one.
1200 data GhcLink
1201 = NoLink -- ^ Don't link at all
1202 | LinkBinary -- ^ Link object code into a binary
1203 | LinkInMemory -- ^ Use the in-memory dynamic linker (works for both
1204 -- bytecode and object code).
1205 | LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
1206 | LinkStaticLib -- ^ Link objects into a static lib
1207 deriving (Eq, Show)
1208
1209 isNoLink :: GhcLink -> Bool
1210 isNoLink NoLink = True
1211 isNoLink _ = False
1212
1213 -- | We accept flags which make packages visible, but how they select
1214 -- the package varies; this data type reflects what selection criterion
1215 -- is used.
1216 data PackageArg =
1217 PackageArg String -- ^ @-package@, by 'PackageName'
1218 | UnitIdArg UnitId -- ^ @-package-id@, by 'UnitId'
1219 deriving (Eq, Show)
1220 instance Outputable PackageArg where
1221 ppr (PackageArg pn) = text "package" <+> text pn
1222 ppr (UnitIdArg uid) = text "unit" <+> ppr uid
1223
1224 -- | Represents the renaming that may be associated with an exposed
1225 -- package, e.g. the @rns@ part of @-package "foo (rns)"@.
1226 --
1227 -- Here are some example parsings of the package flags (where
1228 -- a string literal is punned to be a 'ModuleName':
1229 --
1230 -- * @-package foo@ is @ModRenaming True []@
1231 -- * @-package foo ()@ is @ModRenaming False []@
1232 -- * @-package foo (A)@ is @ModRenaming False [("A", "A")]@
1233 -- * @-package foo (A as B)@ is @ModRenaming False [("A", "B")]@
1234 -- * @-package foo with (A as B)@ is @ModRenaming True [("A", "B")]@
1235 data ModRenaming = ModRenaming {
1236 modRenamingWithImplicit :: Bool, -- ^ Bring all exposed modules into scope?
1237 modRenamings :: [(ModuleName, ModuleName)] -- ^ Bring module @m@ into scope
1238 -- under name @n@.
1239 } deriving (Eq)
1240 instance Outputable ModRenaming where
1241 ppr (ModRenaming b rns) = ppr b <+> parens (ppr rns)
1242
1243 -- | Flags for manipulating the set of non-broken packages.
1244 newtype IgnorePackageFlag = IgnorePackage String -- ^ @-ignore-package@
1245 deriving (Eq)
1246
1247 -- | Flags for manipulating package trust.
1248 data TrustFlag
1249 = TrustPackage String -- ^ @-trust@
1250 | DistrustPackage String -- ^ @-distrust@
1251 deriving (Eq)
1252
1253 -- | Flags for manipulating packages visibility.
1254 data PackageFlag
1255 = ExposePackage String PackageArg ModRenaming -- ^ @-package@, @-package-id@
1256 | HidePackage String -- ^ @-hide-package@
1257 deriving (Eq) -- NB: equality instance is used by packageFlagsChanged
1258
1259 data PackageDBFlag
1260 = PackageDB PkgConfRef
1261 | NoUserPackageDB
1262 | NoGlobalPackageDB
1263 | ClearPackageDBs
1264 deriving (Eq)
1265
1266 packageFlagsChanged :: DynFlags -> DynFlags -> Bool
1267 packageFlagsChanged idflags1 idflags0 =
1268 packageFlags idflags1 /= packageFlags idflags0 ||
1269 ignorePackageFlags idflags1 /= ignorePackageFlags idflags0 ||
1270 pluginPackageFlags idflags1 /= pluginPackageFlags idflags0 ||
1271 trustFlags idflags1 /= trustFlags idflags0 ||
1272 packageDBFlags idflags1 /= packageDBFlags idflags0 ||
1273 packageGFlags idflags1 /= packageGFlags idflags0
1274 where
1275 packageGFlags dflags = map (`gopt` dflags)
1276 [ Opt_HideAllPackages
1277 , Opt_HideAllPluginPackages
1278 , Opt_AutoLinkPackages ]
1279
1280 instance Outputable PackageFlag where
1281 ppr (ExposePackage n arg rn) = text n <> braces (ppr arg <+> ppr rn)
1282 ppr (HidePackage str) = text "-hide-package" <+> text str
1283
1284 defaultHscTarget :: Platform -> HscTarget
1285 defaultHscTarget = defaultObjectTarget
1286
1287 -- | The 'HscTarget' value corresponding to the default way to create
1288 -- object files on the current platform.
1289 defaultObjectTarget :: Platform -> HscTarget
1290 defaultObjectTarget platform
1291 | platformUnregisterised platform = HscC
1292 | cGhcWithNativeCodeGen == "YES" = HscAsm
1293 | otherwise = HscLlvm
1294
1295 tablesNextToCode :: DynFlags -> Bool
1296 tablesNextToCode dflags
1297 = mkTablesNextToCode (platformUnregisterised (targetPlatform dflags))
1298
1299 -- Determines whether we will be compiling
1300 -- info tables that reside just before the entry code, or with an
1301 -- indirection to the entry code. See TABLES_NEXT_TO_CODE in
1302 -- includes/rts/storage/InfoTables.h.
1303 mkTablesNextToCode :: Bool -> Bool
1304 mkTablesNextToCode unregisterised
1305 = not unregisterised && cGhcEnableTablesNextToCode == "YES"
1306
1307 data DynLibLoader
1308 = Deployable
1309 | SystemDependent
1310 deriving Eq
1311
1312 data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll
1313 deriving (Show)
1314
1315 shouldUseColor :: DynFlags -> Bool
1316 shouldUseColor dflags = overrideWith (canUseColor dflags) (useColor dflags)
1317
1318 -----------------------------------------------------------------------------
1319 -- Ways
1320
1321 -- The central concept of a "way" is that all objects in a given
1322 -- program must be compiled in the same "way". Certain options change
1323 -- parameters of the virtual machine, eg. profiling adds an extra word
1324 -- to the object header, so profiling objects cannot be linked with
1325 -- non-profiling objects.
1326
1327 -- After parsing the command-line options, we determine which "way" we
1328 -- are building - this might be a combination way, eg. profiling+threaded.
1329
1330 -- We then find the "build-tag" associated with this way, and this
1331 -- becomes the suffix used to find .hi files and libraries used in
1332 -- this compilation.
1333
1334 data Way
1335 = WayCustom String -- for GHC API clients building custom variants
1336 | WayThreaded
1337 | WayDebug
1338 | WayProf
1339 | WayEventLog
1340 | WayDyn
1341 deriving (Eq, Ord, Show)
1342
1343 allowed_combination :: [Way] -> Bool
1344 allowed_combination way = and [ x `allowedWith` y
1345 | x <- way, y <- way, x < y ]
1346 where
1347 -- Note ordering in these tests: the left argument is
1348 -- <= the right argument, according to the Ord instance
1349 -- on Way above.
1350
1351 -- dyn is allowed with everything
1352 _ `allowedWith` WayDyn = True
1353 WayDyn `allowedWith` _ = True
1354
1355 -- debug is allowed with everything
1356 _ `allowedWith` WayDebug = True
1357 WayDebug `allowedWith` _ = True
1358
1359 (WayCustom {}) `allowedWith` _ = True
1360 WayThreaded `allowedWith` WayProf = True
1361 WayThreaded `allowedWith` WayEventLog = True
1362 WayProf `allowedWith` WayEventLog = True
1363 _ `allowedWith` _ = False
1364
1365 mkBuildTag :: [Way] -> String
1366 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
1367
1368 wayTag :: Way -> String
1369 wayTag (WayCustom xs) = xs
1370 wayTag WayThreaded = "thr"
1371 wayTag WayDebug = "debug"
1372 wayTag WayDyn = "dyn"
1373 wayTag WayProf = "p"
1374 wayTag WayEventLog = "l"
1375
1376 wayRTSOnly :: Way -> Bool
1377 wayRTSOnly (WayCustom {}) = False
1378 wayRTSOnly WayThreaded = True
1379 wayRTSOnly WayDebug = True
1380 wayRTSOnly WayDyn = False
1381 wayRTSOnly WayProf = False
1382 wayRTSOnly WayEventLog = True
1383
1384 wayDesc :: Way -> String
1385 wayDesc (WayCustom xs) = xs
1386 wayDesc WayThreaded = "Threaded"
1387 wayDesc WayDebug = "Debug"
1388 wayDesc WayDyn = "Dynamic"
1389 wayDesc WayProf = "Profiling"
1390 wayDesc WayEventLog = "RTS Event Logging"
1391
1392 -- Turn these flags on when enabling this way
1393 wayGeneralFlags :: Platform -> Way -> [GeneralFlag]
1394 wayGeneralFlags _ (WayCustom {}) = []
1395 wayGeneralFlags _ WayThreaded = []
1396 wayGeneralFlags _ WayDebug = []
1397 wayGeneralFlags _ WayDyn = [Opt_PIC]
1398 -- We could get away without adding -fPIC when compiling the
1399 -- modules of a program that is to be linked with -dynamic; the
1400 -- program itself does not need to be position-independent, only
1401 -- the libraries need to be. HOWEVER, GHCi links objects into a
1402 -- .so before loading the .so using the system linker. Since only
1403 -- PIC objects can be linked into a .so, we have to compile even
1404 -- modules of the main program with -fPIC when using -dynamic.
1405 wayGeneralFlags _ WayProf = [Opt_SccProfilingOn]
1406 wayGeneralFlags _ WayEventLog = []
1407
1408 -- Turn these flags off when enabling this way
1409 wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag]
1410 wayUnsetGeneralFlags _ (WayCustom {}) = []
1411 wayUnsetGeneralFlags _ WayThreaded = []
1412 wayUnsetGeneralFlags _ WayDebug = []
1413 wayUnsetGeneralFlags _ WayDyn = [-- There's no point splitting objects
1414 -- when we're going to be dynamically
1415 -- linking. Plus it breaks compilation
1416 -- on OSX x86.
1417 Opt_SplitObjs,
1418 -- If splitobjs wasn't useful for this,
1419 -- assume sections aren't either.
1420 Opt_SplitSections]
1421 wayUnsetGeneralFlags _ WayProf = []
1422 wayUnsetGeneralFlags _ WayEventLog = []
1423
1424 wayOptc :: Platform -> Way -> [String]
1425 wayOptc _ (WayCustom {}) = []
1426 wayOptc platform WayThreaded = case platformOS platform of
1427 OSOpenBSD -> ["-pthread"]
1428 OSNetBSD -> ["-pthread"]
1429 _ -> []
1430 wayOptc _ WayDebug = []
1431 wayOptc _ WayDyn = []
1432 wayOptc _ WayProf = ["-DPROFILING"]
1433 wayOptc _ WayEventLog = ["-DTRACING"]
1434
1435 wayOptl :: Platform -> Way -> [String]
1436 wayOptl _ (WayCustom {}) = []
1437 wayOptl platform WayThreaded =
1438 case platformOS platform of
1439 -- FreeBSD's default threading library is the KSE-based M:N libpthread,
1440 -- which GHC has some problems with. It's currently not clear whether
1441 -- the problems are our fault or theirs, but it seems that using the
1442 -- alternative 1:1 threading library libthr works around it:
1443 OSFreeBSD -> ["-lthr"]
1444 OSOpenBSD -> ["-pthread"]
1445 OSNetBSD -> ["-pthread"]
1446 _ -> []
1447 wayOptl _ WayDebug = []
1448 wayOptl _ WayDyn = []
1449 wayOptl _ WayProf = []
1450 wayOptl _ WayEventLog = []
1451
1452 wayOptP :: Platform -> Way -> [String]
1453 wayOptP _ (WayCustom {}) = []
1454 wayOptP _ WayThreaded = []
1455 wayOptP _ WayDebug = []
1456 wayOptP _ WayDyn = []
1457 wayOptP _ WayProf = ["-DPROFILING"]
1458 wayOptP _ WayEventLog = ["-DTRACING"]
1459
1460 whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1461 whenGeneratingDynamicToo dflags f = ifGeneratingDynamicToo dflags f (return ())
1462
1463 ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1464 ifGeneratingDynamicToo dflags f g = generateDynamicTooConditional dflags f g g
1465
1466 whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1467 whenCannotGenerateDynamicToo dflags f
1468 = ifCannotGenerateDynamicToo dflags f (return ())
1469
1470 ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1471 ifCannotGenerateDynamicToo dflags f g
1472 = generateDynamicTooConditional dflags g f g
1473
1474 generateDynamicTooConditional :: MonadIO m
1475 => DynFlags -> m a -> m a -> m a -> m a
1476 generateDynamicTooConditional dflags canGen cannotGen notTryingToGen
1477 = if gopt Opt_BuildDynamicToo dflags
1478 then do let ref = canGenerateDynamicToo dflags
1479 b <- liftIO $ readIORef ref
1480 if b then canGen else cannotGen
1481 else notTryingToGen
1482
1483 dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags
1484 dynamicTooMkDynamicDynFlags dflags0
1485 = let dflags1 = addWay' WayDyn dflags0
1486 dflags2 = dflags1 {
1487 outputFile = dynOutputFile dflags1,
1488 hiSuf = dynHiSuf dflags1,
1489 objectSuf = dynObjectSuf dflags1
1490 }
1491 dflags3 = updateWays dflags2
1492 dflags4 = gopt_unset dflags3 Opt_BuildDynamicToo
1493 in dflags4
1494
1495 -----------------------------------------------------------------------------
1496
1497 -- | Used by 'GHC.runGhc' to partially initialize a new 'DynFlags' value
1498 initDynFlags :: DynFlags -> IO DynFlags
1499 initDynFlags dflags = do
1500 let -- We can't build with dynamic-too on Windows, as labels before
1501 -- the fork point are different depending on whether we are
1502 -- building dynamically or not.
1503 platformCanGenerateDynamicToo
1504 = platformOS (targetPlatform dflags) /= OSMinGW32
1505 refCanGenerateDynamicToo <- newIORef platformCanGenerateDynamicToo
1506 refNextTempSuffix <- newIORef 0
1507 refFilesToClean <- newIORef []
1508 refDirsToClean <- newIORef Map.empty
1509 refFilesToNotIntermediateClean <- newIORef []
1510 refGeneratedDumps <- newIORef Set.empty
1511 refRtldInfo <- newIORef Nothing
1512 refRtccInfo <- newIORef Nothing
1513 wrapperNum <- newIORef emptyModuleEnv
1514 canUseUnicode <- do let enc = localeEncoding
1515 str = "‘’"
1516 (withCString enc str $ \cstr ->
1517 do str' <- peekCString enc cstr
1518 return (str == str'))
1519 `catchIOError` \_ -> return False
1520 canUseColor <- stderrSupportsAnsiColors
1521 maybeGhcColorsEnv <- lookupEnv "GHC_COLORS"
1522 maybeGhcColoursEnv <- lookupEnv "GHC_COLOURS"
1523 let adjustCols (Just env) = Col.parseScheme env
1524 adjustCols Nothing = id
1525 let (useColor', colScheme') =
1526 (adjustCols maybeGhcColoursEnv . adjustCols maybeGhcColorsEnv)
1527 (useColor dflags, colScheme dflags)
1528 return dflags{
1529 canGenerateDynamicToo = refCanGenerateDynamicToo,
1530 nextTempSuffix = refNextTempSuffix,
1531 filesToClean = refFilesToClean,
1532 dirsToClean = refDirsToClean,
1533 filesToNotIntermediateClean = refFilesToNotIntermediateClean,
1534 generatedDumps = refGeneratedDumps,
1535 nextWrapperNum = wrapperNum,
1536 useUnicode = canUseUnicode,
1537 useColor = useColor',
1538 canUseColor = canUseColor,
1539 colScheme = colScheme',
1540 rtldInfo = refRtldInfo,
1541 rtccInfo = refRtccInfo
1542 }
1543
1544 -- | The normal 'DynFlags'. Note that they are not suitable for use in this form
1545 -- and must be fully initialized by 'GHC.runGhc' first.
1546 defaultDynFlags :: Settings -> DynFlags
1547 defaultDynFlags mySettings =
1548 -- See Note [Updating flag description in the User's Guide]
1549 DynFlags {
1550 ghcMode = CompManager,
1551 ghcLink = LinkBinary,
1552 hscTarget = defaultHscTarget (sTargetPlatform mySettings),
1553 verbosity = 0,
1554 optLevel = 0,
1555 debugLevel = 0,
1556 simplPhases = 2,
1557 maxSimplIterations = 4,
1558 maxPmCheckIterations = 2000000,
1559 ruleCheck = Nothing,
1560 maxRelevantBinds = Just 6,
1561 maxValidSubstitutions = Just 6,
1562 maxUncoveredPatterns = 4,
1563 simplTickFactor = 100,
1564 specConstrThreshold = Just 2000,
1565 specConstrCount = Just 3,
1566 specConstrRecursive = 3,
1567 liberateCaseThreshold = Just 2000,
1568 floatLamArgs = Just 0, -- Default: float only if no fvs
1569
1570 historySize = 20,
1571 strictnessBefore = [],
1572
1573 parMakeCount = Just 1,
1574
1575 enableTimeStats = False,
1576 ghcHeapSize = Nothing,
1577
1578 importPaths = ["."],
1579 mainModIs = mAIN,
1580 mainFunIs = Nothing,
1581 reductionDepth = treatZeroAsInf mAX_REDUCTION_DEPTH,
1582 solverIterations = treatZeroAsInf mAX_SOLVER_ITERATIONS,
1583
1584 thisInstalledUnitId = toInstalledUnitId mainUnitId,
1585 thisUnitIdInsts_ = Nothing,
1586 thisComponentId_ = Nothing,
1587
1588 objectDir = Nothing,
1589 dylibInstallName = Nothing,
1590 hiDir = Nothing,
1591 stubDir = Nothing,
1592 dumpDir = Nothing,
1593
1594 objectSuf = phaseInputExt StopLn,
1595 hcSuf = phaseInputExt HCc,
1596 hiSuf = "hi",
1597
1598 canGenerateDynamicToo = panic "defaultDynFlags: No canGenerateDynamicToo",
1599 dynObjectSuf = "dyn_" ++ phaseInputExt StopLn,
1600 dynHiSuf = "dyn_hi",
1601
1602 dllSplitFile = Nothing,
1603 dllSplit = Nothing,
1604
1605 pluginModNames = [],
1606 pluginModNameOpts = [],
1607 frontendPluginOpts = [],
1608 hooks = emptyHooks,
1609
1610 outputFile = Nothing,
1611 dynOutputFile = Nothing,
1612 outputHi = Nothing,
1613 dynLibLoader = SystemDependent,
1614 dumpPrefix = Nothing,
1615 dumpPrefixForce = Nothing,
1616 ldInputs = [],
1617 includePaths = [],
1618 libraryPaths = [],
1619 frameworkPaths = [],
1620 cmdlineFrameworks = [],
1621 rtsOpts = Nothing,
1622 rtsOptsEnabled = RtsOptsSafeOnly,
1623 rtsOptsSuggestions = True,
1624
1625 hpcDir = ".hpc",
1626
1627 packageDBFlags = [],
1628 packageFlags = [],
1629 pluginPackageFlags = [],
1630 ignorePackageFlags = [],
1631 trustFlags = [],
1632 packageEnv = Nothing,
1633 pkgDatabase = Nothing,
1634 -- This gets filled in with GHC.setSessionDynFlags
1635 pkgState = emptyPackageState,
1636 ways = defaultWays mySettings,
1637 buildTag = mkBuildTag (defaultWays mySettings),
1638 rtsBuildTag = mkBuildTag (defaultWays mySettings),
1639 splitInfo = Nothing,
1640 settings = mySettings,
1641 -- ghc -M values
1642 depMakefile = "Makefile",
1643 depIncludePkgDeps = False,
1644 depExcludeMods = [],
1645 depSuffixes = [],
1646 -- end of ghc -M values
1647 nextTempSuffix = panic "defaultDynFlags: No nextTempSuffix",
1648 filesToClean = panic "defaultDynFlags: No filesToClean",
1649 dirsToClean = panic "defaultDynFlags: No dirsToClean",
1650 filesToNotIntermediateClean = panic "defaultDynFlags: No filesToNotIntermediateClean",
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], [Located String])
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], [Located String])
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], [Located String])
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 $
2383 errorsToGhcException . map (showPpr dflags0 . getLoc &&& unLoc) $ 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 return (dflags7, leftover, consistency_warnings ++ sh_warns ++ warns)
2431
2432 setLogAction :: DynFlags -> IO DynFlags
2433 setLogAction dflags = do
2434 mlogger <- initLogAction dflags
2435 return $
2436 maybe
2437 dflags
2438 (\logger ->
2439 dflags
2440 { log_action = getLogAction logger
2441 , log_finaliser = getLogFinaliser logger
2442 , initLogAction = return $ Nothing -- Don't initialise it twice
2443 })
2444 mlogger
2445
2446 -- | Write an error or warning to the 'LogOutput'.
2447 putLogMsg :: DynFlags -> WarnReason -> Severity -> SrcSpan -> PprStyle
2448 -> MsgDoc -> IO ()
2449 putLogMsg dflags = log_action dflags dflags
2450
2451 updateWays :: DynFlags -> DynFlags
2452 updateWays dflags
2453 = let theWays = sort $ nub $ ways dflags
2454 in dflags {
2455 ways = theWays,
2456 buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays),
2457 rtsBuildTag = mkBuildTag theWays
2458 }
2459
2460 -- | Check (and potentially disable) any extensions that aren't allowed
2461 -- in safe mode.
2462 --
2463 -- The bool is to indicate if we are parsing command line flags (false means
2464 -- file pragma). This allows us to generate better warnings.
2465 safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
2466 safeFlagCheck _ dflags | safeLanguageOn dflags = (dflagsUnset, warns)
2467 where
2468 -- Handle illegal flags under safe language.
2469 (dflagsUnset, warns) = foldl check_method (dflags, []) unsafeFlags
2470
2471 check_method (df, warns) (str,loc,test,fix)
2472 | test df = (fix df, warns ++ safeFailure (loc df) str)
2473 | otherwise = (df, warns)
2474
2475 safeFailure loc str
2476 = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring "
2477 ++ str]
2478
2479 safeFlagCheck cmdl dflags =
2480 case (safeInferOn dflags) of
2481 True | safeFlags -> (dflags', warn)
2482 True -> (dflags' { safeInferred = False }, warn)
2483 False -> (dflags', warn)
2484
2485 where
2486 -- dynflags and warn for when -fpackage-trust by itself with no safe
2487 -- haskell flag
2488 (dflags', warn)
2489 | safeHaskell dflags == Sf_None && not cmdl && packageTrustOn dflags
2490 = (gopt_unset dflags Opt_PackageTrust, pkgWarnMsg)
2491 | otherwise = (dflags, [])
2492
2493 pkgWarnMsg = [L (pkgTrustOnLoc dflags') $
2494 "-fpackage-trust ignored;" ++
2495 " must be specified with a Safe Haskell flag"]
2496
2497 -- Have we inferred Unsafe? See Note [HscMain . Safe Haskell Inference]
2498 safeFlags = all (\(_,_,t,_) -> not $ t dflags) unsafeFlagsForInfer
2499
2500
2501 {- **********************************************************************
2502 %* *
2503 DynFlags specifications
2504 %* *
2505 %********************************************************************* -}
2506
2507 -- | All dynamic flags option strings without the deprecated ones.
2508 -- These are the user facing strings for enabling and disabling options.
2509 allNonDeprecatedFlags :: [String]
2510 allNonDeprecatedFlags = allFlagsDeps False
2511
2512 -- | All flags with possibility to filter deprecated ones
2513 allFlagsDeps :: Bool -> [String]
2514 allFlagsDeps keepDeprecated = [ '-':flagName flag
2515 | (deprecated, flag) <- flagsAllDeps
2516 , ok (flagOptKind flag)
2517 , keepDeprecated || not (isDeprecated deprecated)]
2518 where ok (PrefixPred _ _) = False
2519 ok _ = True
2520 isDeprecated Deprecated = True
2521 isDeprecated _ = False
2522
2523 {-
2524 - Below we export user facing symbols for GHC dynamic flags for use with the
2525 - GHC API.
2526 -}
2527
2528 -- All dynamic flags present in GHC.
2529 flagsAll :: [Flag (CmdLineP DynFlags)]
2530 flagsAll = map snd flagsAllDeps
2531
2532 -- All dynamic flags present in GHC with deprecation information.
2533 flagsAllDeps :: [(Deprecation, Flag (CmdLineP DynFlags))]
2534 flagsAllDeps = package_flags_deps ++ dynamic_flags_deps
2535
2536
2537 -- All dynamic flags, minus package flags, present in GHC.
2538 flagsDynamic :: [Flag (CmdLineP DynFlags)]
2539 flagsDynamic = map snd dynamic_flags_deps
2540
2541 -- ALl package flags present in GHC.
2542 flagsPackage :: [Flag (CmdLineP DynFlags)]
2543 flagsPackage = map snd package_flags_deps
2544
2545 ----------------Helpers to make flags and keep deprecation information----------
2546
2547 type FlagMaker m = String -> OptKind m -> Flag m
2548 type DynFlagMaker = FlagMaker (CmdLineP DynFlags)
2549 data Deprecation = NotDeprecated | Deprecated deriving (Eq, Ord)
2550
2551 -- Make a non-deprecated flag
2552 make_ord_flag :: DynFlagMaker -> String -> OptKind (CmdLineP DynFlags)
2553 -> (Deprecation, Flag (CmdLineP DynFlags))
2554 make_ord_flag fm name kind = (NotDeprecated, fm name kind)
2555
2556 -- Make a deprecated flag
2557 make_dep_flag :: DynFlagMaker -> String -> OptKind (CmdLineP DynFlags) -> String
2558 -> (Deprecation, Flag (CmdLineP DynFlags))
2559 make_dep_flag fm name kind message = (Deprecated,
2560 fm name $ add_dep_message kind message)
2561
2562 add_dep_message :: OptKind (CmdLineP DynFlags) -> String
2563 -> OptKind (CmdLineP DynFlags)
2564 add_dep_message (NoArg f) message = NoArg $ f >> deprecate message
2565 add_dep_message (HasArg f) message = HasArg $ \s -> f s >> deprecate message
2566 add_dep_message (SepArg f) message = SepArg $ \s -> f s >> deprecate message
2567 add_dep_message (Prefix f) message = Prefix $ \s -> f s >> deprecate message
2568 add_dep_message (OptPrefix f) message =
2569 OptPrefix $ \s -> f s >> deprecate message
2570 add_dep_message (OptIntSuffix f) message =
2571 OptIntSuffix $ \oi -> f oi >> deprecate message
2572 add_dep_message (IntSuffix f) message =
2573 IntSuffix $ \i -> f i >> deprecate message
2574 add_dep_message (FloatSuffix f) message =
2575 FloatSuffix $ \fl -> f fl >> deprecate message
2576 add_dep_message (PassFlag f) message =
2577 PassFlag $ \s -> f s >> deprecate message
2578 add_dep_message (AnySuffix f) message =
2579 AnySuffix $ \s -> f s >> deprecate message
2580 add_dep_message (PrefixPred pred f) message =
2581 PrefixPred pred $ \s -> f s >> deprecate message
2582 add_dep_message (AnySuffixPred pred f) message =
2583 AnySuffixPred pred $ \s -> f s >> deprecate message
2584
2585 ----------------------- The main flags themselves ------------------------------
2586 -- See Note [Updating flag description in the User's Guide]
2587 -- See Note [Supporting CLI completion]
2588 dynamic_flags_deps :: [(Deprecation, Flag (CmdLineP DynFlags))]
2589 dynamic_flags_deps = [
2590 make_dep_flag defFlag "n" (NoArg $ return ())
2591 "The -n flag is deprecated and no longer has any effect"
2592 , make_ord_flag defFlag "cpp" (NoArg (setExtensionFlag LangExt.Cpp))
2593 , make_ord_flag defFlag "F" (NoArg (setGeneralFlag Opt_Pp))
2594 , (Deprecated, defFlag "#include"
2595 (HasArg (\_s ->
2596 addWarn ("-#include and INCLUDE pragmas are " ++
2597 "deprecated: They no longer have any effect"))))
2598 , make_ord_flag defFlag "v" (OptIntSuffix setVerbosity)
2599
2600 , make_ord_flag defGhcFlag "j" (OptIntSuffix
2601 (\n -> case n of
2602 Just n
2603 | n > 0 -> upd (\d -> d { parMakeCount = Just n })
2604 | otherwise -> addErr "Syntax: -j[n] where n > 0"
2605 Nothing -> upd (\d -> d { parMakeCount = Nothing })))
2606 -- When the number of parallel builds
2607 -- is omitted, it is the same
2608 -- as specifing that the number of
2609 -- parallel builds is equal to the
2610 -- result of getNumProcessors
2611 , make_ord_flag defFlag "instantiated-with" (sepArg setUnitIdInsts)
2612 , make_ord_flag defFlag "this-component-id" (sepArg setComponentId)
2613
2614 -- RTS options -------------------------------------------------------------
2615 , make_ord_flag defFlag "H" (HasArg (\s -> upd (\d ->
2616 d { ghcHeapSize = Just $ fromIntegral (decodeSize s)})))
2617
2618 , make_ord_flag defFlag "Rghc-timing" (NoArg (upd (\d ->
2619 d { enableTimeStats = True })))
2620
2621 ------- ways ---------------------------------------------------------------
2622 , make_ord_flag defGhcFlag "prof" (NoArg (addWay WayProf))
2623 , make_ord_flag defGhcFlag "eventlog" (NoArg (addWay WayEventLog))
2624 , make_dep_flag defGhcFlag "smp"
2625 (NoArg $ addWay WayThreaded) "Use -threaded instead"
2626 , make_ord_flag defGhcFlag "debug" (NoArg (addWay WayDebug))
2627 , make_ord_flag defGhcFlag "threaded" (NoArg (addWay WayThreaded))
2628
2629 , make_ord_flag defGhcFlag "ticky"
2630 (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug))
2631
2632 -- -ticky enables ticky-ticky code generation, and also implies -debug which
2633 -- is required to get the RTS ticky support.
2634
2635 ----- Linker --------------------------------------------------------
2636 , make_ord_flag defGhcFlag "static" (NoArg removeWayDyn)
2637 , make_ord_flag defGhcFlag "dynamic" (NoArg (addWay WayDyn))
2638 , make_ord_flag defGhcFlag "rdynamic" $ noArg $
2639 #if defined(linux_HOST_OS)
2640 addOptl "-rdynamic"
2641 #elif defined (mingw32_HOST_OS)
2642 addOptl "-Wl,--export-all-symbols"
2643 #else
2644 -- ignored for compat w/ gcc:
2645 id
2646 #endif
2647 , make_ord_flag defGhcFlag "relative-dynlib-paths"
2648 (NoArg (setGeneralFlag Opt_RelativeDynlibPaths))
2649
2650 ------- Specific phases --------------------------------------------
2651 -- need to appear before -pgmL to be parsed as LLVM flags.
2652 , make_ord_flag defFlag "pgmlo"
2653 (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
2654 , make_ord_flag defFlag "pgmlc"
2655 (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
2656 , make_ord_flag defFlag "pgmi"
2657 (hasArg (\f -> alterSettings (\s -> s { sPgm_i = f})))
2658 , make_ord_flag defFlag "pgmL"
2659 (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
2660 , make_ord_flag defFlag "pgmP"
2661 (hasArg setPgmP)
2662 , make_ord_flag defFlag "pgmF"
2663 (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
2664 , make_ord_flag defFlag "pgmc"
2665 (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])})))
2666 , make_ord_flag defFlag "pgms"
2667 (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])})))
2668 , make_ord_flag defFlag "pgma"
2669 (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
2670 , make_ord_flag defFlag "pgml"
2671 (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
2672 , make_ord_flag defFlag "pgmdll"
2673 (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
2674 , make_ord_flag defFlag "pgmwindres"
2675 (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
2676 , make_ord_flag defFlag "pgmlibtool"
2677 (hasArg (\f -> alterSettings (\s -> s { sPgm_libtool = f})))
2678
2679 -- need to appear before -optl/-opta to be parsed as LLVM flags.
2680 , make_ord_flag defFlag "optlo"
2681 (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
2682 , make_ord_flag defFlag "optlc"
2683 (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
2684 , make_ord_flag defFlag "opti"
2685 (hasArg (\f -> alterSettings (\s -> s { sOpt_i = f : sOpt_i s})))
2686 , make_ord_flag defFlag "optL"
2687 (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
2688 , make_ord_flag defFlag "optP"
2689 (hasArg addOptP)
2690 , make_ord_flag defFlag "optF"
2691 (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
2692 , make_ord_flag defFlag "optc"
2693 (hasArg addOptc)
2694 , make_ord_flag defFlag "opta"
2695 (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
2696 , make_ord_flag defFlag "optl"
2697 (hasArg addOptl)
2698 , make_ord_flag defFlag "optwindres"
2699 (hasArg (\f ->
2700 alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
2701
2702 , make_ord_flag defGhcFlag "split-objs"
2703 (NoArg (if can_split
2704 then setGeneralFlag Opt_SplitObjs
2705 else addWarn "ignoring -split-objs"))
2706
2707 , make_ord_flag defGhcFlag "split-sections"
2708 (noArgM (\dflags -> do
2709 if platformHasSubsectionsViaSymbols (targetPlatform dflags)
2710 then do addErr $
2711 "-split-sections is not useful on this platform " ++
2712 "since it always uses subsections via symbols."
2713 return dflags
2714 else return (gopt_set dflags Opt_SplitSections)))
2715
2716 -------- ghc -M -----------------------------------------------------
2717 , make_ord_flag defGhcFlag "dep-suffix" (hasArg addDepSuffix)
2718 , make_ord_flag defGhcFlag "dep-makefile" (hasArg setDepMakefile)
2719 , make_ord_flag defGhcFlag "include-pkg-deps"
2720 (noArg (setDepIncludePkgDeps True))
2721 , make_ord_flag defGhcFlag "exclude-module" (hasArg addDepExcludeMod)
2722
2723 -------- Linking ----------------------------------------------------
2724 , make_ord_flag defGhcFlag "no-link"
2725 (noArg (\d -> d { ghcLink=NoLink }))
2726 , make_ord_flag defGhcFlag "shared"
2727 (noArg (\d -> d { ghcLink=LinkDynLib }))
2728 , make_ord_flag defGhcFlag "staticlib"
2729 (noArg (\d -> d { ghcLink=LinkStaticLib }))
2730 , make_ord_flag defGhcFlag "dynload" (hasArg parseDynLibLoaderMode)
2731 , make_ord_flag defGhcFlag "dylib-install-name" (hasArg setDylibInstallName)
2732 -- -dll-split is an internal flag, used only during the GHC build
2733 , make_ord_flag defHiddenFlag "dll-split"
2734 (hasArg (\f d -> d { dllSplitFile = Just f, dllSplit = Nothing }))
2735
2736 ------- Libraries ---------------------------------------------------
2737 , make_ord_flag defFlag "L" (Prefix addLibraryPath)
2738 , make_ord_flag defFlag "l" (hasArg (addLdInputs . Option . ("-l" ++)))
2739
2740 ------- Frameworks --------------------------------------------------
2741 -- -framework-path should really be -F ...
2742 , make_ord_flag defFlag "framework-path" (HasArg addFrameworkPath)
2743 , make_ord_flag defFlag "framework" (hasArg addCmdlineFramework)
2744
2745 ------- Output Redirection ------------------------------------------
2746 , make_ord_flag defGhcFlag "odir" (hasArg setObjectDir)
2747 , make_ord_flag defGhcFlag "o" (sepArg (setOutputFile . Just))
2748 , make_ord_flag defGhcFlag "dyno"
2749 (sepArg (setDynOutputFile . Just))
2750 , make_ord_flag defGhcFlag "ohi"
2751 (hasArg (setOutputHi . Just ))
2752 , make_ord_flag defGhcFlag "osuf" (hasArg setObjectSuf)
2753 , make_ord_flag defGhcFlag "dynosuf" (hasArg setDynObjectSuf)
2754 , make_ord_flag defGhcFlag "hcsuf" (hasArg setHcSuf)
2755 , make_ord_flag defGhcFlag "hisuf" (hasArg setHiSuf)
2756 , make_ord_flag defGhcFlag "dynhisuf" (hasArg setDynHiSuf)
2757 , make_ord_flag defGhcFlag "hidir" (hasArg setHiDir)
2758 , make_ord_flag defGhcFlag "tmpdir" (hasArg setTmpDir)
2759 , make_ord_flag defGhcFlag "stubdir" (hasArg setStubDir)
2760 , make_ord_flag defGhcFlag "dumpdir" (hasArg setDumpDir)
2761 , make_ord_flag defGhcFlag "outputdir" (hasArg setOutputDir)
2762 , make_ord_flag defGhcFlag "ddump-file-prefix"
2763 (hasArg (setDumpPrefixForce . Just))
2764
2765 , make_ord_flag defGhcFlag "dynamic-too"
2766 (NoArg (setGeneralFlag Opt_BuildDynamicToo))
2767
2768 ------- Keeping temporary files -------------------------------------
2769 -- These can be singular (think ghc -c) or plural (think ghc --make)
2770 , make_ord_flag defGhcFlag "keep-hc-file"
2771 (NoArg (setGeneralFlag Opt_KeepHcFiles))
2772 , make_ord_flag defGhcFlag "keep-hc-files"
2773 (NoArg (setGeneralFlag Opt_KeepHcFiles))
2774 , make_ord_flag defGhcFlag "keep-s-file"
2775 (NoArg (setGeneralFlag Opt_KeepSFiles))
2776 , make_ord_flag defGhcFlag "keep-s-files"
2777 (NoArg (setGeneralFlag Opt_KeepSFiles))
2778 , make_ord_flag defGhcFlag "keep-llvm-file"
2779 (NoArg $ setObjTarget HscLlvm >> setGeneralFlag Opt_KeepLlvmFiles)
2780 , make_ord_flag defGhcFlag "keep-llvm-files"
2781 (NoArg $ setObjTarget HscLlvm >> setGeneralFlag Opt_KeepLlvmFiles)
2782 -- This only makes sense as plural
2783 , make_ord_flag defGhcFlag "keep-tmp-files"
2784 (NoArg (setGeneralFlag Opt_KeepTmpFiles))
2785 , make_ord_flag defGhcFlag "keep-hi-file"
2786 (NoArg (setGeneralFlag Opt_KeepHiFiles))
2787 , make_ord_flag defGhcFlag "no-keep-hi-file"
2788 (NoArg (unSetGeneralFlag Opt_KeepHiFiles))
2789 , make_ord_flag defGhcFlag "keep-hi-files"
2790 (NoArg (setGeneralFlag Opt_KeepHiFiles))
2791 , make_ord_flag defGhcFlag "no-keep-hi-files"
2792 (NoArg (unSetGeneralFlag Opt_KeepHiFiles))
2793 , make_ord_flag defGhcFlag "keep-o-file"
2794 (NoArg (setGeneralFlag Opt_KeepOFiles))
2795 , make_ord_flag defGhcFlag "no-keep-o-file"
2796 (NoArg (unSetGeneralFlag Opt_KeepOFiles))
2797 , make_ord_flag defGhcFlag "keep-o-files"
2798 (NoArg (setGeneralFlag Opt_KeepOFiles))
2799 , make_ord_flag defGhcFlag "no-keep-o-files"
2800 (NoArg (unSetGeneralFlag Opt_KeepOFiles))
2801
2802 ------- Miscellaneous ----------------------------------------------
2803 , make_ord_flag defGhcFlag "no-auto-link-packages"
2804 (NoArg (unSetGeneralFlag Opt_AutoLinkPackages))
2805 , make_ord_flag defGhcFlag "no-hs-main"
2806 (NoArg (setGeneralFlag Opt_NoHsMain))
2807 , make_ord_flag defGhcFlag "fno-state-hack"
2808 (NoArg (setGeneralFlag Opt_G_NoStateHack))
2809 , make_ord_flag defGhcFlag "fno-opt-coercion"
2810 (NoArg (setGeneralFlag Opt_G_NoOptCoercion))
2811 , make_ord_flag defGhcFlag "with-rtsopts"
2812 (HasArg setRtsOpts)
2813 , make_ord_flag defGhcFlag "rtsopts"
2814 (NoArg (setRtsOptsEnabled RtsOptsAll))
2815 , make_ord_flag defGhcFlag "rtsopts=all"
2816 (NoArg (setRtsOptsEnabled RtsOptsAll))
2817 , make_ord_flag defGhcFlag "rtsopts=some"
2818 (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
2819 , make_ord_flag defGhcFlag "rtsopts=none"
2820 (NoArg (setRtsOptsEnabled RtsOptsNone))
2821 , make_ord_flag defGhcFlag "no-rtsopts"
2822 (NoArg (setRtsOptsEnabled RtsOptsNone))
2823 , make_ord_flag defGhcFlag "no-rtsopts-suggestions"
2824 (noArg (\d -> d {rtsOptsSuggestions = False}))
2825
2826 , make_ord_flag defGhcFlag "main-is" (SepArg setMainIs)
2827 , make_ord_flag defGhcFlag "haddock" (NoArg (setGeneralFlag Opt_Haddock))
2828 , make_ord_flag defGhcFlag "haddock-opts" (hasArg addHaddockOpts)
2829 , make_ord_flag defGhcFlag "hpcdir" (SepArg setOptHpcDir)
2830 , make_ord_flag defGhciFlag "ghci-script" (hasArg addGhciScript)
2831 , make_ord_flag defGhciFlag "interactive-print" (hasArg setInteractivePrint)
2832 , make_ord_flag defGhcFlag "ticky-allocd"
2833 (NoArg (setGeneralFlag Opt_Ticky_Allocd))
2834 , make_ord_flag defGhcFlag "ticky-LNE"
2835 (NoArg (setGeneralFlag Opt_Ticky_LNE))
2836 , make_ord_flag defGhcFlag "ticky-dyn-thunk"
2837 (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk))
2838 ------- recompilation checker --------------------------------------
2839 , make_dep_flag defGhcFlag "recomp"
2840 (NoArg $ unSetGeneralFlag Opt_ForceRecomp)
2841 "Use -fno-force-recomp instead"
2842 , make_dep_flag defGhcFlag "no-recomp"
2843 (NoArg $ setGeneralFlag Opt_ForceRecomp) "Use -fforce-recomp instead"
2844 , make_ord_flag defFlag "fmax-errors"
2845 (intSuffix (\n d -> d { maxErrors = Just (max 1 n) }))
2846 , make_ord_flag defFlag "fno-max-errors"
2847 (noArg (\d -> d { maxErrors = Nothing }))
2848 , make_ord_flag defFlag "freverse-errors"
2849 (noArg (\d -> d {reverseErrors = True} ))
2850 , make_ord_flag defFlag "fno-reverse-errors"
2851 (noArg (\d -> d {reverseErrors = False} ))
2852
2853 ------ HsCpp opts ---------------------------------------------------
2854 , make_ord_flag defFlag "D" (AnySuffix (upd . addOptP))
2855 , make_ord_flag defFlag "U" (AnySuffix (upd . addOptP))
2856
2857 ------- Include/Import Paths ----------------------------------------
2858 , make_ord_flag defFlag "I" (Prefix addIncludePath)
2859 , make_ord_flag defFlag "i" (OptPrefix addImportPath)
2860
2861 ------ Output style options -----------------------------------------
2862 , make_ord_flag defFlag "dppr-user-length" (intSuffix (\n d ->
2863 d { pprUserLength = n }))
2864 , make_ord_flag defFlag "dppr-cols" (intSuffix (\n d ->
2865 d { pprCols = n }))
2866 , make_ord_flag defFlag "fdiagnostics-color=auto"
2867 (NoArg (upd (\d -> d { useColor = Auto })))
2868 , make_ord_flag defFlag "fdiagnostics-color=always"
2869 (NoArg (upd (\d -> d { useColor = Always })))
2870 , make_ord_flag defFlag "fdiagnostics-color=never"
2871 (NoArg (upd (\d -> d { useColor = Never })))
2872
2873 -- Suppress all that is suppressable in core dumps.
2874 -- Except for uniques, as some simplifier phases introduce new variables that
2875 -- have otherwise identical names.
2876 , make_ord_flag defGhcFlag "dsuppress-all"
2877 (NoArg $ do setGeneralFlag Opt_SuppressCoercions
2878 setGeneralFlag Opt_SuppressVarKinds
2879 setGeneralFlag Opt_SuppressModulePrefixes
2880 setGeneralFlag Opt_SuppressTypeApplications
2881 setGeneralFlag Opt_SuppressIdInfo
2882 setGeneralFlag Opt_SuppressTicks
2883 setGeneralFlag Opt_SuppressTypeSignatures)
2884
2885 ------ Debugging ----------------------------------------------------
2886 , make_ord_flag defGhcFlag "dstg-stats"
2887 (NoArg (setGeneralFlag Opt_StgStats))
2888
2889 , make_ord_flag defGhcFlag "ddump-cmm"
2890 (setDumpFlag Opt_D_dump_cmm)
2891 , make_ord_flag defGhcFlag "ddump-cmm-from-stg"
2892 (setDumpFlag Opt_D_dump_cmm_from_stg)
2893 , make_ord_flag defGhcFlag "ddump-cmm-raw"
2894 (setDumpFlag Opt_D_dump_cmm_raw)
2895 , make_ord_flag defGhcFlag "ddump-cmm-verbose"
2896 (setDumpFlag Opt_D_dump_cmm_verbose)
2897 , make_ord_flag defGhcFlag "ddump-cmm-cfg"
2898 (setDumpFlag Opt_D_dump_cmm_cfg)
2899 , make_ord_flag defGhcFlag "ddump-cmm-cbe"
2900 (setDumpFlag Opt_D_dump_cmm_cbe)
2901 , make_ord_flag defGhcFlag "ddump-cmm-switch"
2902 (setDumpFlag Opt_D_dump_cmm_switch)
2903 , make_ord_flag defGhcFlag "ddump-cmm-proc"
2904 (setDumpFlag Opt_D_dump_cmm_proc)
2905 , make_ord_flag defGhcFlag "ddump-cmm-sp"
2906 (setDumpFlag Opt_D_dump_cmm_sp)
2907 , make_ord_flag defGhcFlag "ddump-cmm-sink"
2908 (setDumpFlag Opt_D_dump_cmm_sink)
2909 , make_ord_flag defGhcFlag "ddump-cmm-caf"
2910 (setDumpFlag Opt_D_dump_cmm_caf)
2911 , make_ord_flag defGhcFlag "ddump-cmm-procmap"
2912 (setDumpFlag Opt_D_dump_cmm_procmap)
2913 , make_ord_flag defGhcFlag "ddump-cmm-split"
2914 (setDumpFlag Opt_D_dump_cmm_split)
2915 , make_ord_flag defGhcFlag "ddump-cmm-info"
2916 (setDumpFlag Opt_D_dump_cmm_info)
2917 , make_ord_flag defGhcFlag "ddump-cmm-cps"
2918 (setDumpFlag Opt_D_dump_cmm_cps)
2919 , make_ord_flag defGhcFlag "ddump-core-stats"
2920 (setDumpFlag Opt_D_dump_core_stats)
2921 , make_ord_flag defGhcFlag "ddump-asm"
2922 (setDumpFlag Opt_D_dump_asm)
2923 , make_ord_flag defGhcFlag "ddump-asm-native"
2924 (setDumpFlag Opt_D_dump_asm_native)
2925 , make_ord_flag defGhcFlag "ddump-asm-liveness"
2926 (setDumpFlag Opt_D_dump_asm_liveness)
2927 , make_ord_flag defGhcFlag "ddump-asm-regalloc"
2928 (setDumpFlag Opt_D_dump_asm_regalloc)
2929 , make_ord_flag defGhcFlag "ddump-asm-conflicts"
2930 (setDumpFlag Opt_D_dump_asm_conflicts)
2931 , make_ord_flag defGhcFlag "ddump-asm-regalloc-stages"
2932 (setDumpFlag Opt_D_dump_asm_regalloc_stages)
2933 , make_ord_flag defGhcFlag "ddump-asm-stats"
2934 (setDumpFlag Opt_D_dump_asm_stats)
2935 , make_ord_flag defGhcFlag "ddump-asm-expanded"
2936 (setDumpFlag Opt_D_dump_asm_expanded)
2937 , make_ord_flag defGhcFlag "ddump-llvm"
2938 (NoArg $ setObjTarget HscLlvm >> setDumpFlag' Opt_D_dump_llvm)
2939 , make_ord_flag defGhcFlag "ddump-deriv"
2940 (setDumpFlag Opt_D_dump_deriv)
2941 , make_ord_flag defGhcFlag "ddump-ds"
2942 (setDumpFlag Opt_D_dump_ds)
2943 , make_ord_flag defGhcFlag "ddump-foreign"
2944 (setDumpFlag Opt_D_dump_foreign)
2945 , make_ord_flag defGhcFlag "ddump-inlinings"
2946 (setDumpFlag Opt_D_dump_inlinings)
2947 , make_ord_flag defGhcFlag "ddump-rule-firings"
2948 (setDumpFlag Opt_D_dump_rule_firings)
2949 , make_ord_flag defGhcFlag "ddump-rule-rewrites"
2950 (setDumpFlag Opt_D_dump_rule_rewrites)
2951 , make_ord_flag defGhcFlag "ddump-simpl-trace"
2952 (setDumpFlag Opt_D_dump_simpl_trace)
2953 , make_ord_flag defGhcFlag "ddump-occur-anal"
2954 (setDumpFlag Opt_D_dump_occur_anal)
2955 , make_ord_flag defGhcFlag "ddump-parsed"
2956 (setDumpFlag Opt_D_dump_parsed)
2957 , make_ord_flag defGhcFlag "ddump-parsed-ast"
2958 (setDumpFlag Opt_D_dump_parsed_ast)
2959 , make_ord_flag defGhcFlag "ddump-rn"
2960 (setDumpFlag Opt_D_dump_rn)
2961 , make_ord_flag defGhcFlag "ddump-rn-ast"
2962 (setDumpFlag Opt_D_dump_rn_ast)
2963 , make_ord_flag defGhcFlag "ddump-simpl"
2964 (setDumpFlag Opt_D_dump_simpl)
2965 , make_ord_flag defGhcFlag "ddump-simpl-iterations"
2966 (setDumpFlag Opt_D_dump_simpl_iterations)
2967 , make_ord_flag defGhcFlag "ddump-spec"
2968 (setDumpFlag Opt_D_dump_spec)
2969 , make_ord_flag defGhcFlag "ddump-prep"
2970 (setDumpFlag Opt_D_dump_prep)
2971 , make_ord_flag defGhcFlag "ddump-stg"
2972 (setDumpFlag Opt_D_dump_stg)
2973 , make_ord_flag defGhcFlag "ddump-call-arity"
2974 (setDumpFlag Opt_D_dump_call_arity)
2975 , make_ord_flag defGhcFlag "ddump-stranal"
2976 (setDumpFlag Opt_D_dump_stranal)
2977 , make_ord_flag defGhcFlag "ddump-str-signatures"
2978 (setDumpFlag Opt_D_dump_str_signatures)
2979 , make_ord_flag defGhcFlag "ddump-tc"
2980 (setDumpFlag Opt_D_dump_tc)
2981 , make_ord_flag defGhcFlag "ddump-tc-ast"
2982 (setDumpFlag Opt_D_dump_tc_ast)
2983 , make_ord_flag defGhcFlag "ddump-types"
2984 (setDumpFlag Opt_D_dump_types)
2985 , make_ord_flag defGhcFlag "ddump-rules"
2986 (setDumpFlag Opt_D_dump_rules)
2987 , make_ord_flag defGhcFlag "ddump-cse"
2988 (setDumpFlag Opt_D_dump_cse)
2989 , make_ord_flag defGhcFlag "ddump-worker-wrapper"
2990 (setDumpFlag Opt_D_dump_worker_wrapper)
2991 , make_ord_flag defGhcFlag "ddump-rn-trace"
2992 (setDumpFlag Opt_D_dump_rn_trace)
2993 , make_ord_flag defGhcFlag "ddump-shape"
2994 (setDumpFlag Opt_D_dump_shape)
2995 , make_ord_flag defGhcFlag "ddump-if-trace"
2996 (setDumpFlag Opt_D_dump_if_trace)
2997 , make_ord_flag defGhcFlag "ddump-cs-trace"
2998 (setDumpFlag Opt_D_dump_cs_trace)
2999 , make_ord_flag defGhcFlag "ddump-tc-trace"
3000 (NoArg (do setDumpFlag' Opt_D_dump_tc_trace
3001 setDumpFlag' Opt_D_dump_cs_trace))
3002 , make_ord_flag defGhcFlag "ddump-ec-trace"
3003 (setDumpFlag Opt_D_dump_ec_trace)
3004 , make_ord_flag defGhcFlag "ddump-vt-trace"
3005 (setDumpFlag Opt_D_dump_vt_trace)
3006 , make_ord_flag defGhcFlag "ddump-splices"
3007 (setDumpFlag Opt_D_dump_splices)
3008 , make_ord_flag defGhcFlag "dth-dec-file"
3009 (setDumpFlag Opt_D_th_dec_file)
3010
3011 , make_ord_flag defGhcFlag "ddump-rn-stats"
3012 (setDumpFlag Opt_D_dump_rn_stats)
3013 , make_ord_flag defGhcFlag "ddump-opt-cmm"
3014 (setDumpFlag Opt_D_dump_opt_cmm)
3015 , make_ord_flag defGhcFlag "ddump-simpl-stats"
3016 (setDumpFlag Opt_D_dump_simpl_stats)
3017 , make_ord_flag defGhcFlag "ddump-bcos"
3018 (setDumpFlag Opt_D_dump_BCOs)
3019 , make_ord_flag defGhcFlag "dsource-stats"
3020 (setDumpFlag Opt_D_source_stats)
3021 , make_ord_flag defGhcFlag "dverbose-core2core"
3022 (NoArg $ setVerbosity (Just 2) >> setVerboseCore2Core)
3023 , make_ord_flag defGhcFlag "dverbose-stg2stg"
3024 (setDumpFlag Opt_D_verbose_stg2stg)
3025 , make_ord_flag defGhcFlag "ddump-hi"
3026 (setDumpFlag Opt_D_dump_hi)
3027 , make_ord_flag defGhcFlag "ddump-minimal-imports"
3028 (NoArg (setGeneralFlag Opt_D_dump_minimal_imports))
3029 , make_ord_flag defGhcFlag "ddump-vect"
3030 (setDumpFlag Opt_D_dump_vect)
3031 , make_ord_flag defGhcFlag "ddump-hpc"
3032 (setDumpFlag Opt_D_dump_ticked) -- back compat
3033 , make_ord_flag defGhcFlag "ddump-ticked"
3034 (setDumpFlag Opt_D_dump_ticked)
3035 , make_ord_flag defGhcFlag "ddump-mod-cycles"
3036 (setDumpFlag Opt_D_dump_mod_cycles)
3037 , make_ord_flag defGhcFlag "ddump-mod-map"
3038 (setDumpFlag Opt_D_dump_mod_map)
3039 , make_ord_flag defGhcFlag "ddump-view-pattern-commoning"
3040 (setDumpFlag Opt_D_dump_view_pattern_commoning)
3041 , make_ord_flag defGhcFlag "ddump-to-file"
3042 (NoArg (setGeneralFlag Opt_DumpToFile))
3043 , make_ord_flag defGhcFlag "ddump-hi-diffs"
3044 (setDumpFlag Opt_D_dump_hi_diffs)
3045 , make_ord_flag defGhcFlag "ddump-rtti"
3046 (setDumpFlag Opt_D_dump_rtti)
3047 , make_ord_flag defGhcFlag "dcore-lint"
3048 (NoArg (setGeneralFlag Opt_DoCoreLinting))
3049 , make_ord_flag defGhcFlag "dstg-lint"
3050 (NoArg (setGeneralFlag Opt_DoStgLinting))
3051 , make_ord_flag defGhcFlag "dcmm-lint"
3052 (NoArg (setGeneralFlag Opt_DoCmmLinting))
3053 , make_ord_flag defGhcFlag "dasm-lint"
3054 (NoArg (setGeneralFlag Opt_DoAsmLinting))
3055 , make_ord_flag defGhcFlag "dannot-lint"
3056 (NoArg (setGeneralFlag Opt_DoAnnotationLinting))
3057 , make_ord_flag defGhcFlag "dshow-passes"
3058 (NoArg $ forceRecompile >> (setVerbosity $ Just 2))
3059 , make_ord_flag defGhcFlag "dfaststring-stats"
3060 (NoArg (setGeneralFlag Opt_D_faststring_stats))
3061 , make_ord_flag defGhcFlag "dno-llvm-mangler"
3062 (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag
3063 , make_ord_flag defGhcFlag "ddump-debug"
3064 (setDumpFlag Opt_D_dump_debug)
3065 , make_ord_flag defGhcFlag "ddump-json"
3066 (noArg (flip dopt_set Opt_D_dump_json . setJsonLogAction ) )
3067 , make_ord_flag defGhcFlag "dppr-debug"
3068 (setDumpFlag Opt_D_ppr_debug)
3069 , make_ord_flag defGhcFlag "dno-debug-output"
3070 (setDumpFlag Opt_D_no_debug_output)
3071
3072 ------ Machine dependent (-m<blah>) stuff ---------------------------
3073
3074 , make_ord_flag defGhcFlag "msse" (noArg (\d ->
3075 d { sseVersion = Just SSE1 }))
3076 , make_ord_flag defGhcFlag "msse2" (noArg (\d ->
3077 d { sseVersion = Just SSE2 }))
3078 , make_ord_flag defGhcFlag "msse3" (noArg (\d ->
3079 d { sseVersion = Just SSE3 }))
3080 , make_ord_flag defGhcFlag "msse4" (noArg (\d ->
3081 d { sseVersion = Just SSE4 }))
3082 , make_ord_flag defGhcFlag "msse4.2" (noArg (\d ->
3083 d { sseVersion = Just SSE42 }))
3084 , make_ord_flag defGhcFlag "mavx" (noArg (\d -> d { avx = True }))
3085 , make_ord_flag defGhcFlag "mavx2" (noArg (\d -> d { avx2 = True }))
3086 , make_ord_flag defGhcFlag "mavx512cd" (noArg (\d ->
3087 d { avx512cd = True }))
3088 , make_ord_flag defGhcFlag "mavx512er" (noArg (\d ->
3089 d { avx512er = True }))
3090 , make_ord_flag defGhcFlag "mavx512f" (noArg (\d -> d { avx512f = True }))
3091 , make_ord_flag defGhcFlag "mavx512pf" (noArg (\d ->
3092 d { avx512pf = True }))
3093
3094 ------ Warning opts -------------------------------------------------
3095 , make_ord_flag defFlag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
3096 , make_ord_flag defFlag "Werror"
3097 (NoArg (do { setGeneralFlag Opt_WarnIsError
3098 ; mapM_ setFatalWarningFlag minusWeverythingOpts }))
3099 , make_ord_flag defFlag "Wwarn"
3100 (NoArg (do { unSetGeneralFlag Opt_WarnIsError
3101 ; mapM_ unSetFatalWarningFlag minusWeverythingOpts }))
3102 -- Opt_WarnIsError is still needed to pass -Werror
3103 -- to CPP; see runCpp in SysTools
3104 , make_dep_flag defFlag "Wnot" (NoArg (upd (\d ->
3105 d {warningFlags = EnumSet.empty})))
3106 "Use -w or -Wno-everything instead"
3107 , make_ord_flag defFlag "w" (NoArg (upd (\d ->
3108 d {warningFlags = EnumSet.empty})))
3109
3110 -- New-style uniform warning sets
3111 --
3112 -- Note that -Weverything > -Wall > -Wextra > -Wdefault > -Wno-everything
3113 , make_ord_flag defFlag "Weverything" (NoArg (mapM_
3114 setWarningFlag minusWeverythingOpts))
3115 , make_ord_flag defFlag "Wno-everything"
3116 (NoArg (upd (\d -> d {warningFlags = EnumSet.empty})))
3117
3118 , make_ord_flag defFlag "Wall" (NoArg (mapM_
3119 setWarningFlag minusWallOpts))
3120 , make_ord_flag defFlag "Wno-all" (NoArg (mapM_
3121 unSetWarningFlag minusWallOpts))
3122
3123 , make_ord_flag defFlag "Wextra" (NoArg (mapM_
3124 setWarningFlag minusWOpts))
3125 , make_ord_flag defFlag "Wno-extra" (NoArg (mapM_
3126 unSetWarningFlag minusWOpts))
3127
3128 , make_ord_flag defFlag "Wdefault" (NoArg (mapM_
3129 setWarningFlag standardWarnings))
3130 , make_ord_flag defFlag "Wno-default" (NoArg (mapM_
3131 unSetWarningFlag standardWarnings))
3132
3133 , make_ord_flag defFlag "Wcompat" (NoArg (mapM_
3134 setWarningFlag minusWcompatOpts))
3135 , make_ord_flag defFlag "Wno-compat" (NoArg (mapM_
3136 unSetWarningFlag minusWcompatOpts))
3137
3138 ------ Plugin flags ------------------------------------------------
3139 , make_ord_flag defGhcFlag "fplugin-opt" (hasArg addPluginModuleNameOption)
3140 , make_ord_flag defGhcFlag "fplugin" (hasArg addPluginModuleName)
3141 , make_ord_flag defGhcFlag "ffrontend-opt" (hasArg addFrontendPluginOption)
3142
3143 ------ Optimisation flags ------------------------------------------
3144 , make_dep_flag defGhcFlag "Onot" (noArgM $ setOptLevel 0 )
3145 "Use -O0 instead"
3146 , make_ord_flag defGhcFlag "Odph" (noArgM setDPHOpt)
3147 , make_ord_flag defGhcFlag "O" (optIntSuffixM (\mb_n ->
3148 setOptLevel (mb_n `orElse` 1)))
3149 -- If the number is missing, use 1
3150
3151
3152 , make_ord_flag defFlag "fmax-relevant-binds"
3153 (intSuffix (\n d -> d { maxRelevantBinds = Just n }))
3154 , make_ord_flag defFlag "fno-max-relevant-binds"
3155 (noArg (\d -> d { maxRelevantBinds = Nothing }))
3156 , make_ord_flag defFlag "fmax-valid-substitutions"
3157 (intSuffix (\n d -> d { maxValidSubstitutions = Just n }))
3158 , make_ord_flag defFlag "fno-max-valid-substitutions"
3159 (noArg (\d -> d { maxValidSubstitutions = Nothing }))
3160 , make_ord_flag defFlag "fmax-uncovered-patterns"
3161 (intSuffix (\n d -> d { maxUncoveredPatterns = n }))
3162 , make_ord_flag defFlag "fsimplifier-phases"
3163 (intSuffix (\n d -> d { simplPhases = n }))
3164 , make_ord_flag defFlag "fmax-simplifier-iterations"
3165 (intSuffix (\n d -> d { maxSimplIterations = n }))
3166 , make_ord_flag defFlag "fmax-pmcheck-iterations"
3167 (intSuffix (\n d -> d{ maxPmCheckIterations = n }))
3168 , make_ord_flag defFlag "fsimpl-tick-factor"
3169 (intSuffix (\n d -> d { simplTickFactor = n }))
3170 , make_ord_flag defFlag "fspec-constr-threshold"
3171 (intSuffix (\n d -> d { specConstrThreshold = Just n }))
3172 , make_ord_flag defFlag "fno-spec-constr-threshold"
3173 (noArg (\d -> d { specConstrThreshold = Nothing }))
3174 , make_ord_flag defFlag "fspec-constr-count"
3175 (intSuffix (\n d -> d { specConstrCount = Just n }))
3176 , make_ord_flag defFlag "fno-spec-constr-count"
3177 (noArg (\d -> d { specConstrCount = Nothing }))
3178 , make_ord_flag defFlag "fspec-constr-recursive"
3179 (intSuffix (\n d -> d { specConstrRecursive = n }))
3180 , make_ord_flag defFlag "fliberate-case-threshold"
3181 (intSuffix (\n d -> d { liberateCaseThreshold = Just n }))
3182 , make_ord_flag defFlag "fno-liberate-case-threshold"
3183 (noArg (\d -> d { liberateCaseThreshold = Nothing }))
3184 , make_ord_flag defFlag "frule-check"
3185 (sepArg (\s d -> d { ruleCheck = Just s }))
3186 , make_ord_flag defFlag "freduction-depth"
3187 (intSuffix (\n d -> d { reductionDepth = treatZeroAsInf n }))
3188 , make_ord_flag defFlag "fconstraint-solver-iterations"
3189 (intSuffix (\n d -> d { solverIterations = treatZeroAsInf n }))
3190 , (Deprecated, defFlag "fcontext-stack"
3191 (intSuffixM (\n d ->
3192 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
3193 ; return $ d { reductionDepth = treatZeroAsInf n } })))
3194 , (Deprecated, defFlag "ftype-function-depth"
3195 (intSuffixM (\n d ->
3196 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
3197 ; return $ d { reductionDepth = treatZeroAsInf n } })))
3198 , make_ord_flag defFlag "fstrictness-before"
3199 (intSuffix (\n d -> d { strictnessBefore = n : strictnessBefore d }))
3200 , make_ord_flag defFlag "ffloat-lam-args"
3201 (intSuffix (\n d -> d { floatLamArgs = Just n }))
3202 , make_ord_flag defFlag "ffloat-all-lams"
3203 (noArg (\d -> d { floatLamArgs = Nothing }))
3204 , make_ord_flag defFlag "fhistory-size"
3205 (intSuffix (\n d -> d { historySize = n }))
3206 , make_ord_flag defFlag "funfolding-creation-threshold"
3207 (intSuffix (\n d -> d {ufCreationThreshold = n}))
3208 , make_ord_flag defFlag "funfolding-use-threshold"
3209 (intSuffix (\n d -> d {ufUseThreshold = n}))
3210 , make_ord_flag defFlag "funfolding-fun-discount"
3211 (intSuffix (\n d -> d {ufFunAppDiscount = n}))
3212 , make_ord_flag defFlag "funfolding-dict-discount"
3213 (intSuffix (\n d -> d {ufDictDiscount = n}))
3214 , make_ord_flag defFlag "funfolding-keeness-factor"
3215 (floatSuffix (\n d -> d {ufKeenessFactor = n}))
3216 , make_ord_flag defFlag "fmax-worker-args"
3217 (intSuffix (\n d -> d {maxWorkerArgs = n}))
3218 , make_ord_flag defGhciFlag "fghci-hist-size"
3219 (intSuffix (\n d -> d {ghciHistSize = n}))
3220 , make_ord_flag defGhcFlag "fmax-inline-alloc-size"
3221 (intSuffix (\n d -> d { maxInlineAllocSize = n }))
3222 , make_ord_flag defGhcFlag "fmax-inline-memcpy-insns"
3223 (intSuffix (\n d -> d { maxInlineMemcpyInsns = n }))
3224 , make_ord_flag defGhcFlag "fmax-inline-memset-insns"
3225 (intSuffix (\n d -> d { maxInlineMemsetInsns = n }))
3226 , make_ord_flag defGhcFlag "dinitial-unique"
3227 (intSuffix (\n d -> d { initialUnique = n }))
3228 , make_ord_flag defGhcFlag "dunique-increment"
3229 (intSuffix (\n d -> d { uniqueIncrement = n }))
3230
3231 ------ Profiling ----------------------------------------------------
3232
3233 -- OLD profiling flags
3234 , make_dep_flag defGhcFlag "auto-all"
3235 (noArg (\d -> d { profAuto = ProfAutoAll } ))
3236 "Use -fprof-auto instead"
3237 , make_dep_flag defGhcFlag "no-auto-all"
3238 (noArg (\d -> d { profAuto = NoProfAuto } ))
3239 "Use -fno-prof-auto instead"
3240 , make_dep_flag defGhcFlag "auto"
3241 (noArg (\d -> d { profAuto = ProfAutoExports } ))
3242 "Use -fprof-auto-exported instead"
3243 , make_dep_flag defGhcFlag "no-auto"
3244 (noArg (\d -> d { profAuto = NoProfAuto } ))
3245 "Use -fno-prof-auto instead"
3246 , make_dep_flag defGhcFlag "caf-all"
3247 (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs))
3248 "Use -fprof-cafs instead"
3249 , make_dep_flag defGhcFlag "no-caf-all"
3250 (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs))
3251 "Use -fno-prof-cafs instead"
3252
3253 -- NEW profiling flags
3254 , make_ord_flag defGhcFlag "fprof-auto"
3255 (noArg (\d -> d { profAuto = ProfAutoAll } ))
3256 , make_ord_flag defGhcFlag "fprof-auto-top"
3257 (noArg (\d -> d { profAuto = ProfAutoTop } ))
3258 , make_ord_flag defGhcFlag "fprof-auto-exported"
3259 (noArg (\d -> d { profAuto = ProfAutoExports } ))
3260 , make_ord_flag defGhcFlag "fprof-auto-calls"
3261 (noArg (\d -> d { profAuto = ProfAutoCalls } ))
3262 , make_ord_flag defGhcFlag "fno-prof-auto"
3263 (noArg (\d -> d { profAuto = NoProfAuto } ))
3264
3265 ------ Compiler flags -----------------------------------------------
3266
3267 , make_ord_flag defGhcFlag "fasm" (NoArg (setObjTarget HscAsm))
3268 , make_ord_flag defGhcFlag "fvia-c" (NoArg
3269 (addWarn $ "The -fvia-c flag does nothing; " ++
3270 "it will be removed in a future GHC release"))
3271 , make_ord_flag defGhcFlag "fvia-C" (NoArg
3272 (addWarn $ "The -fvia-C flag does nothing; " ++
3273 "it will be removed in a future GHC release"))
3274 , make_ord_flag defGhcFlag "fllvm" (NoArg (setObjTarget HscLlvm))
3275
3276 , make_ord_flag defFlag "fno-code" (NoArg ((upd $ \d ->
3277 d { ghcLink=NoLink }) >> setTarget HscNothing))
3278 , make_ord_flag defFlag "fbyte-code" (NoArg (setTarget HscInterpreted))
3279 , make_ord_flag defFlag "fobject-code" (NoArg (setTargetWithPlatform
3280 defaultHscTarget))
3281 , make_dep_flag defFlag "fglasgow-exts"
3282 (NoArg enableGlasgowExts) "Use individual extensions instead"
3283 , make_dep_flag defFlag "fno-glasgow-exts"
3284 (NoArg disableGlasgowExts) "Use individual extensions instead"
3285 , make_ord_flag defFlag "Wunused-binds" (NoArg enableUnusedBinds)
3286 , make_ord_flag defFlag "Wno-unused-binds" (NoArg disableUnusedBinds)
3287 , make_ord_flag defHiddenFlag "fwarn-unused-binds" (NoArg enableUnusedBinds)
3288 , make_ord_flag defHiddenFlag "fno-warn-unused-binds" (NoArg
3289 disableUnusedBinds)
3290
3291 ------ Safe Haskell flags -------------------------------------------
3292 , make_ord_flag defFlag "fpackage-trust" (NoArg setPackageTrust)
3293 , make_ord_flag defFlag "fno-safe-infer" (noArg (\d ->
3294 d { safeInfer = False }))
3295 , make_ord_flag defGhcFlag "fPIC" (NoArg (setGeneralFlag Opt_PIC))
3296 , make_ord_flag defGhcFlag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC))
3297
3298 ------ Debugging flags ----------------------------------------------
3299 , make_ord_flag defGhcFlag "g" (OptIntSuffix setDebugLevel)
3300 ]
3301 ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlagsDeps
3302 ++ map (mkFlag turnOff "no-" unSetGeneralFlag ) negatableFlagsDeps
3303 ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlagsDeps
3304 ++ map (mkFlag turnOff "dno-" unSetGeneralFlag ) dFlagsDeps
3305 ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlagsDeps
3306 ++ map (mkFlag turnOff "fno-" unSetGeneralFlag ) fFlagsDeps
3307 ++ map (mkFlag turnOn "W" setWarningFlag ) wWarningFlagsDeps
3308 ++ map (mkFlag turnOff "Wno-" unSetWarningFlag ) wWarningFlagsDeps
3309 ++ map (mkFlag turnOn "Werror=" (\flag -> do {
3310 ; setWarningFlag flag
3311 ; setFatalWarningFlag flag }))
3312 wWarningFlagsDeps
3313 ++ map (mkFlag turnOn "Wwarn=" unSetFatalWarningFlag )
3314 wWarningFlagsDeps
3315 ++ map (mkFlag turnOn "Wno-error=" unSetFatalWarningFlag )
3316 wWarningFlagsDeps
3317 ++ map (mkFlag turnOn "fwarn-" setWarningFlag . hideFlag)
3318 wWarningFlagsDeps
3319 ++ map (mkFlag turnOff "fno-warn-" unSetWarningFlag . hideFlag)
3320 wWarningFlagsDeps
3321 ++ [ (NotDeprecated, unrecognisedWarning "W"),
3322 (Deprecated, unrecognisedWarning "fwarn-"),
3323 (Deprecated, unrecognisedWarning "fno-warn-") ]
3324 ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlagsDeps
3325 ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlagsDeps
3326 ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlagsDeps
3327 ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlagsDeps
3328 ++ map (mkFlag turnOn "X" setLanguage ) languageFlagsDeps
3329 ++ map (mkFlag turnOn "X" setSafeHaskell ) safeHaskellFlagsDeps
3330 ++ [ make_dep_flag defFlag "XGenerics"
3331 (NoArg $ return ())
3332 ("it does nothing; look into -XDefaultSignatures " ++
3333 "and -XDeriveGeneric for generic programming support.")
3334 , make_dep_flag defFlag "XNoGenerics"
3335 (NoArg $ return ())
3336 ("it does nothing; look into -XDefaultSignatures and " ++
3337 "-XDeriveGeneric for generic programming support.") ]
3338
3339 -- | This is where we handle unrecognised warning flags. We only issue a warning
3340 -- if -Wunrecognised-warning-flags is set. See Trac #11429 for context.
3341 unrecognisedWarning :: String -> Flag (CmdLineP DynFlags)
3342 unrecognisedWarning prefix = defHiddenFlag prefix (Prefix action)
3343 where
3344 action :: String -> EwM (CmdLineP DynFlags) ()
3345 action flag = do
3346 f <- wopt Opt_WarnUnrecognisedWarningFlags <$> liftEwM getCmdLineState
3347 when f $ addWarn $ "unrecognised warning flag: -" ++ prefix ++ flag
3348
3349 -- See Note [Supporting CLI completion]
3350 package_flags_deps :: [(Deprecation, Flag (CmdLineP DynFlags))]
3351 package_flags_deps = [
3352 ------- Packages ----------------------------------------------------
3353 make_ord_flag defFlag "package-db"
3354 (HasArg (addPkgConfRef . PkgConfFile))
3355 , make_ord_flag defFlag "clear-package-db" (NoArg clearPkgConf)
3356 , make_ord_flag defFlag "no-global-package-db" (NoArg removeGlobalPkgConf)
3357 , make_ord_flag defFlag "no-user-package-db" (NoArg removeUserPkgConf)
3358 , make_ord_flag defFlag "global-package-db"
3359 (NoArg (addPkgConfRef GlobalPkgConf))
3360 , make_ord_flag defFlag "user-package-db"
3361 (NoArg (addPkgConfRef UserPkgConf))
3362 -- backwards compat with GHC<=7.4 :
3363 , make_dep_flag defFlag "package-conf"
3364 (HasArg $ addPkgConfRef . PkgConfFile) "Use -package-db instead"
3365 , make_dep_flag defFlag "no-user-package-conf"
3366 (NoArg removeUserPkgConf) "Use -no-user-package-db instead"
3367 , make_ord_flag defGhcFlag "package-name" (HasArg $ \name -> do
3368 upd (setUnitId name))
3369 -- TODO: Since we JUST deprecated
3370 -- -this-package-key, let's keep this
3371 -- undeprecated for another cycle.
3372 -- Deprecate this eventually.
3373 -- deprecate "Use -this-unit-id instead")
3374 , make_dep_flag defGhcFlag "this-package-key" (HasArg $ upd . setUnitId)
3375 "Use -this-unit-id instead"
3376 , make_ord_flag defGhcFlag "this-unit-id" (hasArg setUnitId)
3377 , make_ord_flag defFlag "package" (HasArg exposePackage)
3378 , make_ord_flag defFlag "plugin-package-id" (HasArg exposePluginPackageId)
3379 , make_ord_flag defFlag "plugin-package" (HasArg exposePluginPackage)
3380 , make_ord_flag defFlag "package-id" (HasArg exposePackageId)
3381 , make_ord_flag defFlag "hide-package" (HasArg hidePackage)
3382 , make_ord_flag defFlag "hide-all-packages"
3383 (NoArg (setGeneralFlag Opt_HideAllPackages))
3384 , make_ord_flag defFlag "hide-all-plugin-packages"
3385 (NoArg (setGeneralFlag Opt_HideAllPluginPackages))
3386 , make_ord_flag defFlag "package-env" (HasArg setPackageEnv)
3387 , make_ord_flag defFlag "ignore-package" (HasArg ignorePackage)
3388 , make_dep_flag defFlag "syslib" (HasArg exposePackage) "Use -package instead"
3389 , make_ord_flag defFlag "distrust-all-packages"
3390 (NoArg (setGeneralFlag Opt_DistrustAllPackages))
3391 , make_ord_flag defFlag "trust" (HasArg trustPackage)
3392 , make_ord_flag defFlag "distrust" (HasArg distrustPackage)
3393 ]
3394 where
3395 setPackageEnv env = upd $ \s -> s { packageEnv = Just env }
3396
3397 -- | Make a list of flags for shell completion.
3398 -- Filter all available flags into two groups, for interactive GHC vs all other.
3399 flagsForCompletion :: Bool -> [String]
3400 flagsForCompletion isInteractive
3401 = [ '-':flagName flag
3402 | flag <- flagsAll
3403 , modeFilter (flagGhcMode flag)
3404 ]
3405 where
3406 modeFilter AllModes = True
3407 modeFilter OnlyGhci = isInteractive
3408 modeFilter OnlyGhc = not isInteractive
3409 modeFilter HiddenFlag = False
3410
3411 type TurnOnFlag = Bool -- True <=> we are turning the flag on
3412 -- False <=> we are turning the flag off
3413 turnOn :: TurnOnFlag; turnOn = True
3414 turnOff :: TurnOnFlag; turnOff = False
3415
3416 data FlagSpec flag
3417 = FlagSpec
3418 { flagSpecName :: String -- ^ Flag in string form
3419 , flagSpecFlag :: flag -- ^ Flag in internal form
3420 , flagSpecAction :: (TurnOnFlag -> DynP ())
3421 -- ^ Extra action to run when the flag is found
3422 -- Typically, emit a warning or error
3423 , flagSpecGhcMode :: GhcFlagMode
3424 -- ^ In which ghc mode the flag has effect
3425 }
3426
3427 -- | Define a new flag.
3428 flagSpec :: String -> flag -> (Deprecation, FlagSpec flag)
3429 flagSpec name flag = flagSpec' name flag nop
3430
3431 -- | Define a new flag with an effect.
3432 flagSpec' :: String -> flag -> (TurnOnFlag -> DynP ())
3433 -> (Deprecation, FlagSpec flag)
3434 flagSpec' name flag act = (NotDeprecated, FlagSpec name flag act AllModes)
3435
3436 -- | Define a new deprecated flag with an effect.
3437 depFlagSpecOp :: String -> flag -> (TurnOnFlag -> DynP ()) -> String
3438 -> (Deprecation, FlagSpec flag)
3439 depFlagSpecOp name flag act dep =
3440 (Deprecated, snd (flagSpec' name flag (\f -> act f >> deprecate dep)))
3441
3442 -- | Define a new deprecated flag.
3443 depFlagSpec :: String -> flag -> String
3444 -> (Deprecation, FlagSpec flag)
3445 depFlagSpec name flag dep = depFlagSpecOp name flag nop dep
3446
3447 -- | Define a new deprecated flag with an effect where the deprecation message
3448 -- depends on the flag value
3449 depFlagSpecOp' :: String
3450 -> flag
3451 -> (TurnOnFlag -> DynP ())
3452 -> (TurnOnFlag -> String)
3453 -> (Deprecation, FlagSpec flag)
3454 depFlagSpecOp' name flag act dep =
3455 (Deprecated, FlagSpec name flag (\f -> act f >> (deprecate $ dep f))
3456 AllModes)
3457
3458 -- | Define a new deprecated flag where the deprecation message
3459 -- depends on the flag value
3460 depFlagSpec' :: String
3461 -> flag
3462 -> (TurnOnFlag -> String)
3463 -> (Deprecation, FlagSpec flag)
3464 depFlagSpec' name flag dep = depFlagSpecOp' name flag nop dep
3465
3466
3467 -- | Define a new deprecated flag where the deprecation message
3468 -- is shown depending on the flag value
3469 depFlagSpecCond :: String
3470 -> flag
3471 -> (TurnOnFlag -> Bool)
3472 -> String
3473 -> (Deprecation, FlagSpec flag)
3474 depFlagSpecCond name flag cond dep =
3475 (Deprecated, FlagSpec name flag (\f -> when (cond f) $ deprecate dep)
3476 AllModes)
3477
3478 -- | Define a new flag for GHCi.
3479 flagGhciSpec :: String -> flag -> (Deprecation, FlagSpec flag)
3480 flagGhciSpec name flag = flagGhciSpec' name flag nop
3481
3482 -- | Define a new flag for GHCi with an effect.
3483 flagGhciSpec' :: String -> flag -> (TurnOnFlag -> DynP ())
3484 -> (Deprecation, FlagSpec flag)
3485 flagGhciSpec' name flag act = (NotDeprecated, FlagSpec name flag act OnlyGhci)
3486
3487 -- | Define a new flag invisible to CLI completion.
3488 flagHiddenSpec :: String -> flag -> (Deprecation, FlagSpec flag)
3489 flagHiddenSpec name flag = flagHiddenSpec' name flag nop
3490
3491 -- | Define a new flag invisible to CLI completion with an effect.
3492 flagHiddenSpec' :: String -> flag -> (TurnOnFlag -> DynP ())
3493 -> (Deprecation, FlagSpec flag)
3494 flagHiddenSpec' name flag act = (NotDeprecated, FlagSpec name flag act
3495 HiddenFlag)
3496
3497 -- | Hide a 'FlagSpec' from being displayed in @--show-options@.
3498 --
3499 -- This is for example useful for flags that are obsolete, but should not
3500 -- (yet) be deprecated for compatibility reasons.
3501 hideFlag :: (Deprecation, FlagSpec a) -> (Deprecation, FlagSpec a)
3502 hideFlag (dep, fs) = (dep, fs { flagSpecGhcMode = HiddenFlag })
3503
3504 mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on
3505 -> String -- ^ The flag prefix
3506 -> (flag -> DynP ()) -- ^ What to do when the flag is found
3507 -> (Deprecation, FlagSpec flag) -- ^ Specification of
3508 -- this particular flag
3509 -> (Deprecation, Flag (CmdLineP DynFlags))
3510 mkFlag turn_on flagPrefix f (dep, (FlagSpec name flag extra_action mode))
3511 = (dep,
3512 Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on)) mode)
3513
3514 deprecatedForExtension :: String -> TurnOnFlag -> String
3515 deprecatedForExtension lang turn_on
3516 = "use -X" ++ flag ++
3517 " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead"
3518 where
3519 flag | turn_on = lang
3520 | otherwise = "No" ++ lang
3521
3522 useInstead :: String -> String -> TurnOnFlag -> String
3523 useInstead prefix flag turn_on
3524 = "Use " ++ prefix ++ no ++ flag ++ " instead"
3525 where
3526 no = if turn_on then "" else "no-"
3527
3528 nop :: TurnOnFlag -> DynP ()
3529 nop _ = return ()
3530
3531 -- | Find the 'FlagSpec' for a 'WarningFlag'.
3532 flagSpecOf :: WarningFlag -> Maybe (FlagSpec WarningFlag)
3533 flagSpecOf flag = listToMaybe $ filter check wWarningFlags
3534 where
3535 check fs = flagSpecFlag fs == flag
3536
3537 -- | These @-W\<blah\>@ flags can all be reversed with @-Wno-\<blah\>@
3538 wWarningFlags :: [FlagSpec WarningFlag]
3539 wWarningFlags = map snd (sortBy (comparing fst) wWarningFlagsDeps)
3540
3541 wWarningFlagsDeps :: [(Deprecation, FlagSpec WarningFlag)]
3542 wWarningFlagsDeps = [
3543 -- See Note [Updating flag description in the User's Guide]
3544 -- See Note [Supporting CLI completion]
3545 -- Please keep the list of flags below sorted alphabetically
3546 flagSpec "alternative-layout-rule-transitional"
3547 Opt_WarnAlternativeLayoutRuleTransitional,
3548 depFlagSpec "amp" Opt_WarnAMP
3549 "it has no effect",
3550 depFlagSpec "auto-orphans" Opt_WarnAutoOrphans
3551 "it has no effect",
3552 flagSpec "cpp-undef" Opt_WarnCPPUndef,
3553 flagSpec "unbanged-strict-patterns" Opt_WarnUnbangedStrictPatterns,
3554 flagSpec "deferred-type-errors" Opt_WarnDeferredTypeErrors,
3555 flagSpec "deferred-out-of-scope-variables"
3556 Opt_WarnDeferredOutOfScopeVariables,
3557 flagSpec "deprecations" Opt_WarnWarningsDeprecations,
3558 flagSpec "deprecated-flags" Opt_WarnDeprecatedFlags,
3559 flagSpec "deriving-typeable" Opt_WarnDerivingTypeable,
3560 flagSpec "dodgy-exports" Opt_WarnDodgyExports,
3561 flagSpec "dodgy-foreign-imports" Opt_WarnDodgyForeignImports,
3562 flagSpec "dodgy-imports" Opt_WarnDodgyImports,
3563 flagSpec "empty-enumerations" Opt_WarnEmptyEnumerations,
3564 depFlagSpec "duplicate-constraints" Opt_WarnDuplicateConstraints
3565 "it is subsumed by -Wredundant-constraints",
3566 flagSpec "redundant-constraints" Opt_WarnRedundantConstraints,
3567 flagSpec "duplicate-exports" Opt_WarnDuplicateExports,
3568 flagSpec "hi-shadowing" Opt_WarnHiShadows,
3569 flagSpec "implicit-prelude" Opt_WarnImplicitPrelude,
3570 flagSpec "incomplete-patterns" Opt_WarnIncompletePatterns,
3571 flagSpec "incomplete-record-updates" Opt_WarnIncompletePatternsRecUpd,
3572 flagSpec "incomplete-uni-patterns" Opt_WarnIncompleteUniPatterns,
3573 flagSpec "inline-rule-shadowing" Opt_WarnInlineRuleShadowing,
3574 flagSpec "identities" Opt_WarnIdentities,
3575 flagSpec "missing-fields" Opt_WarnMissingFields,
3576 flagSpec "missing-import-lists" Opt_WarnMissingImportList,
3577 depFlagSpec "missing-local-sigs" Opt_WarnMissingLocalSignatures
3578 "it is replaced by -Wmissing-local-signatures",
3579 flagSpec "missing-local-signatures" Opt_WarnMissingLocalSignatures,
3580 flagSpec "missing-methods" Opt_WarnMissingMethods,
3581 flagSpec "missing-monadfail-instances" Opt_WarnMissingMonadFailInstances,
3582 flagSpec "semigroup" Opt_WarnSemigroup,
3583 flagSpec "missing-signatures" Opt_WarnMissingSignatures,
3584 depFlagSpec "missing-exported-sigs" Opt_WarnMissingExportedSignatures
3585 "it is replaced by -Wmissing-exported-signatures",
3586 flagSpec "missing-exported-signatures" Opt_WarnMissingExportedSignatures,
3587 flagSpec "monomorphism-restriction" Opt_WarnMonomorphism,
3588 flagSpec "name-shadowing" Opt_WarnNameShadowing,
3589 flagSpec "noncanonical-monad-instances"
3590 Opt_WarnNonCanonicalMonadInstances,
3591 flagSpec "noncanonical-monadfail-instances"
3592 Opt_WarnNonCanonicalMonadFailInstances,
3593 flagSpec "noncanonical-monoid-instances"
3594 Opt_WarnNonCanonicalMonoidInstances,
3595 flagSpec "orphans" Opt_WarnOrphans,
3596 flagSpec "overflowed-literals" Opt_WarnOverflowedLiterals,
3597 flagSpec "overlapping-patterns" Opt_WarnOverlappingPatterns,
3598 flagSpec "missed-specialisations" Opt_WarnMissedSpecs,
3599 flagSpec "missed-specializations" Opt_WarnMissedSpecs,
3600 flagSpec "all-missed-specialisations" Opt_WarnAllMissedSpecs,
3601 flagSpec "all-missed-specializations" Opt_WarnAllMissedSpecs,
3602 flagSpec' "safe" Opt_WarnSafe setWarnSafe,
3603 flagSpec "trustworthy-safe" Opt_WarnTrustworthySafe,
3604 flagSpec "tabs" Opt_WarnTabs,
3605 flagSpec "type-defaults" Opt_WarnTypeDefaults,
3606 flagSpec "typed-holes" Opt_WarnTypedHoles,
3607 flagSpec "partial-type-signatures" Opt_WarnPartialTypeSignatures,
3608 flagSpec "unrecognised-pragmas" Opt_WarnUnrecognisedPragmas,
3609 flagSpec' "unsafe" Opt_WarnUnsafe setWarnUnsafe,
3610 flagSpec "unsupported-calling-conventions"
3611 Opt_WarnUnsupportedCallingConventions,
3612 flagSpec "unsupported-llvm-version" Opt_WarnUnsupportedLlvmVersion,
3613 flagSpec "unticked-promoted-constructors"
3614 Opt_WarnUntickedPromotedConstructors,
3615 flagSpec "unused-do-bind" Opt_WarnUnusedDoBind,
3616 flagSpec "unused-foralls" Opt_WarnUnusedForalls,
3617 flagSpec "unused-imports" Opt_WarnUnusedImports,
3618 flagSpec "unused-local-binds" Opt_WarnUnusedLocalBinds,
3619 flagSpec "unused-matches" Opt_WarnUnusedMatches,
3620 flagSpec "unused-pattern-binds" Opt_WarnUnusedPatternBinds,
3621 flagSpec "unused-top-binds" Opt_WarnUnusedTopBinds,
3622 flagSpec "unused-type-patterns" Opt_WarnUnusedTypePatterns,
3623 flagSpec "warnings-deprecations" Opt_WarnWarningsDeprecations,
3624 flagSpec "wrong-do-bind" Opt_WarnWrongDoBind,
3625 flagSpec "missing-pattern-synonym-signatures"
3626 Opt_WarnMissingPatternSynonymSignatures,
3627 flagSpec "simplifiable-class-constraints" Opt_WarnSimplifiableClassConstraints,
3628 flagSpec "missing-home-modules" Opt_WarnMissingHomeModules,
3629 flagSpec "unrecognised-warning-flags" Opt_WarnUnrecognisedWarningFlags ]
3630
3631 -- | These @-\<blah\>@ flags can all be reversed with @-no-\<blah\>@
3632 negatableFlagsDeps :: [(Deprecation, FlagSpec GeneralFlag)]
3633 negatableFlagsDeps = [
3634 flagGhciSpec "ignore-dot-ghci" Opt_IgnoreDotGhci ]
3635
3636 -- | These @-d\<blah\>@ flags can all be reversed with @-dno-\<blah\>@
3637 dFlagsDeps :: [(Deprecation, FlagSpec GeneralFlag)]
3638 dFlagsDeps = [
3639 -- See Note [Updating flag description in the User's Guide]
3640 -- See Note [Supporting CLI completion]
3641 -- Please keep the list of flags below sorted alphabetically
3642 flagSpec "ppr-case-as-let" Opt_PprCaseAsLet,
3643 depFlagSpec' "ppr-ticks" Opt_PprShowTicks
3644 (\turn_on -> useInstead "-d" "suppress-ticks" (not turn_on)),
3645 flagSpec "suppress-ticks" Opt_SuppressTicks,
3646 flagSpec "suppress-coercions" Opt_SuppressCoercions,
3647 flagSpec "suppress-idinfo" Opt_SuppressIdInfo,
3648 flagSpec "suppress-unfoldings" Opt_SuppressUnfoldings,
3649 flagSpec "suppress-module-prefixes" Opt_SuppressModulePrefixes,
3650 flagSpec "suppress-type-applications" Opt_SuppressTypeApplications,
3651 flagSpec "suppress-type-signatures" Opt_SuppressTypeSignatures,
3652 flagSpec "suppress-uniques" Opt_SuppressUniques,
3653 flagSpec "suppress-var-kinds" Opt_SuppressVarKinds]
3654
3655 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
3656 fFlags :: [FlagSpec GeneralFlag]
3657 fFlags = map snd fFlagsDeps
3658
3659 fFlagsDeps :: [(Deprecation, FlagSpec GeneralFlag)]
3660 fFlagsDeps = [
3661 -- See Note [Updating flag description in the User's Guide]
3662 -- See Note [Supporting CLI completion]
3663 -- Please keep the list of flags below sorted alphabetically
3664 flagGhciSpec "break-on-error" Opt_BreakOnError,
3665 flagGhciSpec "break-on-exception" Opt_BreakOnException,
3666 flagSpec "building-cabal-package" Opt_BuildingCabalPackage,
3667 flagSpec "call-arity" Opt_CallArity,
3668 flagSpec "case-merge" Opt_CaseMerge,
3669 flagSpec "case-folding" Opt_CaseFolding,
3670 flagSpec "cmm-elim-common-blocks" Opt_CmmElimCommonBlocks,
3671 flagSpec "cmm-sink" Opt_CmmSink,
3672 flagSpec "cse" Opt_CSE,
3673 flagSpec "stg-cse" Opt_StgCSE,
3674 flagSpec "cpr-anal" Opt_CprAnal,
3675 flagSpec "defer-type-errors" Opt_DeferTypeErrors,
3676 flagSpec "defer-typed-holes" Opt_DeferTypedHoles,
3677 flagSpec "defer-out-of-scope-variables" Opt_DeferOutOfScopeVariables,
3678 flagSpec "diagnostics-show-caret" Opt_DiagnosticsShowCaret,
3679 flagSpec "dicts-cheap" Opt_DictsCheap,
3680 flagSpec "dicts-strict" Opt_DictsStrict,
3681 flagSpec "dmd-tx-dict-sel" Opt_DmdTxDictSel,
3682 flagSpec "do-eta-reduction" Opt_DoEtaReduction,
3683 flagSpec "do-lambda-eta-expansion" Opt_DoLambdaEtaExpansion,
3684 flagSpec "eager-blackholing" Opt_EagerBlackHoling,
3685 flagSpec "embed-manifest" Opt_EmbedManifest,
3686 flagSpec "enable-rewrite-rules" Opt_EnableRewriteRules,
3687 flagSpec "error-spans" Opt_ErrorSpans,
3688 flagSpec "excess-precision" Opt_ExcessPrecision,
3689 flagSpec "expose-all-unfoldings" Opt_ExposeAllUnfoldings,
3690 flagSpec "external-interpreter" Opt_ExternalInterpreter,
3691 flagSpec "flat-cache" Opt_FlatCache,
3692 flagSpec "float-in" Opt_FloatIn,
3693 flagSpec "force-recomp" Opt_ForceRecomp,
3694 flagSpec "full-laziness" Opt_FullLaziness,
3695 flagSpec "fun-to-thunk" Opt_FunToThunk,
3696 flagSpec "gen-manifest" Opt_GenManifest,
3697 flagSpec "ghci-history" Opt_GhciHistory,
3698 flagGhciSpec "local-ghci-history" Opt_LocalGhciHistory,
3699 flagSpec "ghci-sandbox" Opt_GhciSandbox,
3700 flagSpec "helpful-errors" Opt_HelpfulErrors,
3701 flagSpec "hpc" Opt_Hpc,
3702 flagSpec "ignore-asserts" Opt_IgnoreAsserts,
3703 flagSpec "ignore-interface-pragmas" Opt_IgnoreInterfacePragmas,
3704 flagGhciSpec "implicit-import-qualified" Opt_ImplicitImportQualified,
3705 flagSpec "irrefutable-tuples" Opt_IrrefutableTuples,
3706 flagSpec "kill-absence" Opt_KillAbsence,
3707 flagSpec "kill-one-shot" Opt_KillOneShot,
3708 flagSpec "late-dmd-anal" Opt_LateDmdAnal,
3709 flagSpec "liberate-case" Opt_LiberateCase,
3710 flagHiddenSpec "llvm-pass-vectors-in-regs" Opt_LlvmPassVectorsInRegisters,
3711 flagHiddenSpec "llvm-tbaa" Opt_LlvmTBAA,
3712 flagHiddenSpec "llvm-fill-undef-with-garbage" Opt_LlvmFillUndefWithGarbage,
3713 flagSpec "loopification" Opt_Loopification,
3714 flagSpec "omit-interface-pragmas" Opt_OmitInterfacePragmas,
3715 flagSpec "omit-yields" Opt_OmitYields,
3716 flagSpec "optimal-applicative-do" Opt_OptimalApplicativeDo,
3717 flagSpec "pedantic-bottoms" Opt_PedanticBottoms,
3718 flagSpec "pre-inlining" Opt_SimplPreInlining,
3719 flagGhciSpec "print-bind-contents" Opt_PrintBindContents,
3720 flagGhciSpec "print-bind-result" Opt_PrintBindResult,
3721 flagGhciSpec "print-evld-with-show" Opt_PrintEvldWithShow,
3722 flagSpec "print-explicit-foralls" Opt_PrintExplicitForalls,
3723 flagSpec "print-explicit-kinds" Opt_PrintExplicitKinds,
3724 flagSpec "print-explicit-coercions" Opt_PrintExplicitCoercions,
3725 flagSpec "print-explicit-runtime-reps" Opt_PrintExplicitRuntimeReps,
3726 flagSpec "print-equality-relations" Opt_PrintEqualityRelations,
3727 flagSpec "print-unicode-syntax" Opt_PrintUnicodeSyntax,
3728 flagSpec "print-expanded-synonyms" Opt_PrintExpandedSynonyms,
3729 flagSpec "print-potential-instances" Opt_PrintPotentialInstances,
3730 flagSpec "print-typechecker-elaboration" Opt_PrintTypecheckerElaboration,
3731 flagSpec "prof-cafs" Opt_AutoSccsOnIndividualCafs,
3732 flagSpec "prof-count-entries" Opt_ProfCountEntries,
3733 flagSpec "regs-graph" Opt_RegsGraph,
3734 flagSpec "regs-iterative" Opt_RegsIterative,
3735 depFlagSpec' "rewrite-rules" Opt_EnableRewriteRules
3736 (useInstead "-f" "enable-rewrite-rules"),
3737 flagSpec "shared-implib" Opt_SharedImplib,
3738 flagSpec "spec-constr" Opt_SpecConstr,
3739 flagSpec "spec-constr-keen" Opt_SpecConstrKeen,
3740 flagSpec "specialise" Opt_Specialise,
3741 flagSpec "specialize" Opt_Specialise,
3742 flagSpec "specialise-aggressively" Opt_SpecialiseAggressively,
3743 flagSpec "specialize-aggressively" Opt_SpecialiseAggressively,
3744 flagSpec "cross-module-specialise" Opt_CrossModuleSpecialise,
3745 flagSpec "cross-module-specialize" Opt_CrossModuleSpecialise,
3746 flagSpec "static-argument-transformation" Opt_StaticArgumentTransformation,
3747 flagSpec "strictness" Opt_Strictness,
3748 flagSpec "use-rpaths" Opt_RPath,
3749 flagSpec "write-interface" Opt_WriteInterface,
3750 flagSpec "unbox-small-strict-fields" Opt_UnboxSmallStrictFields,
3751 flagSpec "unbox-strict-fields" Opt_UnboxStrictFields,
3752 flagSpec "vectorisation-avoidance" Opt_VectorisationAvoidance,
3753 flagSpec "vectorise" Opt_Vectorise,
3754 flagSpec "version-macros" Opt_VersionMacros,
3755 flagSpec "worker-wrapper" Opt_WorkerWrapper,
3756 flagSpec "solve-constant-dicts" Opt_SolveConstantDicts,
3757 flagSpec "show-warning-groups" Opt_ShowWarnGroups,
3758 flagSpec "hide-source-paths" Opt_HideSourcePaths,
3759 flagSpec "show-hole-constraints" Opt_ShowHoleConstraints,
3760 flagSpec "whole-archive-hs-libs" Opt_WholeArchiveHsLibs
3761 ]
3762
3763 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
3764 fLangFlags :: [FlagSpec LangExt.Extension]
3765 fLangFlags = map snd fLangFlagsDeps
3766
3767 fLangFlagsDeps :: [(Deprecation, FlagSpec LangExt.Extension)]
3768 fLangFlagsDeps = [
3769 -- See Note [Updating flag description in the User's Guide]
3770 -- See Note [Supporting CLI completion]
3771 depFlagSpecOp' "th" LangExt.TemplateHaskell
3772 checkTemplateHaskellOk
3773 (deprecatedForExtension "TemplateHaskell"),
3774 depFlagSpec' "fi" LangExt.ForeignFunctionInterface
3775 (deprecatedForExtension "ForeignFunctionInterface"),
3776 depFlagSpec' "ffi" LangExt.ForeignFunctionInterface
3777 (deprecatedForExtension "ForeignFunctionInterface"),
3778 depFlagSpec' "arrows" LangExt.Arrows
3779 (deprecatedForExtension "Arrows"),
3780 depFlagSpec' "implicit-prelude" LangExt.ImplicitPrelude
3781 (deprecatedForExtension "ImplicitPrelude"),
3782 depFlagSpec' "bang-patterns" LangExt.BangPatterns
3783 (deprecatedForExtension "BangPatterns"),
3784 depFlagSpec' "monomorphism-restriction" LangExt.MonomorphismRestriction
3785 (deprecatedForExtension "MonomorphismRestriction"),
3786 depFlagSpec' "mono-pat-binds" LangExt.MonoPatBinds
3787 (deprecatedForExtension "MonoPatBinds"),
3788 depFlagSpec' "extended-default-rules" LangExt.ExtendedDefaultRules
3789 (deprecatedForExtension "ExtendedDefaultRules"),
3790 depFlagSpec' "implicit-params" LangExt.ImplicitParams
3791 (deprecatedForExtension "ImplicitParams"),
3792 depFlagSpec' "scoped-type-variables" LangExt.ScopedTypeVariables
3793 (deprecatedForExtension "ScopedTypeVariables"),
3794 depFlagSpec' "parr" LangExt.ParallelArrays
3795 (deprecatedForExtension "ParallelArrays"),
3796 depFlagSpec' "PArr" LangExt.ParallelArrays
3797 (deprecatedForExtension "ParallelArrays"),
3798 depFlagSpec' "allow-overlapping-instances" LangExt.OverlappingInstances
3799 (deprecatedForExtension "OverlappingInstances"),
3800 depFlagSpec' "allow-undecidable-instances" LangExt.UndecidableInstances
3801 (deprecatedForExtension "UndecidableInstances"),
3802 depFlagSpec'