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