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