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