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