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