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