Expand description
Defines how the compiler represents types internally.
Two important entities in this module are:
rustc_middle::ty::Ty
, used to represent the semantics of a type.rustc_middle::ty::TyCtxt
, the central data structure in the compiler.
For more information, see “The ty
module: representing types” in the rustc-dev-guide.
Re-exports§
pub use self::pattern::Pattern;
pub use self::pattern::PatternKind;
pub use self::trait_def::TraitDef;
pub use vtable::*;
Modules§
- abstract_
const - A subset of a mir body used for const evaluability checking.
- adjustment
- adt 🔒
- assoc 🔒
- cast
- closure 🔒
- codec
- This module contains some shared code for encoding and decoding various
things from the
ty
module, and in particular implements support for “shorthands” which allow to have pointers back into the already encoded stream instead of re-encoding the same thing twice. - consts 🔒
- context 🔒
- Type context book-keeping.
- data_
structures - diagnostics 🔒
- Diagnostics related methods for
Ty
. - elaborate
- elaborate_
impl 🔒 - erase_
regions 🔒 - error
- fast_
reject - flags
- fold
- generic_
args 🔒 - generics 🔒
- impls_
ty 🔒 - This module contains
HashStable
implementations for various data types fromrustc_middle::ty
in no particular order. - inhabitedness
- This module contains logic for determining whether a type is inhabited or
uninhabited. The
InhabitedPredicate
type captures the minimum information needed to determine whether a type is inhabited given aParamEnv
and module ID. - inherent
- Set of traits which are used to emulate the inherent impls that are present in
rustc_middle
. It is customary to glob-importrustc_type_ir::inherent::*
to bring all of these traits into scope when programming in interner-agnostic settings, and to avoid importing any of these directly elsewhere (i.e. specify the full path for an implementation downstream). - instance 🔒
- intrinsic 🔒
- ir_
print - lang_
items - layout
- lift
- list 🔒
- normalize_
erasing_ regions - Methods for normalizing when you don’t care about regions (and
aren’t doing type inference). If either of those things don’t
apply to you, use
infcx.normalize(...)
. - opaque_
types 🔒 - outlives
- The outlives relation
T: 'a
or'a: 'b
. This code frequently refers to rules defined in RFC 1214 (OutlivesFooBar
), so see that RFC for reference. - parameterized 🔒
- pattern
- predicate 🔒
- region 🔒
- relate
- return_
position_ 🔒impl_ trait_ in_ trait - rvalue_
scopes 🔒 - search_
graph - size_
asserts 🔒 - solve
- structural_
impls 🔒 - This module contains implementations of the
Lift
,TypeFoldable
andTypeVisitable
traits for various types in the Rust compiler. Most are written by hand, though we’ve recently added some macros and proc-macros to help with the tedium. - sty 🔒
- This module contains
TyKind
and its major components. - tls
- trait_
def - typeck_
results 🔒 - util
- Miscellaneous type-system utilities that are too small to deserve their own modules.
- visit
- vtable
- walk
- An iterator over the type substructure. WARNING: this does not keep track of the region depth.
Macros§
Structs§
- AdtDef
- AdtDef
Data - The definition of a user-defined type, e.g., a
struct
,enum
, orunion
. - AdtFlags
- Assoc
Item - Information about an associated item
- Assoc
Items - A list of
ty::AssocItem
s in definition order that allows for efficient lookup by name. - Async
Destructor - Bound
Const - Bound
Region - BoundTy
- Bound
Var - CReader
Cache Key - Canonical
- A “canonicalized” type
V
is one where all free inference variables have been rewritten to “canonical vars”. These are numbered starting from 0 in order of first appearance. - Canonical
Query Input - Canonical
User Type Annotation - Canonical
VarInfo - Information about a canonical variable that is included with the canonical value. This is sufficient information for code to create a copy of the canonical value in some other inference context, with fresh inference variables replacing the canonical values.
- Canonical
VarValues - A set of values corresponding to the canonical variables from some
Canonical
. You can give these values tocanonical_value.instantiate
to instantiate them into the canonical value at the right places. - Capture
Info - Part of
MinCaptureInformationMap
; describes the capture kind (&, &mut, move) for a particular capture as well as identifying the part of the source code that triggered this capture to occur. - Captured
Place - A composite describing a
Place
that is captured by a closure. - Clause
- A subset of predicates which can be assumed by the trait solver. They show up in
an item’s where clauses, hence the name
Clause
, and may either be user-written (such as traits) or may be inserted during lowering. - Closure
Args - A closure can be modeled as a struct that looks like:
- Closure
Args Parts - Struct returned by
split()
. - Closure
Size Profile Data - Closure
Type Info - Const
- Const
Conditions ~const
bounds for a given item. This is represented using a struct much likeGenericPredicates
, where you can either choose to only instantiate the “own” bounds or all of the bounds including those from the parent. This distinction is necessary for code likecompare_method_predicate_entailment
.- Const
Int - A type for representing any integer. Only used for printing.
- Const
Vid - A
const
variable ID. - Coroutine
Args - Similar to
ClosureArgs
; see the above documentation for more. - Coroutine
Args Parts - Coroutine
Closure Args - Coroutine
Closure Args Parts - See docs for explanation of how each argument is used.
- Coroutine
Closure Signature - Crate
Inherent Impls - A map for the local crate mapping each type to a vector of its
inherent impls. This is not meant to be used outside of coherence;
rather, you should request the vector for a specific type via
tcx.inherent_impls(def_id)
so as to minimize your dependencies (constructing this map requires touching the entire crate). - Crate
Predicates Map - The crate outlives map is computed during typeck and contains the
outlives of every item in the local crate. You should not use it
directly, because to do so will make your pass dependent on the
HIR of every item in the local crate. Instead, use
tcx.inferred_outlives_of()
to get the outlives for a particular item. - Crate
Variances Map - The crate variances map is computed during typeck and contains the
variance of every item in the local crate. You should not use it
directly, because to do so will make your pass dependent on the
HIR of every item in the local crate. Instead, use
tcx.variances_of()
to get the variance for a particular item. - Ctxt
Interners - Current
Gcx - This is used to get a reference to a
GlobalCtxt
if one is available. - Debruijn
Index - A De Bruijn index is a standard means of representing regions (and perhaps later types) in a higher-ranked setting. In particular, imagine a type like this:
- Deduced
Param Attrs - Parameter attributes that can only be determined by examining the body of a function instead of just its signature.
- Delegation
FnSig - Destructor
- Destructured
Const - The constituent parts of a type level constant of kind ADT or array.
- Early
Binder Iter - Early
Param Region - Expr
- Feed
- The same as
TyCtxtFeed
, but does not contain aTyCtxt
. Use this to pass around when you have aTyCtxt
elsewhere. Just an optimization to save space and not store hundreds ofTyCtxtFeed
in the resolver. - Field
Def - Float
Vid - A floating-point (
f32
orf64
) type variable ID. - FnHeader
- FnSig
Tys - Free
Region Info - This struct contains information regarding a free parameter region,
either a
ReEarlyParam
orReLateParam
. - GenSig
- Generic
Arg - An entity in the Rust type system, which can be one of
several kinds (types, lifetimes, and consts).
To reduce memory usage, a
GenericArg
is an interned pointer, with the lowest 2 bits being reserved for a tag to indicate the type (Ty
,Region
, orConst
) it points to. - Generic
Param Count - Generic
Param Def - Generic
Predicates - Bounds on generics.
- Generics
- Information about the formal type/lifetime parameters associated
with an item or method. Analogous to
hir::Generics
. - Global
Ctxt - See TyCtxt for details about this type.
- Impl
Header - The “header” of an impl is everything outside the body: a Self type, a trait ref (in the case of a trait impl), and a set of predicates (from the bounds / where-clauses).
- Impl
Trait Header - Infer
VarInfo - Inline
Const Args - An inline const is modeled like
- Inline
Const Args Parts - Struct returned by
split()
. - Instance
- An
InstanceKind
along with the args that are needed to substitute the instance. - Instantiated
Predicates - Represents the bounds declared on a particular set of type
parameters. Should eventually be generalized into a flag list of
where-clauses. You can obtain an
InstantiatedPredicates
list from aGenericPredicates
by using theinstantiate
method. Note that this method reflects an important semantic invariant ofInstantiatedPredicates
: while theGenericPredicates
are expressed in terms of the bound type parameters of the impl/trait/whatever, anInstantiatedPredicates
instance represented a set of bounds for some particular instantiation, meaning that the generic parameters have been instantiated with their values. - IntVid
- An integral (
u32
,i32
,usize
, etc.) type variable ID. - Intrinsic
Def - IsSuggestable
Visitor - Iter
Identity Copied - Iter
Instantiated - Iter
Instantiated Copied - Late
Param Region - The parameter representation of late-bound function parameters, “some region
at least as big as the scope
fr.scope
”. - Main
Definition - Make
Suggestable Folder - Opaque
Hidden Type - Param
Const - Param
Env - When interacting with the type system we must provide information about the
environment.
ParamEnv
is the type that represents this information. See the dev guide chapter for more information. - Param
EnvAnd - ParamTy
- Placeholder
- The “placeholder index” fully defines a placeholder region, type, or const. Placeholders are identified by both a universe, as well as a name residing within that universe. Distinct bound regions/types/consts within the same universe simply have an unknown relationship to one another.
- Predicate
- A statement that can be proven by a trait solver. This includes things that may
show up in where clauses, such as trait predicates and projection predicates,
and also things that are emitted as part of type checking such as
DynCompatible
predicate which is emitted when a type is coerced to a trait object. - Pseudo
Canonical Input - Similar to
CanonicalInput
, this carries thetyping_mode
and the environment necessary to do any kind of trait solving inside of nested queries. - Region
- Use this rather than
RegionKind
, whenever possible. - Region
Vid - A region variable ID.
- Resolver
AstLowering - Resolutions that should only be used for lowering. This struct is meant to be consumed by lowering.
- Resolver
Global Ctxt - Resolver
Outputs - Rust2024
Incompatible PatInfo - Information on a pattern incompatible with Rust 2024, for use by the error/migration diagnostic emitted during THIR construction.
- Rvalue
Scopes RvalueScopes
is a mapping from sub-expressions to extended lifetime as determined by rules laid out inrustc_hir_analysis::check::rvalue_scopes
.- Scalar
Int - The raw bytes of a simple value.
- Short
Instance - Static
Lifetime Visitor - Collect al types that have an implicit
'static
obligation that we could suggest'_
for. - Symbol
Name - Term
- Trait
Object Visitor - Collect al types that have an implicit
'static
obligation that we could suggest'_
for. - Ty
- Use this rather than
TyKind
, whenever possible. - TyCtxt
- The central data structure of the compiler. It stores references to the various arenas and also houses the results of the various compiler queries that have been performed. See the rustc dev guide for more details.
- TyCtxt
Feed - This struct should only be created by
create_def
. - TyVid
- A type variable ID.
- Type
Flags - Flags that we track on types. These flags are propagated upwards through the type during type construction, so that we can quickly check whether the type has various kinds of types in it without recursing over the type itself.
- Typeck
Results - Typing
Env - The environment in which to do trait solving.
- Universe
Index - “Universes” are used during type- and trait-checking in the
presence of
for<..>
binders to control what sets of names are visible. Universes are arranged into a tree: the root universe contains names that are always visible. Each child then adds a new set of names that are visible, in addition to those of its parent. We say that the child universe “extends” the parent universe with new names. - Unsafe
Binder Inner - Unused
Generic Params - UpvarId
- Upvars do not get their own
NodeId
. Instead, we use the pair of the original var ID (that is, the root variable that is referenced by the upvar) and the ID of the closure expression. - Upvar
Path - User
Args - Stores the user-given args to reach some fully qualified path
(e.g.,
<T>::Item
or<T as Trait>::Item
). - User
Self Ty - Specifies the user-given self type. In the case of a path that refers to a member in an inherent impl, this self type is sometimes needed to constrain the type parameters on the impl. For example, in this code:
- User
Type - User
Type Annotation Index - ValTree
- An interned valtree. Use this rather than
ValTreeKind
, whenever possible. - Validate
Bound Vars - Value
- A type-level constant value.
- Variant
Def - Definition of a variant – a struct’s fields or an enum variant.
- Variant
Flags - With
Cached Type Info - A helper type that you can wrap round your own type in order to automatically cache the stable hash, type flags and debruijn index on creation and not recompute it whenever the information is needed. This is only done in incremental mode. You can also opt out of caching by using StableHash::ZERO for the hash, in which case the hash gets computed each time. This is useful if you have values that you intern but never (can?) use for stable hashing.
Enums§
- AdtKind
- Alias
Relation Direction - Alias
Term Kind - Alias
TyKind - Assoc
Item Container - Assoc
Kind - Asyncness
- Borrow
Kind - Bound
Constness - Bound
Region Kind - Bound
TyKind - Bound
Variable Kind - Canonical
TyVar Kind - Rust actually has more than one category of type variables; notably, the type variables we create for literals (e.g., 22 or 22.) can only be instantiated with integral/float types (e.g., usize or f32). In order to faithfully reproduce a type, we need to know what set of types a given type variable can be unified with.
- Canonical
VarKind - Describes the “kind” of the canonical variable. This is a “kind” in the type-theory sense of the term – i.e., a “meta” type system that analyzes type-like values.
- Closure
Kind - Represents the various closure traits in the language. This
will determine the type of the environment (
self
, in the desugaring) argument that the closure expects. - DynKind
- Specifies how a trait object is represented.
- Expr
Kind - FloatTy
- Float
VarValue - Generic
Param DefKind - Impl
Overlap Kind - Impl
Polarity - Impl
Subject - Impl
Trait InTrait Data - Useful source information about where a desugared associated type for an RPITIT originated from.
- Infer
Const - An inference variable for a const, for use in const generics.
- InferTy
- A placeholder for a type that hasn’t been inferred yet.
- Instance
Kind - IntTy
- IntVar
Value - Late
Param Region Kind - When liberating bound regions, we map their
BoundRegionKind
to this as we need to track the index of anonymous regions. We otherwise end up liberating multiple bound regions to the same late-bound region. - Movability
- The movability of a coroutine / closure literal:
whether a coroutine contains self-references, causing it to be
!Unpin
. - Mutability
- Param
Term - Predicate
Polarity - Polarity for a trait predicate. May either be negative or positive.
Distinguished from
ImplPolarity
since we never compute goals with “reservation” level. - Reify
Reason - Describes why a
ReifyShim
was created. This is needed to distinguish a ReifyShim created to adjust for things like#[track_caller]
in a vtable from aReifyShim
created to produce a function pointer from a vtable entry. Currently, this is only used when KCFI is enabled, as only KCFI needs to treat those twoReifyShim
s differently. - Representability
- TermVid
- UintTy
- Upvar
Args - Upvar
Capture - Information describing the capture of an upvar. This is computed
during
typeck
, specifically byregionck
. - User
Type Kind - A user-given type annotation attached to a constant. These arise
from constants that are named via paths, like
Foo::<A>::new
and so forth. - ValTree
Kind - This datastructure is used to represent the value of constants used in the type system.
- Variance
- Variance
Diag Info - Extra information about why we ended up with a particular variance.
This is only used to add more information to error messages, and
has no effect on soundness. While choosing the ‘wrong’
VarianceDiagInfo
may lead to confusing notes in error messages, it will never cause a miscompilation or unsoundness. - Variant
Discr - Visibility
Constants§
- CAPTURE_
STRUCT_ LOCAL - Captures are represented using fields inside a structure. This represents accessing self in the closure structure
- CONST_
TAG 🔒 - INNERMOST
- SHORTHAND_
OFFSET - The shorthand encoding uses an enum’s variant index
usize
and is offset by this value so it never matches a real variant. This offset is also chosen so that the first byte is never < 0x80. - TAG_
MASK 🔒 - TYPE_
TAG 🔒
Traits§
- Article
- Collect
AndApply - Imagine you have a function
F: FnOnce(&[T]) -> R
, plus an iteratoriter
that producesT
items. You could combine them withf(&iter.collect::<Vec<_>>())
, but this requires allocating memory for theVec
. - Coroutine
Args Ext - Existential
Predicate Stable CmpExt - Fallible
Type Folder - This trait is implemented for every folding traversal. There is a fold method defined for every type of interest. Each such method has a default that does an “identity” fold.
- Infer
Ctxt Like - Interner
- IsIdentity
- IsSuggestable
- Lift
- A trait implemented for all
X<'a>
types that can be safely and efficiently converted toX<'tcx>
as long as they are part of the providedTyCtxt<'tcx>
. This can be done, for example, forTy<'tcx>
orGenericArgsRef<'tcx>
by looking them up in their respective interners. - Parameterized
Over Tcx - RefDecodable
- Trait for decoding to a reference.
- Term
Kind Pack Ext - TyDecoder
- TyEncoder
- Type
Foldable - This trait is implemented for every type that can be folded, providing the skeleton of the traversal.
- Type
Folder - This trait is implemented for every infallible folding traversal. There is
a fold method defined for every type of interest. Each such method has a
default that does an “identity” fold. Implementations of these methods
often fall back to a
super_fold_with
method if the primary argument doesn’t satisfy a particular condition. - Type
Super Foldable - Type
Super Visitable - Type
Visitable - This trait is implemented for every type that can be visited, providing the skeleton of the traversal.
- Type
Visitable Ext - Type
Visitor - This trait is implemented for every visiting traversal. There is a visit method defined for every type of interest. Each such method has a default that recurses into the type’s fields in a non-custom fashion.
- Upcast
- An
Into
-like trait that takesTyCtxt
to perform interner-specific transformations. - Upcast
From - A
From
-like trait that takesTyCtxt
to perform interner-specific transformations.
Functions§
- analyze_
coroutine_ closure_ captures - ast_
int_ ty - ast_
uint_ ty - debug_
bound_ var - float_
ty - int_ty
- is_
ancestor_ or_ same_ capture - Return true if the
proj_possible_ancestor
represents an ancestor path toproj_capture
orproj_possible_ancestor
is same asproj_capture
, assuming they both start off of the same root variable. - place_
to_ string_ for_ capture - provide
- suggest_
arbitrary_ trait_ bound - suggest_
constraining_ type_ param - Suggest restricting a type param with a new bound.
- suggest_
constraining_ type_ params - Suggest restricting a type param with a new bound.
- uint_ty
Type Aliases§
- Alias
Term - AliasTy
- Binder
- Canonical
Poly FnSig - Canonical
User Type - Canonical user type annotation.
- Canonical
User Type Annotations - Mapping of type annotation indices to canonical user type annotations.
- Clause
Kind - Clauses
- Coerce
Predicate - Const
Kind - Early
Binder - Existential
Predicate - Existential
Projection - Existential
Trait Ref - FnSig
- Generic
ArgKind - Generic
Args - List of generic arguments that are gonna be used to replace generic parameters.
- Generic
Args Ref - Host
Effect Predicate - List
List<T>
is a bit like&[T]
, but with some critical differences.- List
With Cached Type Info - A
List
that additionally stores type information inline to speed upTypeVisitableExt
operations. - MinCapture
Information Map - Given the closure DefId this map provides a map of root variables to minimum
set of
CapturedPlace
s that need to be tracked to support all captures of that closure. - MinCapture
List - Part of
MinCaptureInformationMap
; List ofCapturePlace
s. - Normalizes
To - Opaque
Type Key - Outlives
Predicate - Placeholder
Const - Placeholder
Region - Placeholder
Type - Poly
Coerce Predicate - Poly
Existential Predicate - Poly
Existential Projection - Poly
Existential Trait Ref - Poly
FnSig - Poly
Projection Predicate - Poly
Region Outlives Predicate - Poly
Subtype Predicate - Poly
Trait Predicate - Poly
Trait Ref - Poly
Type Outlives Predicate - Predicate
Kind - Projection
Predicate - Region
Kind - Region
Outlives Predicate - Registered
Tools - Root
Variable MinCapture List - Part of
MinCaptureInformationMap
; Maps a root variable to the list ofCapturedPlace
. Used to track the minimum set ofPlace
s that need to be captured to support all Places captured by the closure starting at a given root variable. - Subtype
Predicate - Term
Kind - Trait
Predicate - Trait
Ref - TyKind
- Type
AndMut - Type
Outlives Predicate - Typing
Mode - Unevaluated
Const