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