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