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