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