2 (c) The University of Glasgow 2006-2012
3 (c) The GRASP Project, Glasgow University, 1992-2002
6 Various types used during typechecking, please see TcRnMonad as well for
7 operations on these types. You probably want to import it, instead of this
10 All the monads exported here are built on top of the same IOEnv monad. The
11 monad functions like a Reader monad in the way it passes the environment
12 around. This is done to allow the environment to be manipulated in a stack
13 like fashion when entering expressions... etc.
15 For state that is global and should be returned at the end (e.g not part
16 of the stack mechanism), you should use a TcRef (= IORef) to store them.
19 {-# LANGUAGE CPP, DeriveFunctor, ExistentialQuantification, GeneralizedNewtypeDeriving,
23 TcRnIf
, TcRn
, TcM
, RnM
, IfM
, IfL
, IfG
, -- The monad is opaque outside this module
26 -- The environment types
28 TcGblEnv
(..), TcLclEnv
(..),
29 setLclEnvTcLevel
, getLclEnvTcLevel
,
30 setLclEnvLoc
, getLclEnvLoc
,
31 IfGblEnv
(..), IfLclEnv
(..),
34 -- Frontend types (shouldn't really be here)
38 ErrCtxt
, RecFieldEnv
, pushErrCtxt
, pushErrCtxtSameOrigin
,
39 ImportAvails
(..), emptyImportAvails
, plusImportAvails
,
40 WhereFrom
(..), mkModDeps
, modDepsElts
,
43 TcTypeEnv
, TcBinderStack
, TcBinder
(..),
44 TcTyThing
(..), PromotionErr
(..),
45 IdBindingInfo
(..), ClosedTypeId
, RhsNames
,
48 pprTcTyThingCategory
, pprPECategory
, CompleteMatch
(..),
51 DsM
, DsLclEnv
(..), DsGblEnv
(..),
52 DsMetaEnv
, DsMetaVal
(..), CompleteMatchMap
,
53 mkCompleteMatchMap
, extendCompleteMatchMap
,
56 ThStage
(..), SpliceType
(..), PendingStuff
(..),
57 topStage
, topAnnStage
, topSpliceStage
,
58 ThLevel
, impLevel
, outerLevel
, thLevel
,
65 TcSigFun
, TcSigInfo
(..), TcIdSigInfo
(..),
66 TcIdSigInst
(..), TcPatSynInfo
(..),
67 isPartialSig
, hasCompleteSig
,
72 removeBindingShadowing
,
74 -- Constraint solver plugins
75 TcPlugin
(..), TcPluginResult
(..), TcPluginSolver
,
76 TcPluginM
, runTcPluginM
, unsafeTcPluginTcM
,
80 RoleAnnotEnv
, emptyRoleAnnotEnv
, mkRoleAnnotEnv
,
81 lookupRoleAnnot
, getRoleAnnots
84 #include
"HsVersions.h"
92 import TyCon
( TyCon
, tyConKind
)
93 import PatSyn
( PatSyn
)
94 import Id
( idType
, idName
)
95 import FieldLabel
( FieldLabel
)
102 import {-# SOURCE #-} GHC
.HsToCore
.PmCheck
.Types
(Delta
)
124 import PrelNames
( isUnboundName
)
125 import CostCentreState
127 import Control
.Monad
(ap)
128 import qualified Control
.Monad
.Fail
as MonadFail
129 import Data
.Set
( Set
)
130 import qualified Data
.Set
as S
132 import Data
.List
( sort )
133 import Data
.Map
( Map
)
134 import Data
.Dynamic
( Dynamic
)
135 import Data
.Typeable
( TypeRep
)
136 import Data
.Maybe ( mapMaybe )
138 import GHCi
.RemoteTypes
140 import {-# SOURCE #-} TcHoleFitTypes
( HoleFitPlugin
)
142 import qualified Language
.Haskell
.TH
as TH
144 -- | A 'NameShape' is a substitution on 'Name's that can be used
145 -- to refine the identities of a hole while we are renaming interfaces
146 -- (see 'RnModIface'). Specifically, a 'NameShape' for
147 -- 'ns_module_name' @A@, defines a mapping from @{A.T}@
148 -- (for some 'OccName' @T@) to some arbitrary other 'Name'.
150 -- The most intruiging thing about a 'NameShape', however, is
151 -- how it's constructed. A 'NameShape' is *implied* by the
152 -- exported 'AvailInfo's of the implementor of an interface:
153 -- if an implementor of signature @<H>@ exports @M.T@, you implicitly
154 -- define a substitution from @{H.T}@ to @M.T@. So a 'NameShape'
155 -- is computed from the list of 'AvailInfo's that are exported
156 -- by the implementation of a module, or successively merged
157 -- together by the export lists of signatures which are joining
160 -- It's not the most obvious way to go about doing this, but it
161 -- does seem to work!
163 -- NB: Can't boot this and put it in NameShape because then we
164 -- start pulling in too many DynFlags things.
165 data NameShape
= NameShape
{
166 ns_mod_name
:: ModuleName
,
167 ns_exports
:: [AvailInfo
],
168 ns_map
:: OccEnv Name
173 ************************************************************************
175 Standard monad definition for TcRn
176 All the combinators for the monad can be found in TcRnMonad
178 ************************************************************************
180 The monad itself has to be defined here, because it is mentioned by ErrCtxt
183 type TcRnIf a b
= IOEnv
(Env a b
)
184 type TcRn
= TcRnIf TcGblEnv TcLclEnv
-- Type inference
185 type IfM lcl
= TcRnIf IfGblEnv lcl
-- Iface stuff
186 type IfG
= IfM
() -- Top level
187 type IfL
= IfM IfLclEnv
-- Nested
188 type DsM
= TcRnIf DsGblEnv DsLclEnv
-- Desugaring
190 -- TcRn is the type-checking and renaming monad: the main monad that
191 -- most type-checking takes place in. The global environment is
192 -- 'TcGblEnv', which tracks all of the top-level type-checking
193 -- information we've accumulated while checking a module, while the
194 -- local environment is 'TcLclEnv', which tracks local information as
195 -- we move inside expressions.
197 -- | Historical "renaming monad" (now it's just 'TcRn').
200 -- | Historical "type-checking monad" (now it's just 'TcRn').
203 -- We 'stack' these envs through the Reader like monad infrastructure
204 -- as we move into an expression (although the change is focused in
208 env_top
:: !HscEnv
, -- Top-level stuff that never changes
209 -- Includes all info about imported things
210 -- BangPattern is to fix leak, see #15111
212 env_us
:: {-# UNPACK #-} !(IORef UniqSupply
),
213 -- Unique supply for local variables
215 env_gbl
:: gbl
, -- Info about things defined at the top level
216 -- of the module being compiled
218 env_lcl
:: lcl
-- Nested stuff; changes as we go into
221 instance ContainsDynFlags
(Env gbl lcl
) where
222 extractDynFlags env
= hsc_dflags
(env_top env
)
224 instance ContainsModule gbl
=> ContainsModule
(Env gbl lcl
) where
225 extractModule env
= extractModule
(env_gbl env
)
229 ************************************************************************
231 The interface environments
232 Used when dealing with IfaceDecls
234 ************************************************************************
239 -- Some information about where this environment came from;
240 -- useful for debugging.
242 -- The type environment for the module being compiled,
243 -- in case the interface refers back to it via a reference that
244 -- was originally a hi-boot file.
245 -- We need the module name so we can test when it's appropriate
246 -- to look in this env.
247 -- See Note [Tying the knot] in TcIface
248 if_rec_types
:: Maybe (Module
, IfG TypeEnv
)
249 -- Allows a read effect, so it can be in a mutable
250 -- variable; c.f. handling the external package type env
251 -- Nothing => interactive stuff, no loops possible
256 -- The module for the current IfaceDecl
257 -- So if we see f = \x -> x
258 -- it means M.f = \x -> x, where M is the if_mod
259 -- NB: This is a semantic module, see
260 -- Note [Identity versus semantic module]
263 -- Whether or not the IfaceDecl came from a boot
264 -- file or not; we'll use this to choose between
265 -- NoUnfolding and BootUnfolding
268 -- The field is used only for error reporting
269 -- if (say) there's a Lint error in it
271 -- Where the interface came from:
272 -- .hi file, or GHCi state, or ext core
273 -- plus which bit is currently being examined
275 if_nsubst
:: Maybe NameShape
,
277 -- This field is used to make sure "implicit" declarations
278 -- (anything that cannot be exported in mi_exports) get
279 -- wired up correctly in typecheckIfacesForMerging. Most
280 -- of the time it's @Nothing@. See Note [Resolving never-exported Names in TcIface]
282 if_implicits_env
:: Maybe TypeEnv
,
284 if_tv_env
:: FastStringEnv TyVar
, -- Nested tyvar bindings
285 if_id_env
:: FastStringEnv Id
-- Nested id binding
289 ************************************************************************
293 ************************************************************************
295 Now the mondo monad magic (yes, @DsM@ is a silly name)---carry around
296 a @UniqueSupply@ and some annotations, which
297 presumably include source-file location information:
302 { ds_mod
:: Module
-- For SCC profiling
303 , ds_fam_inst_env
:: FamInstEnv
-- Like tcg_fam_inst_env
304 , ds_unqual
:: PrintUnqualified
305 , ds_msgs
:: IORef Messages
-- Warning messages
306 , ds_if_env
:: (IfGblEnv
, IfLclEnv
) -- Used for looking up global,
307 -- possibly-imported things
308 , ds_complete_matches
:: CompleteMatchMap
309 -- Additional complete pattern matches
310 , ds_cc_st
:: IORef CostCentreState
311 -- Tracking indices for cost centre annotations
314 instance ContainsModule DsGblEnv
where
315 extractModule
= ds_mod
317 data DsLclEnv
= DsLclEnv
{
318 dsl_meta
:: DsMetaEnv
, -- Template Haskell bindings
319 dsl_loc
:: RealSrcSpan
, -- To put in pattern-matching error msgs
321 -- See Note [Note [Type and Term Equality Propagation] in Check.hs
322 -- The oracle state Delta is augmented as we walk inwards,
323 -- through each pattern match in turn
327 -- Inside [| |] brackets, the desugarer looks
328 -- up variables in the DsMetaEnv
329 type DsMetaEnv
= NameEnv DsMetaVal
332 = DsBound Id
-- Bound by a pattern inside the [| |].
333 -- Will be dynamically alpha renamed.
334 -- The Id has type THSyntax.Var
336 | DsSplice
(HsExpr GhcTc
) -- These bindings are introduced by
337 -- the PendingSplices on a HsBracketOut
341 ************************************************************************
343 Global typechecker environment
345 ************************************************************************
348 -- | 'FrontendResult' describes the result of running the
349 -- frontend of a Haskell module. Usually, you'll get
350 -- a 'FrontendTypecheck', since running the frontend involves
351 -- typechecking a program, but for an hs-boot merge you'll
352 -- just get a ModIface, since no actual typechecking occurred.
354 -- This data type really should be in HscTypes, but it needs
355 -- to have a TcGblEnv which is only defined here.
357 = FrontendTypecheck TcGblEnv
359 -- Note [Identity versus semantic module]
360 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
361 -- When typechecking an hsig file, it is convenient to keep track
362 -- of two different "this module" identifiers:
364 -- - The IDENTITY module is simply thisPackage + the module
365 -- name; i.e. it uniquely *identifies* the interface file
366 -- we're compiling. For example, p[A=<A>]:A is an
367 -- identity module identifying the requirement named A
370 -- - The SEMANTIC module, which is the actual module that
371 -- this signature is intended to represent (e.g. if
372 -- we have a identity module p[A=base:Data.IORef]:A,
373 -- then the semantic module is base:Data.IORef)
375 -- Which one should you use?
377 -- - In the desugarer and later phases of compilation,
378 -- identity and semantic modules coincide, since we never compile
379 -- signatures (we just generate blank object files for
382 -- A corrolary of this is that the following invariant holds at any point
385 -- if I have a Module, this_mod, in hand representing the module
386 -- currently being compiled,
387 -- then moduleUnitId this_mod == thisPackage dflags
389 -- - For any code involving Names, we want semantic modules.
390 -- See lookupIfaceTop in IfaceEnv, mkIface and addFingerprints
391 -- in MkIface, and tcLookupGlobal in TcEnv
393 -- - When reading interfaces, we want the identity module to
394 -- identify the specific interface we want (such interfaces
395 -- should never be loaded into the EPS). However, if a
396 -- hole module <A> is requested, we look for A.hi
397 -- in the home library we are compiling. (See LoadIface.)
398 -- Similarly, in RnNames we check for self-imports using
399 -- identity modules, to allow signatures to import their implementor.
401 -- - For recompilation avoidance, you want the identity module,
402 -- since that will actually say the specific interface you
403 -- want to track (and recompile if it changes)
405 -- | 'TcGblEnv' describes the top-level of the module at the
406 -- point at which the typechecker is finished work.
407 -- It is this structure that is handed on to the desugarer
408 -- For state that needs to be updated during the typechecking
409 -- phase and returned at end, use a 'TcRef' (= 'IORef').
412 tcg_mod
:: Module
, -- ^ Module being compiled
413 tcg_semantic_mod
:: Module
, -- ^ If a signature, the backing module
414 -- See also Note [Identity versus semantic module]
415 tcg_src
:: HscSource
,
416 -- ^ What kind of module (regular Haskell, hs-boot, hsig)
418 tcg_rdr_env
:: GlobalRdrEnv
, -- ^ Top level envt; used during renaming
419 tcg_default
:: Maybe [Type
],
420 -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
422 tcg_fix_env
:: FixityEnv
, -- ^ Just for things in this module
423 tcg_field_env
:: RecFieldEnv
, -- ^ Just for things in this module
424 -- See Note [The interactive package] in HscTypes
426 tcg_type_env
:: TypeEnv
,
427 -- ^ Global type env for the module we are compiling now. All
428 -- TyCons and Classes (for this module) end up in here right away,
429 -- along with their derived constructors, selectors.
431 -- (Ids defined in this module start in the local envt, though they
432 -- move to the global envt during zonking)
434 -- NB: for what "things in this module" means, see
435 -- Note [The interactive package] in HscTypes
437 tcg_type_env_var
:: TcRef TypeEnv
,
438 -- Used only to initialise the interface-file
439 -- typechecker in initIfaceTcRn, so that it can see stuff
440 -- bound in this module when dealing with hi-boot recursions
441 -- Updated at intervals (e.g. after dealing with types and classes)
443 tcg_inst_env
:: !InstEnv
,
444 -- ^ Instance envt for all /home-package/ modules;
445 -- Includes the dfuns in tcg_insts
446 -- NB. BangPattern is to fix a leak, see #15111
447 tcg_fam_inst_env
:: !FamInstEnv
, -- ^ Ditto for family instances
448 -- NB. BangPattern is to fix a leak, see #15111
449 tcg_ann_env
:: AnnEnv
, -- ^ And for annotations
451 -- Now a bunch of things about this module that are simply
452 -- accumulated, but never consulted until the end.
453 -- Nevertheless, it's convenient to accumulate them along
454 -- with the rest of the info from this module.
455 tcg_exports
:: [AvailInfo
], -- ^ What is exported
456 tcg_imports
:: ImportAvails
,
457 -- ^ Information about what was imported from where, including
458 -- things bound in this module. Also store Safe Haskell info
459 -- here about transitive trusted package requirements.
461 -- There are not many uses of this field, so you can grep for
464 -- The ImportAvails records information about the following
467 -- 1. All of the modules you directly imported (tcRnImports)
468 -- 2. The orphans (only!) of all imported modules in a GHCi
469 -- session (runTcInteractive)
470 -- 3. The module that instantiated a signature
471 -- 4. Each of the signatures that merged in
473 -- It is used in the following ways:
474 -- - imp_orphs is used to determine what orphan modules should be
475 -- visible in the context (tcVisibleOrphanMods)
476 -- - imp_finsts is used to determine what family instances should
477 -- be visible (tcExtendLocalFamInstEnv)
478 -- - To resolve the meaning of the export list of a module
480 -- - imp_mods is used to compute usage info (mkIfaceTc, deSugar)
481 -- - imp_trust_own_pkg is used for Safe Haskell in interfaces
482 -- (mkIfaceTc, as well as in HscMain)
483 -- - To create the Dependencies field in interface (mkDependencies)
485 -- These three fields track unused bindings and imports
486 -- See Note [Tracking unused binding and imports]
488 tcg_used_gres
:: TcRef
[GlobalRdrElt
],
489 tcg_keep
:: TcRef NameSet
,
491 tcg_th_used
:: TcRef
Bool,
492 -- ^ @True@ <=> Template Haskell syntax used.
494 -- We need this so that we can generate a dependency on the
495 -- Template Haskell package, because the desugarer is going
496 -- to emit loads of references to TH symbols. The reference
497 -- is implicit rather than explicit, so we have to zap a
500 tcg_th_splice_used
:: TcRef
Bool,
501 -- ^ @True@ <=> A Template Haskell splice was used.
503 -- Splices disable recompilation avoidance (see #481)
505 tcg_dfun_n
:: TcRef OccSet
,
506 -- ^ Allows us to choose unique DFun names.
508 tcg_merged
:: [(Module
, Fingerprint
)],
509 -- ^ The requirements we merged with; we always have to recompile
510 -- if any of these changed.
512 -- The next fields accumulate the payload of the module
513 -- The binds, rules and foreign-decl fields are collected
514 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
516 tcg_rn_exports
:: Maybe [(Located
(IE GhcRn
), Avails
)],
517 -- Nothing <=> no explicit export list
518 -- Is always Nothing if we don't want to retain renamed
520 -- If present contains each renamed export list item
521 -- together with its exported names.
523 tcg_rn_imports
:: [LImportDecl GhcRn
],
524 -- Keep the renamed imports regardless. They are not
525 -- voluminous and are needed if you want to report unused imports
527 tcg_rn_decls
:: Maybe (HsGroup GhcRn
),
528 -- ^ Renamed decls, maybe. @Nothing@ <=> Don't retain renamed
531 tcg_dependent_files
:: TcRef
[FilePath], -- ^ dependencies from addDependentFile
533 tcg_th_topdecls
:: TcRef
[LHsDecl GhcPs
],
534 -- ^ Top-level declarations from addTopDecls
536 tcg_th_foreign_files
:: TcRef
[(ForeignSrcLang
, FilePath)],
537 -- ^ Foreign files emitted from TH.
539 tcg_th_topnames
:: TcRef NameSet
,
540 -- ^ Exact names bound in top-level declarations in tcg_th_topdecls
542 tcg_th_modfinalizers
:: TcRef
[(TcLclEnv
, ThModFinalizers
)],
543 -- ^ Template Haskell module finalizers.
545 -- They can use particular local environments.
547 tcg_th_coreplugins
:: TcRef
[String],
548 -- ^ Core plugins added by Template Haskell code.
550 tcg_th_state
:: TcRef
(Map TypeRep Dynamic
),
551 tcg_th_remote_state
:: TcRef
(Maybe (ForeignRef
(IORef QState
))),
552 -- ^ Template Haskell state
554 tcg_ev_binds
:: Bag EvBind
, -- Top-level evidence bindings
556 -- Things defined in this module, or (in GHCi)
557 -- in the declarations for a single GHCi command.
558 -- For the latter, see Note [The interactive package] in HscTypes
559 tcg_tr_module
:: Maybe Id
, -- Id for $trModule :: GHC.Types.Module
560 -- for which every module has a top-level defn
561 -- except in GHCi in which case we have Nothing
562 tcg_binds
:: LHsBinds GhcTc
, -- Value bindings in this module
563 tcg_sigs
:: NameSet
, -- ...Top-level names that *lack* a signature
564 tcg_imp_specs
:: [LTcSpecPrag
], -- ...SPECIALISE prags for imported Ids
565 tcg_warns
:: Warnings
, -- ...Warnings and deprecations
566 tcg_anns
:: [Annotation
], -- ...Annotations
567 tcg_tcs
:: [TyCon
], -- ...TyCons and Classes
568 tcg_insts
:: [ClsInst
], -- ...Instances
569 tcg_fam_insts
:: [FamInst
], -- ...Family instances
570 tcg_rules
:: [LRuleDecl GhcTc
], -- ...Rules
571 tcg_fords
:: [LForeignDecl GhcTc
], -- ...Foreign import & exports
572 tcg_patsyns
:: [PatSyn
], -- ...Pattern synonyms
574 tcg_doc_hdr
:: Maybe LHsDocString
, -- ^ Maybe Haddock header docs
575 tcg_hpc
:: !AnyHpcUsage
, -- ^ @True@ if any part of the
576 -- prog uses hpc instrumentation.
577 -- NB. BangPattern is to fix a leak, see #15111
579 tcg_self_boot
:: SelfBootInfo
, -- ^ Whether this module has a
580 -- corresponding hi-boot file
582 tcg_main
:: Maybe Name
, -- ^ The Name of the main
583 -- function, if this module is
586 tcg_safeInfer
:: TcRef
(Bool, WarningMessages
),
587 -- ^ Has the typechecker inferred this module as -XSafe (Safe Haskell)
588 -- See Note [Safe Haskell Overlapping Instances Implementation],
589 -- although this is used for more than just that failure case.
591 tcg_tc_plugins
:: [TcPluginSolver
],
592 -- ^ A list of user-defined plugins for the constraint solver.
593 tcg_hf_plugins
:: [HoleFitPlugin
],
594 -- ^ A list of user-defined plugins for hole fit suggestions.
596 tcg_top_loc
:: RealSrcSpan
,
597 -- ^ The RealSrcSpan this module came from
599 tcg_static_wc
:: TcRef WantedConstraints
,
600 -- ^ Wanted constraints of static forms.
601 -- See Note [Constraints in static forms].
602 tcg_complete_matches
:: [CompleteMatch
],
604 -- ^ Tracking indices for cost centre annotations
605 tcg_cc_st
:: TcRef CostCentreState
608 -- NB: topModIdentity, not topModSemantic!
609 -- Definition sites of orphan identities will be identity modules, not semantic
612 -- Note [Constraints in static forms]
613 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
615 -- When a static form produces constraints like
617 -- f :: StaticPtr (Bool -> String)
620 -- we collect them in tcg_static_wc and resolve them at the end
621 -- of type checking. They need to be resolved separately because
622 -- we don't want to resolve them in the context of the enclosing
623 -- expression. Consider
625 -- g :: Show a => StaticPtr (a -> String)
628 -- If the @Show a0@ constraint that the body of the static form produces was
629 -- resolved in the context of the enclosing expression, then the body of the
630 -- static form wouldn't be closed because the Show dictionary would come from
631 -- g's context instead of coming from the top level.
633 tcVisibleOrphanMods
:: TcGblEnv
-> ModuleSet
634 tcVisibleOrphanMods tcg_env
635 = mkModuleSet
(tcg_mod tcg_env
: imp_orphs
(tcg_imports tcg_env
))
637 instance ContainsModule TcGblEnv
where
638 extractModule env
= tcg_semantic_mod env
640 type RecFieldEnv
= NameEnv
[FieldLabel
]
641 -- Maps a constructor name *in this module*
642 -- to the fields for that constructor.
643 -- This is used when dealing with ".." notation in record
644 -- construction and pattern matching.
645 -- The FieldEnv deals *only* with constructors defined in *this*
646 -- module. For imported modules, we get the same info from the
650 = NoSelfBoot
-- No corresponding hi-boot file
652 { sb_mds
:: ModDetails
-- There was a hi-boot file,
653 , sb_tcs
:: NameSet
} -- defining these TyCons,
654 -- What is sb_tcs used for? See Note [Extra dependencies from .hs-boot files]
658 {- Note [Tracking unused binding and imports]
659 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
660 We gather three sorts of usage information
662 * tcg_dus :: DefUses (defs/uses)
663 Records what is defined in this module and what is used.
665 Records *defined* Names (local, top-level)
666 and *used* Names (local or imported)
668 Used (a) to report "defined but not used"
669 (see RnNames.reportUnusedNames)
670 (b) to generate version-tracking usage info in interface
671 files (see MkIface.mkUsedNames)
672 This usage info is mainly gathered by the renamer's
673 gathering of free-variables
675 * tcg_used_gres :: TcRef [GlobalRdrElt]
676 Records occurrences of imported entities.
678 Used only to report unused import declarations
680 Records each *occurrence* an *imported* (not locally-defined) entity.
681 The occurrence is recorded by keeping a GlobalRdrElt for it.
682 These is not the GRE that is in the GlobalRdrEnv; rather it
683 is recorded *after* the filtering done by pickGREs. So it reflect
684 /how that occurrence is in scope/. See Note [GRE filtering] in
687 * tcg_keep :: TcRef NameSet
688 Records names of the type constructors, data constructors, and Ids that
689 are used by the constraint solver.
691 The typechecker may use find that some imported or
692 locally-defined things are used, even though they
693 do not appear to be mentioned in the source code:
695 (a) The to/from functions for generic data types
697 (b) Top-level variables appearing free in the RHS of an
700 (c) Top-level variables appearing free in a TH bracket
701 See Note [Keeping things alive for Template Haskell]
704 (d) The data constructor of a newtype that is used
705 to solve a Coercible instance (e.g. #10347). Example
706 module T10347 (N, mkN) where
708 newtype N a = MkN Int
712 Then we wish to record `MkN` as used, since it is (morally)
713 used to perform the coercion in `mkN`. To do so, the
714 Coercible solver updates tcg_keep's TcRef whenever it
715 encounters a use of `coerce` that crosses newtype boundaries.
717 The tcg_keep field is used in two distinct ways:
719 * Desugar.addExportFlagsAndRules. Where things like (a-c) are locally
720 defined, we should give them an an Exported flag, so that the
721 simplifier does not discard them as dead code, and so that they are
722 exposed in the interface file (but not to export to the user).
724 * RnNames.reportUnusedNames. Where newtype data constructors like (d)
725 are imported, we don't want to report them as unused.
728 ************************************************************************
730 The local typechecker environment
732 ************************************************************************
734 Note [The Global-Env/Local-Env story]
735 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
736 During type checking, we keep in the tcg_type_env
737 * All types and classes
738 * All Ids derived from types and classes (constructors, selectors)
740 At the end of type checking, we zonk the local bindings,
741 and as we do so we add to the tcg_type_env
742 * Locally defined top-level Ids
744 Why? Because they are now Ids not TcIds. This final GlobalEnv is
745 a) fed back (via the knot) to typechecking the
746 unfoldings of interface signatures
747 b) used in the ModDetails of this module
750 data TcLclEnv
-- Changes as we move inside an expression
751 -- Discarded after typecheck/rename; not passed on to desugarer
753 tcl_loc
:: RealSrcSpan
, -- Source span
754 tcl_ctxt
:: [ErrCtxt
], -- Error context, innermost on top
755 tcl_tclvl
:: TcLevel
, -- Birthplace for new unification variables
757 tcl_th_ctxt
:: ThStage
, -- Template Haskell context
758 tcl_th_bndrs
:: ThBindEnv
, -- and binder info
759 -- The ThBindEnv records the TH binding level of in-scope Names
760 -- defined in this module (not imported)
761 -- We can't put this info in the TypeEnv because it's needed
762 -- (and extended) in the renamer, for untyed splices
764 tcl_arrow_ctxt
:: ArrowCtxt
, -- Arrow-notation context
766 tcl_rdr
:: LocalRdrEnv
, -- Local name envt
767 -- Maintained during renaming, of course, but also during
768 -- type checking, solely so that when renaming a Template-Haskell
769 -- splice we have the right environment for the renamer.
771 -- Does *not* include global name envt; may shadow it
772 -- Includes both ordinary variables and type variables;
773 -- they are kept distinct because tyvar have a different
774 -- occurrence constructor (Name.TvOcc)
775 -- We still need the unsullied global name env so that
776 -- we can look up record field names
778 tcl_env
:: TcTypeEnv
, -- The local type environment:
779 -- Ids and TyVars defined in this module
781 tcl_bndrs
:: TcBinderStack
, -- Used for reporting relevant bindings,
782 -- and for tidying types
784 tcl_lie
:: TcRef WantedConstraints
, -- Place to accumulate type constraints
785 tcl_errs
:: TcRef Messages
-- Place to accumulate errors
788 setLclEnvTcLevel
:: TcLclEnv
-> TcLevel
-> TcLclEnv
789 setLclEnvTcLevel env lvl
= env
{ tcl_tclvl
= lvl
}
791 getLclEnvTcLevel
:: TcLclEnv
-> TcLevel
792 getLclEnvTcLevel
= tcl_tclvl
794 setLclEnvLoc
:: TcLclEnv
-> RealSrcSpan
-> TcLclEnv
795 setLclEnvLoc env loc
= env
{ tcl_loc
= loc
}
797 getLclEnvLoc
:: TcLclEnv
-> RealSrcSpan
798 getLclEnvLoc
= tcl_loc
800 type ErrCtxt
= (Bool, TidyEnv
-> TcM
(TidyEnv
, MsgDoc
))
801 -- Monadic so that we have a chance
802 -- to deal with bound type variables just before error
803 -- message construction
805 -- Bool: True <=> this is a landmark context; do not
806 -- discard it when trimming for display
808 -- These are here to avoid module loops: one might expect them
809 -- in Constraint, but they refer to ErrCtxt which refers to TcM.
810 -- Easier to just keep these definitions here, alongside TcM.
811 pushErrCtxt
:: CtOrigin
-> ErrCtxt
-> CtLoc
-> CtLoc
812 pushErrCtxt o err loc
@(CtLoc
{ ctl_env
= lcl
})
813 = loc
{ ctl_origin
= o
, ctl_env
= lcl
{ tcl_ctxt
= err
: tcl_ctxt lcl
} }
815 pushErrCtxtSameOrigin
:: ErrCtxt
-> CtLoc
-> CtLoc
816 -- Just add information w/o updating the origin!
817 pushErrCtxtSameOrigin err loc
@(CtLoc
{ ctl_env
= lcl
})
818 = loc
{ ctl_env
= lcl
{ tcl_ctxt
= err
: tcl_ctxt lcl
} }
820 type TcTypeEnv
= NameEnv TcTyThing
822 type ThBindEnv
= NameEnv
(TopLevelFlag
, ThLevel
)
823 -- Domain = all Ids bound in this module (ie not imported)
824 -- The TopLevelFlag tells if the binding is syntactically top level.
825 -- We need to know this, because the cross-stage persistence story allows
826 -- cross-stage at arbitrary types if the Id is bound at top level.
828 -- Nota bene: a ThLevel of 'outerLevel' is *not* the same as being
829 -- bound at top level! See Note [Template Haskell levels] in TcSplice
831 {- Note [Given Insts]
833 Because of GADTs, we have to pass inwards the Insts provided by type signatures
834 and existential contexts. Consider
835 data T a where { T1 :: b -> b -> T [b] }
836 f :: Eq a => T a -> Bool
837 f (T1 x y) = [x]==[y]
839 The constructor T1 binds an existential variable 'b', and we need Eq [b].
840 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
845 -- | Type alias for 'IORef'; the convention is we'll use this for mutable
846 -- bits of data in 'TcGblEnv' which are updated during typechecking and
847 -- returned at the end.
848 type TcRef a
= IORef a
849 -- ToDo: when should I refer to it as a 'TcId' instead of an 'Id'?
853 ---------------------------
855 ---------------------------
857 type TcBinderStack
= [TcBinder
]
858 -- This is a stack of locally-bound ids and tyvars,
860 -- Used only in error reporting (relevantBindings in TcError),
862 -- We can't use the tcl_env type environment, because it doesn't
863 -- keep track of the nesting order
868 TopLevelFlag
-- Tells whether the binding is syntactically top-level
869 -- (The monomorphic Ids for a recursive group count
870 -- as not-top-level for this purpose.)
872 | TcIdBndr_ExpType
-- Variant that allows the type to be specified as
878 | TcTvBndr
-- e.g. case x of P (y::a) -> blah
879 Name
-- We bind the lexical name "a" to the type of y,
880 TyVar
-- which might be an utterly different (perhaps
881 -- existential) tyvar
883 instance Outputable TcBinder
where
884 ppr
(TcIdBndr
id top_lvl
) = ppr
id <> brackets
(ppr top_lvl
)
885 ppr
(TcIdBndr_ExpType
id _ top_lvl
) = ppr
id <> brackets
(ppr top_lvl
)
886 ppr
(TcTvBndr name tv
) = ppr name
<+> ppr tv
888 instance HasOccName TcBinder
where
889 occName
(TcIdBndr
id _
) = occName
(idName
id)
890 occName
(TcIdBndr_ExpType name _ _
) = occName name
891 occName
(TcTvBndr name _
) = occName name
894 -- Builds up a list of bindings whose OccName has not been seen before
895 -- i.e., If ys = removeBindingShadowing xs
897 -- - ys is obtained from xs by deleting some elements
898 -- - ys has no duplicate OccNames
899 -- - The first duplicated OccName in xs is retained in ys
900 -- Overloaded so that it can be used for both GlobalRdrElt in typed-hole
901 -- substitutions and TcBinder when looking for relevant bindings.
902 removeBindingShadowing
:: HasOccName a
=> [a
] -> [a
]
903 removeBindingShadowing bindings
= reverse $ fst $ foldl
904 (\(bindingAcc
, seenNames
) binding
->
905 if occName binding `elemOccSet` seenNames
-- if we've seen it
906 then (bindingAcc
, seenNames
) -- skip it
907 else (binding
:bindingAcc
, extendOccSet seenNames
(occName binding
)))
908 ([], emptyOccSet
) bindings
910 ---------------------------
911 -- Template Haskell stages and levels
912 ---------------------------
914 data SpliceType
= Typed | Untyped
916 data ThStage
-- See Note [Template Haskell state diagram] in TcSplice
917 = Splice SpliceType
-- Inside a top-level splice
918 -- This code will be run *at compile time*;
919 -- the result replaces the splice
922 | RunSplice
(TcRef
[ForeignRef
(TH
.Q
())])
923 -- Set when running a splice, i.e. NOT when renaming or typechecking the
924 -- Haskell code for the splice. See Note [RunSplice ThLevel].
926 -- Contains a list of mod finalizers collected while executing the splice.
928 -- 'addModFinalizer' inserts finalizers here, and from here they are taken
929 -- to construct an @HsSpliced@ annotation for untyped splices. See Note
930 -- [Delaying modFinalizers in untyped splices] in "RnSplice".
932 -- For typed splices, the typechecker takes finalizers from here and
933 -- inserts them in the list of finalizers in the global environment.
935 -- See Note [Collecting modFinalizers in typed splices] in "TcSplice".
937 | Comp
-- Ordinary Haskell code
940 | Brack
-- Inside brackets
941 ThStage
-- Enclosing stage
945 = RnPendingUntyped
-- Renaming the inside of an *untyped* bracket
946 (TcRef
[PendingRnSplice
]) -- Pending splices in here
948 | RnPendingTyped
-- Renaming the inside of a *typed* bracket
950 | TcPending
-- Typechecking the inside of a typed bracket
951 (TcRef
[PendingTcSplice
]) -- Accumulate pending splices here
952 (TcRef WantedConstraints
) -- and type constraints here
954 topStage
, topAnnStage
, topSpliceStage
:: ThStage
956 topAnnStage
= Splice Untyped
957 topSpliceStage
= Splice Untyped
959 instance Outputable ThStage
where
960 ppr
(Splice _
) = text
"Splice"
961 ppr
(RunSplice _
) = text
"RunSplice"
962 ppr Comp
= text
"Comp"
963 ppr
(Brack s _
) = text
"Brack" <> parens
(ppr s
)
966 -- NB: see Note [Template Haskell levels] in TcSplice
967 -- Incremented when going inside a bracket,
968 -- decremented when going inside a splice
969 -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
970 -- original "Template meta-programming for Haskell" paper
972 impLevel
, outerLevel
:: ThLevel
973 impLevel
= 0 -- Imported things; they can be used inside a top level splice
974 outerLevel
= 1 -- Things defined outside brackets
976 thLevel
:: ThStage
-> ThLevel
977 thLevel
(Splice _
) = 0
978 thLevel
(RunSplice _
) =
979 -- See Note [RunSplice ThLevel].
980 panic
"thLevel: called when running a splice"
982 thLevel
(Brack s _
) = thLevel s
+ 1
984 {- Node [RunSplice ThLevel]
985 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
986 The 'RunSplice' stage is set when executing a splice, and only when running a
987 splice. In particular it is not set when the splice is renamed or typechecked.
989 'RunSplice' is needed to provide a reference where 'addModFinalizer' can insert
990 the finalizer (see Note [Delaying modFinalizers in untyped splices]), and
991 'addModFinalizer' runs when doing Q things. Therefore, It doesn't make sense to
992 set 'RunSplice' when renaming or typechecking the splice, where 'Splice',
993 'Brack' or 'Comp' are used instead.
997 ---------------------------
998 -- Arrow-notation context
999 ---------------------------
1001 {- Note [Escaping the arrow scope]
1002 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1003 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
1004 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
1007 proc x -> (e1 -< e2)
1009 Here, x is not in scope in e1, but it is in scope in e2. This can get
1013 proc y -> (proc z -> e1) -< e2
1015 Here, x and z are in scope in e1, but y is not.
1017 We implement this by
1018 recording the environment when passing a proc (using newArrowScope),
1019 and returning to that (using escapeArrowScope) on the left of -< and the
1022 All this can be dealt with by the *renamer*. But the type checker needs
1023 to be involved too. Example (arrowfail001)
1024 class Foo a where foo :: a -> ()
1025 data Bar = forall a. Foo a => Bar a
1027 get = proc x -> case x of Bar a -> foo -< a
1028 Here the call of 'foo' gives rise to a (Foo a) constraint that should not
1029 be captured by the pattern match on 'Bar'. Rather it should join the
1030 constraints from further out. So we must capture the constraint bag
1031 from further out in the ArrowCtxt that we push inwards.
1034 data ArrowCtxt
-- Note [Escaping the arrow scope]
1036 | ArrowCtxt LocalRdrEnv
(TcRef WantedConstraints
)
1039 ---------------------------
1041 ---------------------------
1043 -- | A typecheckable thing available in a local context. Could be
1044 -- 'AGlobal' 'TyThing', but also lexically scoped variables, etc.
1045 -- See 'TcEnv' for how to retrieve a 'TyThing' given a 'Name'.
1047 = AGlobal TyThing
-- Used only in the return type of a lookup
1049 | ATcId
-- Ids defined in this module; may not be fully zonked
1051 , tct_info
:: IdBindingInfo
-- See Note [Meaning of IdBindingInfo]
1054 | ATyVar Name TcTyVar
-- See Note [Type variables in the type environment]
1056 | ATcTyCon TyCon
-- Used temporarily, during kind checking, for the
1057 -- tycons and clases in this recursive group
1058 -- The TyCon is always a TcTyCon. Its kind
1059 -- can be a mono-kind or a poly-kind; in TcTyClsDcls see
1060 -- Note [Type checking recursive type and class declarations]
1062 | APromotionErr PromotionErr
1065 = TyConPE
-- TyCon used in a kind before we are ready
1066 -- data T :: T -> * where ...
1067 | ClassPE
-- Ditto Class
1069 | FamDataConPE
-- Data constructor for a data family
1070 -- See Note [AFamDataCon: not promoting data family constructors]
1072 | ConstrainedDataConPE PredType
1073 -- Data constructor with a non-equality context
1074 -- See Note [Don't promote data constructors with
1075 -- non-equality contexts] in TcHsType
1076 | PatSynPE
-- Pattern synonyms
1077 -- See Note [Don't promote pattern synonyms] in TcEnv
1079 | RecDataConPE
-- Data constructor in a recursive loop
1080 -- See Note [Recursion and promoting data constructors] in TcTyClsDecls
1081 | NoDataKindsTC
-- -XDataKinds not enabled (for a tycon)
1082 | NoDataKindsDC
-- -XDataKinds not enabled (for a datacon)
1084 instance Outputable TcTyThing
where -- Debugging only
1085 ppr
(AGlobal g
) = ppr g
1086 ppr elt
@(ATcId
{}) = text
"Identifier" <>
1087 brackets
(ppr
(tct_id elt
) <> dcolon
1088 <> ppr
(varType
(tct_id elt
)) <> comma
1089 <+> ppr
(tct_info elt
))
1090 ppr
(ATyVar n tv
) = text
"Type variable" <+> quotes
(ppr n
) <+> equals
<+> ppr tv
1091 <+> dcolon
<+> ppr
(varType tv
)
1092 ppr
(ATcTyCon tc
) = text
"ATcTyCon" <+> ppr tc
<+> dcolon
<+> ppr
(tyConKind tc
)
1093 ppr
(APromotionErr err
) = text
"APromotionErr" <+> ppr err
1095 -- | IdBindingInfo describes how an Id is bound.
1097 -- It is used for the following purposes:
1098 -- a) for static forms in TcExpr.checkClosedInStaticForm and
1099 -- b) to figure out when a nested binding can be generalised,
1100 -- in TcBinds.decideGeneralisationPlan.
1102 data IdBindingInfo
-- See Note [Meaning of IdBindingInfo and ClosedTypeId]
1106 RhsNames
-- Used for (static e) checks only
1107 ClosedTypeId
-- Used for generalisation checks
1108 -- and for (static e) checks
1110 -- | IsGroupClosed describes a group of mutually-recursive bindings
1113 (NameEnv RhsNames
) -- Free var info for the RHS of each binding in the goup
1114 -- Used only for (static e) checks
1116 ClosedTypeId
-- True <=> all the free vars of the group are
1117 -- imported or ClosedLet or
1118 -- NonClosedLet with ClosedTypeId=True.
1119 -- In particular, no tyvars, no NotLetBound
1121 type RhsNames
= NameSet
-- Names of variables, mentioned on the RHS of
1122 -- a definition, that are not Global or ClosedLet
1124 type ClosedTypeId
= Bool
1125 -- See Note [Meaning of IdBindingInfo and ClosedTypeId]
1127 {- Note [Meaning of IdBindingInfo]
1128 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1129 NotLetBound means that
1130 the Id is not let-bound (e.g. it is bound in a
1131 lambda-abstraction or in a case pattern)
1133 ClosedLet means that
1134 - The Id is let-bound,
1135 - Any free term variables are also Global or ClosedLet
1136 - Its type has no free variables (NB: a top-level binding subject
1137 to the MR might have free vars in its type)
1138 These ClosedLets can definitely be floated to top level; and we
1139 may need to do so for static forms.
1143 NonClosedLet emptyNameSet True
1145 (NonClosedLet (fvs::RhsNames) (cl::ClosedTypeId)) means that
1146 - The Id is let-bound
1148 - The fvs::RhsNames contains the free names of the RHS,
1149 excluding Global and ClosedLet ones.
1151 - For the ClosedTypeId field see Note [Bindings with closed types]
1153 For (static e) to be valid, we need for every 'x' free in 'e',
1154 that x's binding is floatable to the top level. Specifically:
1155 * x's RhsNames must be empty
1156 * x's type has no free variables
1157 See Note [Grand plan for static forms] in StaticPtrTable.hs.
1158 This test is made in TcExpr.checkClosedInStaticForm.
1159 Actually knowing x's RhsNames (rather than just its emptiness
1160 or otherwise) is just so we can produce better error messages
1162 Note [Bindings with closed types: ClosedTypeId]
1163 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1166 f x = let g ys = map not ys
1169 Can we generalise 'g' under the OutsideIn algorithm? Yes,
1170 because all g's free variables are top-level; that is they themselves
1171 have no free type variables, and it is the type variables in the
1172 environment that makes things tricky for OutsideIn generalisation.
1174 Here's the invariant:
1175 If an Id has ClosedTypeId=True (in its IdBindingInfo), then
1176 the Id's type is /definitely/ closed (has no free type variables).
1178 a) The Id's acutal type is closed (has no free tyvars)
1179 b) Either the Id has a (closed) user-supplied type signature
1180 or all its free variables are Global/ClosedLet
1181 or NonClosedLet with ClosedTypeId=True.
1182 In particular, none are NotLetBound.
1184 Why is (b) needed? Consider
1185 \x. (x :: Int, let y = x+1 in ...)
1186 Initially x::alpha. If we happen to typecheck the 'let' before the
1187 (x::Int), y's type will have a free tyvar; but if the other way round
1188 it won't. So we treat any let-bound variable with a free
1189 non-let-bound variable as not ClosedTypeId, regardless of what the
1190 free vars of its type actually are.
1192 But if it has a signature, all is well:
1193 \x. ...(let { y::Int; y = x+1 } in
1194 let { v = y+2 } in ...)...
1195 Here the signature on 'v' makes 'y' a ClosedTypeId, so we can
1200 * A top-level binding may not have ClosedTypeId=True, if it suffers
1203 * A nested binding may be closed (eg 'g' in the example we started
1204 with). Indeed, that's the point; whether a function is defined at
1205 top level or nested is orthogonal to the question of whether or
1208 * A binding may be non-closed because it mentions a lexically scoped
1211 f x = let g y = ...(y::a)...
1213 Under OutsideIn we are free to generalise an Id all of whose free
1214 variables have ClosedTypeId=True (or imported). This is an extension
1215 compared to the JFP paper on OutsideIn, which used "top-level" as a
1216 proxy for "closed". (It's not a good proxy anyway -- the MR can make
1217 a top-level binding with a free type variable.)
1219 Note [Type variables in the type environment]
1220 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1221 The type environment has a binding for each lexically-scoped
1222 type variable that is in scope. For example
1224 f :: forall a. a -> a
1228 g1 (ys :: [b]) = head ys :: b
1231 g2 (ys :: [c]) = head ys :: c
1233 * The forall'd variable 'a' in the signature scopes over f's RHS.
1235 * The pattern-bound type variable 'b' in 'g1' scopes over g1's
1236 RHS; note that it is bound to a skolem 'a' which is not itself
1239 * The pattern-bound type variable 'c' in 'g2' is bound to
1240 Int; that is, pattern-bound type variables can stand for
1241 arbitrary types. (see
1242 GHC proposal #128 "Allow ScopedTypeVariables to refer to types"
1243 https://github.com/ghc-proposals/ghc-proposals/pull/128,
1245 "Type variables in patterns", Haskell Symposium 2018.
1248 This is implemented by the constructor
1250 in the type environment.
1252 * The Name is the name of the original, lexically scoped type
1255 * The TcTyVar is sometimes a skolem (like in 'f'), and sometimes
1256 a unification variable (like in 'g1', 'g2'). We never zonk the
1257 type environment so in the latter case it always stays as a
1258 unification variable, although that variable may be later
1259 unified with a type (such as Int in 'g2').
1262 instance Outputable IdBindingInfo
where
1263 ppr NotLetBound
= text
"NotLetBound"
1264 ppr ClosedLet
= text
"TopLevelLet"
1265 ppr
(NonClosedLet fvs closed_type
) =
1266 text
"TopLevelLet" <+> ppr fvs
<+> ppr closed_type
1268 instance Outputable PromotionErr
where
1269 ppr ClassPE
= text
"ClassPE"
1270 ppr TyConPE
= text
"TyConPE"
1271 ppr PatSynPE
= text
"PatSynPE"
1272 ppr FamDataConPE
= text
"FamDataConPE"
1273 ppr
(ConstrainedDataConPE
pred) = text
"ConstrainedDataConPE"
1274 <+> parens
(ppr
pred)
1275 ppr RecDataConPE
= text
"RecDataConPE"
1276 ppr NoDataKindsTC
= text
"NoDataKindsTC"
1277 ppr NoDataKindsDC
= text
"NoDataKindsDC"
1279 pprTcTyThingCategory
:: TcTyThing
-> SDoc
1280 pprTcTyThingCategory
(AGlobal thing
) = pprTyThingCategory thing
1281 pprTcTyThingCategory
(ATyVar
{}) = text
"Type variable"
1282 pprTcTyThingCategory
(ATcId
{}) = text
"Local identifier"
1283 pprTcTyThingCategory
(ATcTyCon
{}) = text
"Local tycon"
1284 pprTcTyThingCategory
(APromotionErr pe
) = pprPECategory pe
1286 pprPECategory
:: PromotionErr
-> SDoc
1287 pprPECategory ClassPE
= text
"Class"
1288 pprPECategory TyConPE
= text
"Type constructor"
1289 pprPECategory PatSynPE
= text
"Pattern synonym"
1290 pprPECategory FamDataConPE
= text
"Data constructor"
1291 pprPECategory ConstrainedDataConPE
{} = text
"Data constructor"
1292 pprPECategory RecDataConPE
= text
"Data constructor"
1293 pprPECategory NoDataKindsTC
= text
"Type constructor"
1294 pprPECategory NoDataKindsDC
= text
"Data constructor"
1297 ************************************************************************
1299 Operations over ImportAvails
1301 ************************************************************************
1304 -- | 'ImportAvails' summarises what was imported from where, irrespective of
1305 -- whether the imported things are actually used or not. It is used:
1307 -- * when processing the export list,
1309 -- * when constructing usage info for the interface file,
1311 -- * to identify the list of directly imported modules for initialisation
1312 -- purposes and for optimised overlap checking of family instances,
1314 -- * when figuring out what things are really unused
1318 imp_mods
:: ImportedMods
,
1319 -- = ModuleEnv [ImportedModsVal],
1320 -- ^ Domain is all directly-imported modules
1322 -- See the documentation on ImportedModsVal in HscTypes for the
1323 -- meaning of the fields.
1325 -- We need a full ModuleEnv rather than a ModuleNameEnv here,
1326 -- because we might be importing modules of the same name from
1327 -- different packages. (currently not the case, but might be in the
1330 imp_dep_mods
:: ModuleNameEnv
(ModuleName
, IsBootInterface
),
1331 -- ^ Home-package modules needed by the module being compiled
1333 -- It doesn't matter whether any of these dependencies
1334 -- are actually /used/ when compiling the module; they
1335 -- are listed if they are below it at all. For
1336 -- example, suppose M imports A which imports X. Then
1337 -- compiling M might not need to consult X.hi, but X
1338 -- is still listed in M's dependencies.
1340 imp_dep_pkgs
:: Set InstalledUnitId
,
1341 -- ^ Packages needed by the module being compiled, whether directly,
1342 -- or via other modules in this package, or via modules imported
1343 -- from other packages.
1345 imp_trust_pkgs
:: Set InstalledUnitId
,
1346 -- ^ This is strictly a subset of imp_dep_pkgs and records the
1347 -- packages the current module needs to trust for Safe Haskell
1348 -- compilation to succeed. A package is required to be trusted if
1349 -- we are dependent on a trustworthy module in that package.
1350 -- While perhaps making imp_dep_pkgs a tuple of (UnitId, Bool)
1351 -- where True for the bool indicates the package is required to be
1352 -- trusted is the more logical design, doing so complicates a lot
1353 -- of code not concerned with Safe Haskell.
1354 -- See Note [RnNames . Tracking Trust Transitively]
1356 imp_trust_own_pkg
:: Bool,
1357 -- ^ Do we require that our own package is trusted?
1358 -- This is to handle efficiently the case where a Safe module imports
1359 -- a Trustworthy module that resides in the same package as it.
1360 -- See Note [RnNames . Trust Own Package]
1362 imp_orphs
:: [Module
],
1363 -- ^ Orphan modules below us in the import tree (and maybe including
1364 -- us for imported modules)
1366 imp_finsts
:: [Module
]
1367 -- ^ Family instance modules below us in the import tree (and maybe
1368 -- including us for imported modules)
1371 mkModDeps
:: [(ModuleName
, IsBootInterface
)]
1372 -> ModuleNameEnv
(ModuleName
, IsBootInterface
)
1373 mkModDeps deps
= foldl' add emptyUFM deps
1375 add env elt
@(m
,_
) = addToUFM env m elt
1378 :: ModuleNameEnv
(ModuleName
, IsBootInterface
)
1379 -> [(ModuleName
, IsBootInterface
)]
1380 modDepsElts
= sort . nonDetEltsUFM
1381 -- It's OK to use nonDetEltsUFM here because sorting by module names
1382 -- restores determinism
1384 emptyImportAvails
:: ImportAvails
1385 emptyImportAvails
= ImportAvails
{ imp_mods
= emptyModuleEnv
,
1386 imp_dep_mods
= emptyUFM
,
1387 imp_dep_pkgs
= S
.empty,
1388 imp_trust_pkgs
= S
.empty,
1389 imp_trust_own_pkg
= False,
1393 -- | Union two ImportAvails
1395 -- This function is a key part of Import handling, basically
1396 -- for each import we create a separate ImportAvails structure
1397 -- and then union them all together with this function.
1398 plusImportAvails
:: ImportAvails
-> ImportAvails
-> ImportAvails
1400 (ImportAvails
{ imp_mods
= mods1
,
1401 imp_dep_mods
= dmods1
, imp_dep_pkgs
= dpkgs1
,
1402 imp_trust_pkgs
= tpkgs1
, imp_trust_own_pkg
= tself1
,
1403 imp_orphs
= orphs1
, imp_finsts
= finsts1
})
1404 (ImportAvails
{ imp_mods
= mods2
,
1405 imp_dep_mods
= dmods2
, imp_dep_pkgs
= dpkgs2
,
1406 imp_trust_pkgs
= tpkgs2
, imp_trust_own_pkg
= tself2
,
1407 imp_orphs
= orphs2
, imp_finsts
= finsts2
})
1408 = ImportAvails
{ imp_mods
= plusModuleEnv_C
(++) mods1 mods2
,
1409 imp_dep_mods
= plusUFM_C plus_mod_dep dmods1 dmods2
,
1410 imp_dep_pkgs
= dpkgs1 `S
.union` dpkgs2
,
1411 imp_trust_pkgs
= tpkgs1 `S
.union` tpkgs2
,
1412 imp_trust_own_pkg
= tself1 || tself2
,
1413 imp_orphs
= orphs1 `unionLists` orphs2
,
1414 imp_finsts
= finsts1 `unionLists` finsts2
}
1416 plus_mod_dep r1
@(m1
, boot1
) r2
@(m2
, boot2
)
1417 | ASSERT2
( m1
== m2
, (ppr m1
<+> ppr m2
) $$ (ppr boot1
<+> ppr boot2
) )
1420 -- If either side can "see" a non-hi-boot interface, use that
1421 -- Reusing existing tuples saves 10% of allocations on test
1422 -- perf/compiler/MultiLayerModules
1425 ************************************************************************
1427 \subsection{Where from}
1429 ************************************************************************
1431 The @WhereFrom@ type controls where the renamer looks for an interface file
1435 = ImportByUser IsBootInterface
-- Ordinary user import (perhaps {-# SOURCE #-})
1436 | ImportBySystem
-- Non user import.
1437 | ImportByPlugin
-- Importing a plugin;
1438 -- See Note [Care with plugin imports] in LoadIface
1440 instance Outputable WhereFrom
where
1441 ppr
(ImportByUser is_boot
) | is_boot
= text
"{- SOURCE -}"
1443 ppr ImportBySystem
= text
"{- SYSTEM -}"
1444 ppr ImportByPlugin
= text
"{- PLUGIN -}"
1447 {- *********************************************************************
1451 ********************************************************************* -}
1453 -- These data types need to be here only because
1454 -- TcSimplify uses them, and TcSimplify is fairly
1455 -- low down in the module hierarchy
1457 type TcSigFun
= Name
-> Maybe TcSigInfo
1459 data TcSigInfo
= TcIdSig TcIdSigInfo
1460 | TcPatSynSig TcPatSynInfo
1462 data TcIdSigInfo
-- See Note [Complete and partial type signatures]
1463 = CompleteSig
-- A complete signature with no wildcards,
1464 -- so the complete polymorphic type is known.
1465 { sig_bndr
:: TcId
-- The polymorphic Id with that type
1467 , sig_ctxt
:: UserTypeCtxt
-- In the case of type-class default methods,
1468 -- the Name in the FunSigCtxt is not the same
1469 -- as the TcId; the former is 'op', while the
1470 -- latter is '$dmop' or some such
1472 , sig_loc
:: SrcSpan
-- Location of the type signature
1475 | PartialSig
-- A partial type signature (i.e. includes one or more
1476 -- wildcards). In this case it doesn't make sense to give
1477 -- the polymorphic Id, because we are going to /infer/ its
1478 -- type, so we can't make the polymorphic Id ab-initio
1479 { psig_name
:: Name
-- Name of the function; used when report wildcards
1480 , psig_hs_ty
:: LHsSigWcType GhcRn
-- The original partial signature in
1482 , sig_ctxt
:: UserTypeCtxt
1483 , sig_loc
:: SrcSpan
-- Location of the type signature
1487 {- Note [Complete and partial type signatures]
1488 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1489 A type signature is partial when it contains one or more wildcards
1490 (= type holes). The wildcard can either be:
1491 * A (type) wildcard occurring in sig_theta or sig_tau. These are
1494 g :: Eq _a => _a -> _a -> Bool
1495 * Or an extra-constraints wildcard, stored in sig_cts:
1496 h :: (Num a, _) => a -> a
1498 A type signature is a complete type signature when there are no
1499 wildcards in the type signature, i.e. iff sig_wcs is empty and
1500 sig_extra_cts is Nothing.
1504 = TISI
{ sig_inst_sig
:: TcIdSigInfo
1506 , sig_inst_skols
:: [(Name
, TcTyVar
)]
1507 -- Instantiated type and kind variables, TyVarTvs
1508 -- The Name is the Name that the renamer chose;
1509 -- but the TcTyVar may come from instantiating
1510 -- the type and hence have a different unique.
1511 -- No need to keep track of whether they are truly lexically
1512 -- scoped because the renamer has named them uniquely
1513 -- See Note [Binding scoped type variables] in TcSigs
1515 -- NB: The order of sig_inst_skols is irrelevant
1516 -- for a CompleteSig, but for a PartialSig see
1517 -- Note [Quantified varaibles in partial type signatures]
1519 , sig_inst_theta
:: TcThetaType
1520 -- Instantiated theta. In the case of a
1521 -- PartialSig, sig_theta does not include
1522 -- the extra-constraints wildcard
1524 , sig_inst_tau
:: TcSigmaType
-- Instantiated tau
1525 -- See Note [sig_inst_tau may be polymorphic]
1527 -- Relevant for partial signature only
1528 , sig_inst_wcs
:: [(Name
, TcTyVar
)]
1529 -- Like sig_inst_skols, but for /named/ wildcards (_a etc).
1530 -- The named wildcards scope over the binding, and hence
1531 -- their Names may appear in type signatures in the binding
1533 , sig_inst_wcx
:: Maybe TcType
1534 -- Extra-constraints wildcard to fill in, if any
1535 -- If this exists, it is surely of the form (meta_tv |> co)
1536 -- (where the co might be reflexive). This is filled in
1537 -- only from the return value of TcHsType.tcAnonWildCardOcc
1540 {- Note [sig_inst_tau may be polymorphic]
1541 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1542 Note that "sig_inst_tau" might actually be a polymorphic type,
1543 if the original function had a signature like
1544 forall a. Eq a => forall b. Ord b => ....
1545 But that's ok: tcMatchesFun (called by tcRhs) can deal with that
1546 It happens, too! See Note [Polymorphic methods] in TcClassDcl.
1548 Note [Quantified varaibles in partial type signatures]
1549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1551 f :: forall a b. _ -> a -> _ -> b
1554 Then we expect f's final type to be
1555 f :: forall {x,y}. forall a b. (x,y) -> a -> b -> b
1557 Note that x,y are Inferred, and can't be use for visible type
1558 application (VTA). But a,b are Specified, and remain Specified
1559 in the final type, so we can use VTA for them. (Exception: if
1560 it turns out that a's kind mentions b we need to reorder them
1563 The sig_inst_skols of the TISI from a partial signature records
1564 that original order, and is used to get the variables of f's
1565 final type in the correct order.
1568 Note [Wildcards in partial signatures]
1569 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1570 The wildcards in psig_wcs may stand for a type mentioning
1571 the universally-quantified tyvars of psig_ty
1573 E.g. f :: forall a. _ -> a
1575 We get sig_inst_skols = [a]
1576 sig_inst_tau = _22 -> a
1577 sig_inst_wcs = [_22]
1578 and _22 in the end is unified with the type 'a'
1580 Moreover the kind of a wildcard in sig_inst_wcs may mention
1581 the universally-quantified tyvars sig_inst_skols
1582 e.g. f :: t a -> t _
1584 sig_inst_skols = [k:*, (t::k ->*), (a::k)]
1585 sig_inst_tau = t a -> t _22
1586 sig_inst_wcs = [ _22::k ]
1591 patsig_name
:: Name
,
1592 patsig_implicit_bndrs
:: [TyVarBinder
], -- Implicitly-bound kind vars (Inferred) and
1593 -- implicitly-bound type vars (Specified)
1594 -- See Note [The pattern-synonym signature splitting rule] in TcPatSyn
1595 patsig_univ_bndrs
:: [TyVar
], -- Bound by explicit user forall
1596 patsig_req
:: TcThetaType
,
1597 patsig_ex_bndrs
:: [TyVar
], -- Bound by explicit user forall
1598 patsig_prov
:: TcThetaType
,
1599 patsig_body_ty
:: TcSigmaType
1602 instance Outputable TcSigInfo
where
1603 ppr
(TcIdSig idsi
) = ppr idsi
1604 ppr
(TcPatSynSig tpsi
) = text
"TcPatSynInfo" <+> ppr tpsi
1606 instance Outputable TcIdSigInfo
where
1607 ppr
(CompleteSig
{ sig_bndr
= bndr
})
1608 = ppr bndr
<+> dcolon
<+> ppr
(idType bndr
)
1609 ppr
(PartialSig
{ psig_name
= name
, psig_hs_ty
= hs_ty
})
1610 = text
"psig" <+> ppr name
<+> dcolon
<+> ppr hs_ty
1612 instance Outputable TcIdSigInst
where
1613 ppr
(TISI
{ sig_inst_sig
= sig
, sig_inst_skols
= skols
1614 , sig_inst_theta
= theta
, sig_inst_tau
= tau
})
1615 = hang
(ppr sig
) 2 (vcat
[ ppr skols
, ppr theta
<+> darrow
<+> ppr tau
])
1617 instance Outputable TcPatSynInfo
where
1618 ppr
(TPSI
{ patsig_name
= name
}) = ppr name
1620 isPartialSig
:: TcIdSigInst
-> Bool
1621 isPartialSig
(TISI
{ sig_inst_sig
= PartialSig
{} }) = True
1622 isPartialSig _
= False
1624 -- | No signature or a partial signature
1625 hasCompleteSig
:: TcSigFun
-> Name
-> Bool
1626 hasCompleteSig sig_fn name
1627 = case sig_fn name
of
1628 Just
(TcIdSig
(CompleteSig
{})) -> True
1633 Constraint Solver Plugins
1634 -------------------------
1637 type TcPluginSolver
= [Ct
] -- given
1640 -> TcPluginM TcPluginResult
1642 newtype TcPluginM a
= TcPluginM
(EvBindsVar
-> TcM a
) deriving (Functor
)
1644 instance Applicative TcPluginM
where
1645 pure x
= TcPluginM
(const $ pure x
)
1648 instance Monad TcPluginM
where
1649 #if !MIN_VERSION_base
(4,13,0)
1650 fail = MonadFail
.fail
1653 TcPluginM
(\ ev
-> do a
<- m ev
1654 runTcPluginM
(k a
) ev
)
1656 instance MonadFail
.MonadFail TcPluginM
where
1657 fail x
= TcPluginM
(const $ fail x
)
1659 runTcPluginM
:: TcPluginM a
-> EvBindsVar
-> TcM a
1660 runTcPluginM
(TcPluginM m
) = m
1662 -- | This function provides an escape for direct access to
1663 -- the 'TcM` monad. It should not be used lightly, and
1664 -- the provided 'TcPluginM' API should be favoured instead.
1665 unsafeTcPluginTcM
:: TcM a
-> TcPluginM a
1666 unsafeTcPluginTcM
= TcPluginM
. const
1668 -- | Access the 'EvBindsVar' carried by the 'TcPluginM' during
1669 -- constraint solving. Returns 'Nothing' if invoked during
1670 -- 'tcPluginInit' or 'tcPluginStop'.
1671 getEvBindsTcPluginM
:: TcPluginM EvBindsVar
1672 getEvBindsTcPluginM
= TcPluginM
return
1675 data TcPlugin
= forall s
. TcPlugin
1676 { tcPluginInit
:: TcPluginM s
1677 -- ^ Initialize plugin, when entering type-checker.
1679 , tcPluginSolve
:: s
-> TcPluginSolver
1680 -- ^ Solve some constraints.
1681 -- TODO: WRITE MORE DETAILS ON HOW THIS WORKS.
1683 , tcPluginStop
:: s
-> TcPluginM
()
1684 -- ^ Clean up after the plugin, when exiting the type-checker.
1688 = TcPluginContradiction
[Ct
]
1689 -- ^ The plugin found a contradiction.
1690 -- The returned constraints are removed from the inert set,
1691 -- and recorded as insoluble.
1693 | TcPluginOk
[(EvTerm
,Ct
)] [Ct
]
1694 -- ^ The first field is for constraints that were solved.
1695 -- These are removed from the inert set,
1696 -- and the evidence for them is recorded.
1697 -- The second field contains new work, that should be processed by
1698 -- the constraint solver.
1700 {- *********************************************************************
1704 ********************************************************************* -}
1706 type RoleAnnotEnv
= NameEnv
(LRoleAnnotDecl GhcRn
)
1708 mkRoleAnnotEnv
:: [LRoleAnnotDecl GhcRn
] -> RoleAnnotEnv
1709 mkRoleAnnotEnv role_annot_decls
1710 = mkNameEnv
[ (name
, ra_decl
)
1711 | ra_decl
<- role_annot_decls
1712 , let name
= roleAnnotDeclName
(unLoc ra_decl
)
1713 , not (isUnboundName name
) ]
1714 -- Some of the role annots will be unbound;
1715 -- we don't wish to include these
1717 emptyRoleAnnotEnv
:: RoleAnnotEnv
1718 emptyRoleAnnotEnv
= emptyNameEnv
1720 lookupRoleAnnot
:: RoleAnnotEnv
-> Name
-> Maybe (LRoleAnnotDecl GhcRn
)
1721 lookupRoleAnnot
= lookupNameEnv
1723 getRoleAnnots
:: [Name
] -> RoleAnnotEnv
-> [LRoleAnnotDecl GhcRn
]
1724 getRoleAnnots bndrs role_env
1725 = mapMaybe (lookupRoleAnnot role_env
) bndrs