1 //! This module contains `TyKind` and its major components.
3 #![allow(rustc::usage_of_ty_tykind)]
8 use crate::infer::canonical::Canonical;
9 use crate::middle::region;
10 use crate::mir::interpret::ConstValue;
11 use crate::mir::interpret::Scalar;
12 use crate::mir::Promoted;
13 use crate::ty::layout::VariantIdx;
14 use crate::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst, SubstsRef};
16 self, AdtDef, DefIdTree, Discr, Ty, TyCtxt, TypeFlags, TypeFoldable, WithConstness,
18 use crate::ty::{List, ParamEnv, ParamEnvAnd, TyS};
19 use polonius_engine::Atom;
20 use rustc_data_structures::captures::Captures;
22 use rustc_hir::def_id::DefId;
23 use rustc_index::vec::Idx;
24 use rustc_macros::HashStable;
25 use rustc_span::symbol::{kw, Symbol};
26 use rustc_target::spec::abi;
27 use smallvec::SmallVec;
29 use std::cmp::Ordering;
30 use std::marker::PhantomData;
32 use syntax::ast::{self, Ident};
49 pub struct TypeAndMut<'tcx> {
51 pub mutbl: hir::Mutability,
66 /// A "free" region `fr` can be interpreted as "some region
67 /// at least as big as the scope `fr.scope`".
68 pub struct FreeRegion {
70 pub bound_region: BoundRegion,
85 pub enum BoundRegion {
86 /// An anonymous region parameter for a given fn (&T)
89 /// Named region parameters for functions (a in &'a T)
91 /// The `DefId` is needed to distinguish free regions in
92 /// the event of shadowing.
93 BrNamed(DefId, Symbol),
95 /// Anonymous region for the implicit env pointer parameter
101 pub fn is_named(&self) -> bool {
103 BoundRegion::BrNamed(_, name) => name != kw::UnderscoreLifetime,
108 /// When canonicalizing, we replace unbound inference variables and free
109 /// regions with anonymous late bound regions. This method asserts that
110 /// we have an anonymous late bound region, which hence may refer to
111 /// a canonical variable.
112 pub fn assert_bound_var(&self) -> BoundVar {
114 BoundRegion::BrAnon(var) => BoundVar::from_u32(var),
115 _ => bug!("bound region is not anonymous"),
120 /// N.B., if you change this, you'll probably want to change the corresponding
121 /// AST structure in `libsyntax/ast.rs` as well.
134 #[rustc_diagnostic_item = "TyKind"]
135 pub enum TyKind<'tcx> {
136 /// The primitive boolean type. Written as `bool`.
139 /// The primitive character type; holds a Unicode scalar value
140 /// (a non-surrogate code point). Written as `char`.
143 /// A primitive signed integer type. For example, `i32`.
146 /// A primitive unsigned integer type. For example, `u32`.
149 /// A primitive floating-point type. For example, `f64`.
152 /// Structures, enumerations and unions.
154 /// InternalSubsts here, possibly against intuition, *may* contain `Param`s.
155 /// That is, even after substitution it is possible that there are type
156 /// variables. This happens when the `Adt` corresponds to an ADT
157 /// definition and not a concrete use of it.
158 Adt(&'tcx AdtDef, SubstsRef<'tcx>),
160 /// An unsized FFI type that is opaque to Rust. Written as `extern type T`.
163 /// The pointee of a string slice. Written as `str`.
166 /// An array with the given length. Written as `[T; n]`.
167 Array(Ty<'tcx>, &'tcx ty::Const<'tcx>),
169 /// The pointee of an array slice. Written as `[T]`.
172 /// A raw pointer. Written as `*mut T` or `*const T`
173 RawPtr(TypeAndMut<'tcx>),
175 /// A reference; a pointer with an associated lifetime. Written as
176 /// `&'a mut T` or `&'a T`.
177 Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability),
179 /// The anonymous type of a function declaration/definition. Each
180 /// function has a unique type, which is output (for a function
181 /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
183 /// For example the type of `bar` here:
186 /// fn foo() -> i32 { 1 }
187 /// let bar = foo; // bar: fn() -> i32 {foo}
189 FnDef(DefId, SubstsRef<'tcx>),
191 /// A pointer to a function. Written as `fn() -> i32`.
193 /// For example the type of `bar` here:
196 /// fn foo() -> i32 { 1 }
197 /// let bar: fn() -> i32 = foo;
199 FnPtr(PolyFnSig<'tcx>),
201 /// A trait, defined with `trait`.
202 Dynamic(Binder<&'tcx List<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
204 /// The anonymous type of a closure. Used to represent the type of
206 Closure(DefId, SubstsRef<'tcx>),
208 /// The anonymous type of a generator. Used to represent the type of
210 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
212 /// A type representin the types stored inside a generator.
213 /// This should only appear in GeneratorInteriors.
214 GeneratorWitness(Binder<&'tcx List<Ty<'tcx>>>),
216 /// The never type `!`
219 /// A tuple type. For example, `(i32, bool)`.
220 /// Use `TyS::tuple_fields` to iterate over the field types.
221 Tuple(SubstsRef<'tcx>),
223 /// The projection of an associated type. For example,
224 /// `<T as Trait<..>>::N`.
225 Projection(ProjectionTy<'tcx>),
227 /// A placeholder type used when we do not have enough information
228 /// to normalize the projection of an associated type to an
229 /// existing concrete type. Currently only used with chalk-engine.
230 UnnormalizedProjection(ProjectionTy<'tcx>),
232 /// Opaque (`impl Trait`) type found in a return type.
233 /// The `DefId` comes either from
234 /// * the `impl Trait` ast::Ty node,
235 /// * or the `type Foo = impl Trait` declaration
236 /// The substitutions are for the generics of the function in question.
237 /// After typeck, the concrete type can be found in the `types` map.
238 Opaque(DefId, SubstsRef<'tcx>),
240 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
243 /// Bound type variable, used only when preparing a trait query.
244 Bound(ty::DebruijnIndex, BoundTy),
246 /// A placeholder type - universally quantified higher-ranked type.
247 Placeholder(ty::PlaceholderType),
249 /// A type variable used during type checking.
252 /// A placeholder for a type which could not be computed; this is
253 /// propagated to avoid useless error messages.
257 // `TyKind` is used a lot. Make sure it doesn't unintentionally get bigger.
258 #[cfg(target_arch = "x86_64")]
259 static_assert_size!(TyKind<'_>, 24);
261 /// A closure can be modeled as a struct that looks like:
263 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
271 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
272 /// in scope on the function that defined the closure,
273 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
274 /// is rather hackily encoded via a scalar type. See
275 /// `TyS::to_opt_closure_kind` for details.
276 /// - CS represents the *closure signature*, representing as a `fn()`
277 /// type. For example, `fn(u32, u32) -> u32` would mean that the closure
278 /// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
280 /// - U0...Uk are type parameters representing the types of its upvars
281 /// (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
282 /// and the up-var has the type `Foo`, then `Ui = &Foo`).
284 /// So, for example, given this function:
286 /// fn foo<'a, T>(data: &'a mut T) {
287 /// do(|| data.count += 1)
290 /// the type of the closure would be something like:
292 /// struct Closure<'a, T, U0> {
296 /// Note that the type of the upvar is not specified in the struct.
297 /// You may wonder how the impl would then be able to use the upvar,
298 /// if it doesn't know it's type? The answer is that the impl is
299 /// (conceptually) not fully generic over Closure but rather tied to
300 /// instances with the expected upvar types:
302 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
306 /// You can see that the *impl* fully specified the type of the upvar
307 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
308 /// (Here, I am assuming that `data` is mut-borrowed.)
310 /// Now, the last question you may ask is: Why include the upvar types
311 /// as extra type parameters? The reason for this design is that the
312 /// upvar types can reference lifetimes that are internal to the
313 /// creating function. In my example above, for example, the lifetime
314 /// `'b` represents the scope of the closure itself; this is some
315 /// subset of `foo`, probably just the scope of the call to the to
316 /// `do()`. If we just had the lifetime/type parameters from the
317 /// enclosing function, we couldn't name this lifetime `'b`. Note that
318 /// there can also be lifetimes in the types of the upvars themselves,
319 /// if one of them happens to be a reference to something that the
320 /// creating fn owns.
322 /// OK, you say, so why not create a more minimal set of parameters
323 /// that just includes the extra lifetime parameters? The answer is
324 /// primarily that it would be hard --- we don't know at the time when
325 /// we create the closure type what the full types of the upvars are,
326 /// nor do we know which are borrowed and which are not. In this
327 /// design, we can just supply a fresh type parameter and figure that
330 /// All right, you say, but why include the type parameters from the
331 /// original function then? The answer is that codegen may need them
332 /// when monomorphizing, and they may not appear in the upvars. A
333 /// closure could capture no variables but still make use of some
334 /// in-scope type parameter with a bound (e.g., if our example above
335 /// had an extra `U: Default`, and the closure called `U::default()`).
337 /// There is another reason. This design (implicitly) prohibits
338 /// closures from capturing themselves (except via a trait
339 /// object). This simplifies closure inference considerably, since it
340 /// means that when we infer the kind of a closure or its upvars, we
341 /// don't have to handle cycles where the decisions we make for
342 /// closure C wind up influencing the decisions we ought to make for
343 /// closure C (which would then require fixed point iteration to
344 /// handle). Plus it fixes an ICE. :P
348 /// Generators are handled similarly in `GeneratorSubsts`. The set of
349 /// type parameters is similar, but `CK` and `CS` are replaced by the
350 /// following type parameters:
352 /// * `GS`: The generator's "resume type", which is the type of the
353 /// argument passed to `resume`, and the type of `yield` expressions
354 /// inside the generator.
355 /// * `GY`: The "yield type", which is the type of values passed to
356 /// `yield` inside the generator.
357 /// * `GR`: The "return type", which is the type of value returned upon
358 /// completion of the generator.
359 /// * `GW`: The "generator witness".
360 #[derive(Copy, Clone, Debug, TypeFoldable)]
361 pub struct ClosureSubsts<'tcx> {
362 /// Lifetime and type parameters from the enclosing function,
363 /// concatenated with the types of the upvars.
365 /// These are separated out because codegen wants to pass them around
366 /// when monomorphizing.
367 pub substs: SubstsRef<'tcx>,
370 /// Struct returned by `split()`. Note that these are subslices of the
371 /// parent slice and not canonical substs themselves.
372 struct SplitClosureSubsts<'tcx> {
373 closure_kind_ty: Ty<'tcx>,
374 closure_sig_ty: Ty<'tcx>,
375 upvar_kinds: &'tcx [GenericArg<'tcx>],
378 impl<'tcx> ClosureSubsts<'tcx> {
379 /// Divides the closure substs into their respective
380 /// components. Single source of truth with respect to the
382 fn split(self, def_id: DefId, tcx: TyCtxt<'_>) -> SplitClosureSubsts<'tcx> {
383 let generics = tcx.generics_of(def_id);
384 let parent_len = generics.parent_count;
386 closure_kind_ty: self.substs.type_at(parent_len),
387 closure_sig_ty: self.substs.type_at(parent_len + 1),
388 upvar_kinds: &self.substs[parent_len + 2..],
397 ) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
398 let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
399 upvar_kinds.iter().map(|t| {
400 if let GenericArgKind::Type(ty) = t.unpack() {
403 bug!("upvar should be type")
408 /// Returns the closure kind for this closure; may return a type
409 /// variable during inference. To get the closure kind during
410 /// inference, use `infcx.closure_kind(def_id, substs)`.
411 pub fn kind_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
412 self.split(def_id, tcx).closure_kind_ty
415 /// Returns the type representing the closure signature for this
416 /// closure; may contain type variables during inference. To get
417 /// the closure signature during inference, use
418 /// `infcx.fn_sig(def_id)`.
419 pub fn sig_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
420 self.split(def_id, tcx).closure_sig_ty
423 /// Returns the closure kind for this closure; only usable outside
424 /// of an inference context, because in that context we know that
425 /// there are no type variables.
427 /// If you have an inference context, use `infcx.closure_kind()`.
428 pub fn kind(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::ClosureKind {
429 self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
432 /// Extracts the signature from the closure; only usable outside
433 /// of an inference context, because in that context we know that
434 /// there are no type variables.
436 /// If you have an inference context, use `infcx.closure_sig()`.
437 pub fn sig(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
438 let ty = self.sig_ty(def_id, tcx);
440 ty::FnPtr(sig) => sig,
441 _ => bug!("closure_sig_ty is not a fn-ptr: {:?}", ty.kind),
446 /// Similar to `ClosureSubsts`; see the above documentation for more.
447 #[derive(Copy, Clone, Debug, TypeFoldable)]
448 pub struct GeneratorSubsts<'tcx> {
449 pub substs: SubstsRef<'tcx>,
452 struct SplitGeneratorSubsts<'tcx> {
457 upvar_kinds: &'tcx [GenericArg<'tcx>],
460 impl<'tcx> GeneratorSubsts<'tcx> {
461 fn split(self, def_id: DefId, tcx: TyCtxt<'_>) -> SplitGeneratorSubsts<'tcx> {
462 let generics = tcx.generics_of(def_id);
463 let parent_len = generics.parent_count;
464 SplitGeneratorSubsts {
465 resume_ty: self.substs.type_at(parent_len),
466 yield_ty: self.substs.type_at(parent_len + 1),
467 return_ty: self.substs.type_at(parent_len + 2),
468 witness: self.substs.type_at(parent_len + 3),
469 upvar_kinds: &self.substs[parent_len + 4..],
473 /// This describes the types that can be contained in a generator.
474 /// It will be a type variable initially and unified in the last stages of typeck of a body.
475 /// It contains a tuple of all the types that could end up on a generator frame.
476 /// The state transformation MIR pass may only produce layouts which mention types
477 /// in this tuple. Upvars are not counted here.
478 pub fn witness(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
479 self.split(def_id, tcx).witness
487 ) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
488 let SplitGeneratorSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
489 upvar_kinds.iter().map(|t| {
490 if let GenericArgKind::Type(ty) = t.unpack() {
493 bug!("upvar should be type")
498 /// Returns the type representing the resume type of the generator.
499 pub fn resume_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
500 self.split(def_id, tcx).resume_ty
503 /// Returns the type representing the yield type of the generator.
504 pub fn yield_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
505 self.split(def_id, tcx).yield_ty
508 /// Returns the type representing the return type of the generator.
509 pub fn return_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
510 self.split(def_id, tcx).return_ty
513 /// Returns the "generator signature", which consists of its yield
514 /// and return types.
516 /// N.B., some bits of the code prefers to see this wrapped in a
517 /// binder, but it never contains bound regions. Probably this
518 /// function should be removed.
519 pub fn poly_sig(self, def_id: DefId, tcx: TyCtxt<'_>) -> PolyGenSig<'tcx> {
520 ty::Binder::dummy(self.sig(def_id, tcx))
523 /// Returns the "generator signature", which consists of its resume, yield
524 /// and return types.
525 pub fn sig(self, def_id: DefId, tcx: TyCtxt<'_>) -> GenSig<'tcx> {
527 resume_ty: self.resume_ty(def_id, tcx),
528 yield_ty: self.yield_ty(def_id, tcx),
529 return_ty: self.return_ty(def_id, tcx),
534 impl<'tcx> GeneratorSubsts<'tcx> {
535 /// Generator has not been resumed yet.
536 pub const UNRESUMED: usize = 0;
537 /// Generator has returned or is completed.
538 pub const RETURNED: usize = 1;
539 /// Generator has been poisoned.
540 pub const POISONED: usize = 2;
542 const UNRESUMED_NAME: &'static str = "Unresumed";
543 const RETURNED_NAME: &'static str = "Returned";
544 const POISONED_NAME: &'static str = "Panicked";
546 /// The valid variant indices of this generator.
548 pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
549 // FIXME requires optimized MIR
550 let num_variants = tcx.generator_layout(def_id).variant_fields.len();
551 VariantIdx::new(0)..VariantIdx::new(num_variants)
554 /// The discriminant for the given variant. Panics if the `variant_index` is
557 pub fn discriminant_for_variant(
561 variant_index: VariantIdx,
563 // Generators don't support explicit discriminant values, so they are
564 // the same as the variant index.
565 assert!(self.variant_range(def_id, tcx).contains(&variant_index));
566 Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
569 /// The set of all discriminants for the generator, enumerated with their
572 pub fn discriminants(
576 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
577 self.variant_range(def_id, tcx).map(move |index| {
578 (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
582 /// Calls `f` with a reference to the name of the enumerator for the given
585 pub fn variant_name(self, v: VariantIdx) -> Cow<'static, str> {
587 Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
588 Self::RETURNED => Cow::from(Self::RETURNED_NAME),
589 Self::POISONED => Cow::from(Self::POISONED_NAME),
590 _ => Cow::from(format!("Suspend{}", v.as_usize() - 3)),
594 /// The type of the state discriminant used in the generator type.
596 pub fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
600 /// This returns the types of the MIR locals which had to be stored across suspension points.
601 /// It is calculated in rustc_mir::transform::generator::StateTransform.
602 /// All the types here must be in the tuple in GeneratorInterior.
604 /// The locals are grouped by their variant number. Note that some locals may
605 /// be repeated in multiple variants.
611 ) -> impl Iterator<Item = impl Iterator<Item = Ty<'tcx>> + Captures<'tcx>> {
612 let layout = tcx.generator_layout(def_id);
613 layout.variant_fields.iter().map(move |variant| {
614 variant.iter().map(move |field| layout.field_tys[*field].subst(tcx, self.substs))
618 /// This is the types of the fields of a generator which are not stored in a
621 pub fn prefix_tys(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> impl Iterator<Item = Ty<'tcx>> {
622 self.upvar_tys(def_id, tcx)
626 #[derive(Debug, Copy, Clone)]
627 pub enum UpvarSubsts<'tcx> {
628 Closure(SubstsRef<'tcx>),
629 Generator(SubstsRef<'tcx>),
632 impl<'tcx> UpvarSubsts<'tcx> {
638 ) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
639 let upvar_kinds = match self {
640 UpvarSubsts::Closure(substs) => substs.as_closure().split(def_id, tcx).upvar_kinds,
641 UpvarSubsts::Generator(substs) => substs.as_generator().split(def_id, tcx).upvar_kinds,
643 upvar_kinds.iter().map(|t| {
644 if let GenericArgKind::Type(ty) = t.unpack() {
647 bug!("upvar should be type")
653 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, RustcEncodable, RustcDecodable)]
654 #[derive(HashStable, TypeFoldable)]
655 pub enum ExistentialPredicate<'tcx> {
656 /// E.g., `Iterator`.
657 Trait(ExistentialTraitRef<'tcx>),
658 /// E.g., `Iterator::Item = T`.
659 Projection(ExistentialProjection<'tcx>),
664 impl<'tcx> ExistentialPredicate<'tcx> {
665 /// Compares via an ordering that will not change if modules are reordered or other changes are
666 /// made to the tree. In particular, this ordering is preserved across incremental compilations.
667 pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering {
668 use self::ExistentialPredicate::*;
669 match (*self, *other) {
670 (Trait(_), Trait(_)) => Ordering::Equal,
671 (Projection(ref a), Projection(ref b)) => {
672 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id))
674 (AutoTrait(ref a), AutoTrait(ref b)) => {
675 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash)
677 (Trait(_), _) => Ordering::Less,
678 (Projection(_), Trait(_)) => Ordering::Greater,
679 (Projection(_), _) => Ordering::Less,
680 (AutoTrait(_), _) => Ordering::Greater,
685 impl<'tcx> Binder<ExistentialPredicate<'tcx>> {
686 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> {
687 use crate::ty::ToPredicate;
688 match *self.skip_binder() {
689 ExistentialPredicate::Trait(tr) => {
690 Binder(tr).with_self_ty(tcx, self_ty).without_const().to_predicate()
692 ExistentialPredicate::Projection(p) => {
693 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty)))
695 ExistentialPredicate::AutoTrait(did) => {
697 Binder(ty::TraitRef { def_id: did, substs: tcx.mk_substs_trait(self_ty, &[]) });
698 trait_ref.without_const().to_predicate()
704 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<ExistentialPredicate<'tcx>> {}
706 impl<'tcx> List<ExistentialPredicate<'tcx>> {
707 /// Returns the "principal `DefId`" of this set of existential predicates.
709 /// A Rust trait object type consists (in addition to a lifetime bound)
710 /// of a set of trait bounds, which are separated into any number
711 /// of auto-trait bounds, and at most one non-auto-trait bound. The
712 /// non-auto-trait bound is called the "principal" of the trait
715 /// Only the principal can have methods or type parameters (because
716 /// auto traits can have neither of them). This is important, because
717 /// it means the auto traits can be treated as an unordered set (methods
718 /// would force an order for the vtable, while relating traits with
719 /// type parameters without knowing the order to relate them in is
720 /// a rather non-trivial task).
722 /// For example, in the trait object `dyn fmt::Debug + Sync`, the
723 /// principal bound is `Some(fmt::Debug)`, while the auto-trait bounds
724 /// are the set `{Sync}`.
726 /// It is also possible to have a "trivial" trait object that
727 /// consists only of auto traits, with no principal - for example,
728 /// `dyn Send + Sync`. In that case, the set of auto-trait bounds
729 /// is `{Send, Sync}`, while there is no principal. These trait objects
730 /// have a "trivial" vtable consisting of just the size, alignment,
732 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
734 ExistentialPredicate::Trait(tr) => Some(tr),
739 pub fn principal_def_id(&self) -> Option<DefId> {
740 self.principal().map(|trait_ref| trait_ref.def_id)
744 pub fn projection_bounds<'a>(
746 ) -> impl Iterator<Item = ExistentialProjection<'tcx>> + 'a {
747 self.iter().filter_map(|predicate| match *predicate {
748 ExistentialPredicate::Projection(projection) => Some(projection),
754 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item = DefId> + 'a {
755 self.iter().filter_map(|predicate| match *predicate {
756 ExistentialPredicate::AutoTrait(did) => Some(did),
762 impl<'tcx> Binder<&'tcx List<ExistentialPredicate<'tcx>>> {
763 pub fn principal(&self) -> Option<ty::Binder<ExistentialTraitRef<'tcx>>> {
764 self.skip_binder().principal().map(Binder::bind)
767 pub fn principal_def_id(&self) -> Option<DefId> {
768 self.skip_binder().principal_def_id()
772 pub fn projection_bounds<'a>(
774 ) -> impl Iterator<Item = PolyExistentialProjection<'tcx>> + 'a {
775 self.skip_binder().projection_bounds().map(Binder::bind)
779 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item = DefId> + 'a {
780 self.skip_binder().auto_traits()
785 ) -> impl DoubleEndedIterator<Item = Binder<ExistentialPredicate<'tcx>>> + 'tcx {
786 self.skip_binder().iter().cloned().map(Binder::bind)
790 /// A complete reference to a trait. These take numerous guises in syntax,
791 /// but perhaps the most recognizable form is in a where-clause:
795 /// This would be represented by a trait-reference where the `DefId` is the
796 /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0,
797 /// and `U` as parameter 1.
799 /// Trait references also appear in object types like `Foo<U>`, but in
800 /// that case the `Self` parameter is absent from the substitutions.
802 /// Note that a `TraitRef` introduces a level of region binding, to
803 /// account for higher-ranked trait bounds like `T: for<'a> Foo<&'a U>`
804 /// or higher-ranked object types.
805 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
806 #[derive(HashStable, TypeFoldable)]
807 pub struct TraitRef<'tcx> {
809 pub substs: SubstsRef<'tcx>,
812 impl<'tcx> TraitRef<'tcx> {
813 pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> {
814 TraitRef { def_id, substs }
817 /// Returns a `TraitRef` of the form `P0: Foo<P1..Pn>` where `Pi`
818 /// are the parameters defined on trait.
819 pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> TraitRef<'tcx> {
820 TraitRef { def_id, substs: InternalSubsts::identity_for_item(tcx, def_id) }
824 pub fn self_ty(&self) -> Ty<'tcx> {
825 self.substs.type_at(0)
828 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
829 // Select only the "input types" from a trait-reference. For
830 // now this is all the types that appear in the
831 // trait-reference, but it should eventually exclude
839 substs: SubstsRef<'tcx>,
840 ) -> ty::TraitRef<'tcx> {
841 let defs = tcx.generics_of(trait_id);
843 ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) }
847 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
849 impl<'tcx> PolyTraitRef<'tcx> {
850 pub fn self_ty(&self) -> Ty<'tcx> {
851 self.skip_binder().self_ty()
854 pub fn def_id(&self) -> DefId {
855 self.skip_binder().def_id
858 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
859 // Note that we preserve binding levels
860 Binder(ty::TraitPredicate { trait_ref: *self.skip_binder() })
864 /// An existential reference to a trait, where `Self` is erased.
865 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
867 /// exists T. T: Trait<'a, 'b, X, Y>
869 /// The substitutions don't include the erased `Self`, only trait
870 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
871 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
872 #[derive(HashStable, TypeFoldable)]
873 pub struct ExistentialTraitRef<'tcx> {
875 pub substs: SubstsRef<'tcx>,
878 impl<'tcx> ExistentialTraitRef<'tcx> {
879 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'b {
880 // Select only the "input types" from a trait-reference. For
881 // now this is all the types that appear in the
882 // trait-reference, but it should eventually exclude
887 pub fn erase_self_ty(
889 trait_ref: ty::TraitRef<'tcx>,
890 ) -> ty::ExistentialTraitRef<'tcx> {
891 // Assert there is a Self.
892 trait_ref.substs.type_at(0);
894 ty::ExistentialTraitRef {
895 def_id: trait_ref.def_id,
896 substs: tcx.intern_substs(&trait_ref.substs[1..]),
900 /// Object types don't have a self type specified. Therefore, when
901 /// we convert the principal trait-ref into a normal trait-ref,
902 /// you must give *some* self type. A common choice is `mk_err()`
903 /// or some placeholder type.
904 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> {
905 // otherwise the escaping vars would be captured by the binder
906 // debug_assert!(!self_ty.has_escaping_bound_vars());
908 ty::TraitRef { def_id: self.def_id, substs: tcx.mk_substs_trait(self_ty, self.substs) }
912 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
914 impl<'tcx> PolyExistentialTraitRef<'tcx> {
915 pub fn def_id(&self) -> DefId {
916 self.skip_binder().def_id
919 /// Object types don't have a self type specified. Therefore, when
920 /// we convert the principal trait-ref into a normal trait-ref,
921 /// you must give *some* self type. A common choice is `mk_err()`
922 /// or some placeholder type.
923 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> {
924 self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
928 /// Binder is a binder for higher-ranked lifetimes or types. It is part of the
929 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
930 /// (which would be represented by the type `PolyTraitRef ==
931 /// Binder<TraitRef>`). Note that when we instantiate,
932 /// erase, or otherwise "discharge" these bound vars, we change the
933 /// type from `Binder<T>` to just `T` (see
934 /// e.g., `liberate_late_bound_regions`).
935 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
936 pub struct Binder<T>(T);
939 /// Wraps `value` in a binder, asserting that `value` does not
940 /// contain any bound vars that would be bound by the
941 /// binder. This is commonly used to 'inject' a value T into a
942 /// different binding level.
943 pub fn dummy<'tcx>(value: T) -> Binder<T>
945 T: TypeFoldable<'tcx>,
947 debug_assert!(!value.has_escaping_bound_vars());
951 /// Wraps `value` in a binder, binding higher-ranked vars (if any).
952 pub fn bind(value: T) -> Binder<T> {
956 /// Skips the binder and returns the "bound" value. This is a
957 /// risky thing to do because it's easy to get confused about
958 /// De Bruijn indices and the like. It is usually better to
959 /// discharge the binder using `no_bound_vars` or
960 /// `replace_late_bound_regions` or something like
961 /// that. `skip_binder` is only valid when you are either
962 /// extracting data that has nothing to do with bound vars, you
963 /// are doing some sort of test that does not involve bound
964 /// regions, or you are being very careful about your depth
967 /// Some examples where `skip_binder` is reasonable:
969 /// - extracting the `DefId` from a PolyTraitRef;
970 /// - comparing the self type of a PolyTraitRef to see if it is equal to
971 /// a type parameter `X`, since the type `X` does not reference any regions
972 pub fn skip_binder(&self) -> &T {
976 pub fn as_ref(&self) -> Binder<&T> {
980 pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
984 self.as_ref().map_bound(f)
987 pub fn map_bound<F, U>(self, f: F) -> Binder<U>
994 /// Unwraps and returns the value within, but only if it contains
995 /// no bound vars at all. (In other words, if this binder --
996 /// and indeed any enclosing binder -- doesn't bind anything at
997 /// all.) Otherwise, returns `None`.
999 /// (One could imagine having a method that just unwraps a single
1000 /// binder, but permits late-bound vars bound by enclosing
1001 /// binders, but that would require adjusting the debruijn
1002 /// indices, and given the shallow binding structure we often use,
1003 /// would not be that useful.)
1004 pub fn no_bound_vars<'tcx>(self) -> Option<T>
1006 T: TypeFoldable<'tcx>,
1008 if self.skip_binder().has_escaping_bound_vars() {
1011 Some(self.skip_binder().clone())
1015 /// Given two things that have the same binder level,
1016 /// and an operation that wraps on their contents, executes the operation
1017 /// and then wraps its result.
1019 /// `f` should consider bound regions at depth 1 to be free, and
1020 /// anything it produces with bound regions at depth 1 will be
1021 /// bound in the resulting return value.
1022 pub fn fuse<U, F, R>(self, u: Binder<U>, f: F) -> Binder<R>
1024 F: FnOnce(T, U) -> R,
1026 Binder(f(self.0, u.0))
1029 /// Splits the contents into two things that share the same binder
1030 /// level as the original, returning two distinct binders.
1032 /// `f` should consider bound regions at depth 1 to be free, and
1033 /// anything it produces with bound regions at depth 1 will be
1034 /// bound in the resulting return values.
1035 pub fn split<U, V, F>(self, f: F) -> (Binder<U>, Binder<V>)
1037 F: FnOnce(T) -> (U, V),
1039 let (u, v) = f(self.0);
1040 (Binder(u), Binder(v))
1044 /// Represents the projection of an associated type. In explicit UFCS
1045 /// form this would be written `<T as Trait<..>>::N`.
1046 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1047 #[derive(HashStable, TypeFoldable)]
1048 pub struct ProjectionTy<'tcx> {
1049 /// The parameters of the associated item.
1050 pub substs: SubstsRef<'tcx>,
1052 /// The `DefId` of the `TraitItem` for the associated type `N`.
1054 /// Note that this is not the `DefId` of the `TraitRef` containing this
1055 /// associated type, which is in `tcx.associated_item(item_def_id).container`.
1056 pub item_def_id: DefId,
1059 impl<'tcx> ProjectionTy<'tcx> {
1060 /// Construct a `ProjectionTy` by searching the trait from `trait_ref` for the
1061 /// associated item named `item_name`.
1062 pub fn from_ref_and_name(
1064 trait_ref: ty::TraitRef<'tcx>,
1066 ) -> ProjectionTy<'tcx> {
1067 let item_def_id = tcx
1068 .associated_items(trait_ref.def_id)
1069 .find_by_name_and_kind(tcx, item_name, ty::AssocKind::Type, trait_ref.def_id)
1073 ProjectionTy { substs: trait_ref.substs, item_def_id }
1076 /// Extracts the underlying trait reference from this projection.
1077 /// For example, if this is a projection of `<T as Iterator>::Item`,
1078 /// then this function would return a `T: Iterator` trait reference.
1079 pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> {
1080 let def_id = tcx.associated_item(self.item_def_id).container.id();
1081 ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, tcx.generics_of(def_id)) }
1084 pub fn self_ty(&self) -> Ty<'tcx> {
1085 self.substs.type_at(0)
1089 #[derive(Clone, Debug, TypeFoldable)]
1090 pub struct GenSig<'tcx> {
1091 pub resume_ty: Ty<'tcx>,
1092 pub yield_ty: Ty<'tcx>,
1093 pub return_ty: Ty<'tcx>,
1096 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
1098 impl<'tcx> PolyGenSig<'tcx> {
1099 pub fn resume_ty(&self) -> ty::Binder<Ty<'tcx>> {
1100 self.map_bound_ref(|sig| sig.resume_ty)
1102 pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
1103 self.map_bound_ref(|sig| sig.yield_ty)
1105 pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
1106 self.map_bound_ref(|sig| sig.return_ty)
1110 /// Signature of a function type, which we have arbitrarily
1111 /// decided to use to refer to the input/output types.
1113 /// - `inputs`: is the list of arguments and their modes.
1114 /// - `output`: is the return type.
1115 /// - `c_variadic`: indicates whether this is a C-variadic function.
1116 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1117 #[derive(HashStable, TypeFoldable)]
1118 pub struct FnSig<'tcx> {
1119 pub inputs_and_output: &'tcx List<Ty<'tcx>>,
1120 pub c_variadic: bool,
1121 pub unsafety: hir::Unsafety,
1125 impl<'tcx> FnSig<'tcx> {
1126 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
1127 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
1130 pub fn output(&self) -> Ty<'tcx> {
1131 self.inputs_and_output[self.inputs_and_output.len() - 1]
1134 // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible
1136 fn fake() -> FnSig<'tcx> {
1138 inputs_and_output: List::empty(),
1140 unsafety: hir::Unsafety::Normal,
1141 abi: abi::Abi::Rust,
1146 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1148 impl<'tcx> PolyFnSig<'tcx> {
1150 pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
1151 self.map_bound_ref(|fn_sig| fn_sig.inputs())
1154 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
1155 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
1157 pub fn inputs_and_output(&self) -> ty::Binder<&'tcx List<Ty<'tcx>>> {
1158 self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
1161 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
1162 self.map_bound_ref(|fn_sig| fn_sig.output())
1164 pub fn c_variadic(&self) -> bool {
1165 self.skip_binder().c_variadic
1167 pub fn unsafety(&self) -> hir::Unsafety {
1168 self.skip_binder().unsafety
1170 pub fn abi(&self) -> abi::Abi {
1171 self.skip_binder().abi
1175 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<FnSig<'tcx>>>;
1189 pub struct ParamTy {
1194 impl<'tcx> ParamTy {
1195 pub fn new(index: u32, name: Symbol) -> ParamTy {
1196 ParamTy { index, name: name }
1199 pub fn for_self() -> ParamTy {
1200 ParamTy::new(0, kw::SelfUpper)
1203 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1204 ParamTy::new(def.index, def.name)
1207 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1208 tcx.mk_ty_param(self.index, self.name)
1224 pub struct ParamConst {
1229 impl<'tcx> ParamConst {
1230 pub fn new(index: u32, name: Symbol) -> ParamConst {
1231 ParamConst { index, name }
1234 pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
1235 ParamConst::new(def.index, def.name)
1238 pub fn to_const(self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
1239 tcx.mk_const_param(self.index, self.name, ty)
1243 rustc_index::newtype_index! {
1244 /// A [De Bruijn index][dbi] is a standard means of representing
1245 /// regions (and perhaps later types) in a higher-ranked setting. In
1246 /// particular, imagine a type like this:
1248 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1251 /// | +------------+ 0 | |
1253 /// +--------------------------------+ 1 |
1255 /// +------------------------------------------+ 0
1257 /// In this type, there are two binders (the outer fn and the inner
1258 /// fn). We need to be able to determine, for any given region, which
1259 /// fn type it is bound by, the inner or the outer one. There are
1260 /// various ways you can do this, but a De Bruijn index is one of the
1261 /// more convenient and has some nice properties. The basic idea is to
1262 /// count the number of binders, inside out. Some examples should help
1263 /// clarify what I mean.
1265 /// Let's start with the reference type `&'b isize` that is the first
1266 /// argument to the inner function. This region `'b` is assigned a De
1267 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
1268 /// fn). The region `'a` that appears in the second argument type (`&'a
1269 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
1270 /// second-innermost binder". (These indices are written on the arrays
1271 /// in the diagram).
1273 /// What is interesting is that De Bruijn index attached to a particular
1274 /// variable will vary depending on where it appears. For example,
1275 /// the final type `&'a char` also refers to the region `'a` declared on
1276 /// the outermost fn. But this time, this reference is not nested within
1277 /// any other binders (i.e., it is not an argument to the inner fn, but
1278 /// rather the outer one). Therefore, in this case, it is assigned a
1279 /// De Bruijn index of 0, because the innermost binder in that location
1280 /// is the outer fn.
1282 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1283 #[derive(HashStable)]
1284 pub struct DebruijnIndex {
1285 DEBUG_FORMAT = "DebruijnIndex({})",
1286 const INNERMOST = 0,
1290 pub type Region<'tcx> = &'tcx RegionKind;
1292 /// Representation of (lexical) regions. Note that the NLL checker
1293 /// uses a distinct representation of regions. For this reason, it
1294 /// internally replaces all the regions with inference variables --
1295 /// the index of the variable is then used to index into internal NLL
1296 /// data structures. See `rustc_mir::borrow_check` module for more
1299 /// ## The Region lattice within a given function
1301 /// In general, the (lexical, and hence deprecated) region lattice
1305 /// static ----------+-----...------+ (greatest)
1307 /// early-bound and | |
1308 /// free regions | |
1310 /// scope regions | |
1312 /// empty(root) placeholder(U1) |
1314 /// | / placeholder(Un)
1319 /// empty(Un) -------- (smallest)
1322 /// Early-bound/free regions are the named lifetimes in scope from the
1323 /// function declaration. They have relationships to one another
1324 /// determined based on the declared relationships from the
1325 /// function. They all collectively outlive the scope regions. (See
1326 /// `RegionRelations` type, and particularly
1327 /// `crate::infer::outlives::free_region_map::FreeRegionMap`.)
1329 /// The scope regions are related to one another based on the AST
1330 /// structure. (See `RegionRelations` type, and particularly the
1331 /// `rustc::middle::region::ScopeTree`.)
1333 /// Note that inference variables and bound regions are not included
1334 /// in this diagram. In the case of inference variables, they should
1335 /// be inferred to some other region from the diagram. In the case of
1336 /// bound regions, they are excluded because they don't make sense to
1337 /// include -- the diagram indicates the relationship between free
1340 /// ## Inference variables
1342 /// During region inference, we sometimes create inference variables,
1343 /// represented as `ReVar`. These will be inferred by the code in
1344 /// `infer::lexical_region_resolve` to some free region from the
1345 /// lattice above (the minimal region that meets the
1348 /// During NLL checking, where regions are defined differently, we
1349 /// also use `ReVar` -- in that case, the index is used to index into
1350 /// the NLL region checker's data structures. The variable may in fact
1351 /// represent either a free region or an inference variable, in that
1354 /// ## Bound Regions
1356 /// These are regions that are stored behind a binder and must be substituted
1357 /// with some concrete region before being used. There are two kind of
1358 /// bound regions: early-bound, which are bound in an item's `Generics`,
1359 /// and are substituted by a `InternalSubsts`, and late-bound, which are part of
1360 /// higher-ranked types (e.g., `for<'a> fn(&'a ())`), and are substituted by
1361 /// the likes of `liberate_late_bound_regions`. The distinction exists
1362 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1364 /// Unlike `Param`s, bound regions are not supposed to exist "in the wild"
1365 /// outside their binder, e.g., in types passed to type inference, and
1366 /// should first be substituted (by placeholder regions, free regions,
1367 /// or region variables).
1369 /// ## Placeholder and Free Regions
1371 /// One often wants to work with bound regions without knowing their precise
1372 /// identity. For example, when checking a function, the lifetime of a borrow
1373 /// can end up being assigned to some region parameter. In these cases,
1374 /// it must be ensured that bounds on the region can't be accidentally
1375 /// assumed without being checked.
1377 /// To do this, we replace the bound regions with placeholder markers,
1378 /// which don't satisfy any relation not explicitly provided.
1380 /// There are two kinds of placeholder regions in rustc: `ReFree` and
1381 /// `RePlaceholder`. When checking an item's body, `ReFree` is supposed
1382 /// to be used. These also support explicit bounds: both the internally-stored
1383 /// *scope*, which the region is assumed to outlive, as well as other
1384 /// relations stored in the `FreeRegionMap`. Note that these relations
1385 /// aren't checked when you `make_subregion` (or `eq_types`), only by
1386 /// `resolve_regions_and_report_errors`.
1388 /// When working with higher-ranked types, some region relations aren't
1389 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1390 /// `RePlaceholder` is designed for this purpose. In these contexts,
1391 /// there's also the risk that some inference variable laying around will
1392 /// get unified with your placeholder region: if you want to check whether
1393 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1394 /// with a placeholder region `'%a`, the variable `'_` would just be
1395 /// instantiated to the placeholder region `'%a`, which is wrong because
1396 /// the inference variable is supposed to satisfy the relation
1397 /// *for every value of the placeholder region*. To ensure that doesn't
1398 /// happen, you can use `leak_check`. This is more clearly explained
1399 /// by the [rustc guide].
1401 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1402 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1403 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/hrtb.html
1404 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1405 pub enum RegionKind {
1406 /// Region bound in a type or fn declaration which will be
1407 /// substituted 'early' -- that is, at the same time when type
1408 /// parameters are substituted.
1409 ReEarlyBound(EarlyBoundRegion),
1411 /// Region bound in a function scope, which will be substituted when the
1412 /// function is called.
1413 ReLateBound(DebruijnIndex, BoundRegion),
1415 /// When checking a function body, the types of all arguments and so forth
1416 /// that refer to bound region parameters are modified to refer to free
1417 /// region parameters.
1420 /// A concrete region naming some statically determined scope
1421 /// (e.g., an expression or sequence of statements) within the
1422 /// current function.
1423 ReScope(region::Scope),
1425 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1428 /// A region variable. Should not exist after typeck.
1431 /// A placeholder region -- basically, the higher-ranked version of `ReFree`.
1432 /// Should not exist after typeck.
1433 RePlaceholder(ty::PlaceholderRegion),
1435 /// Empty lifetime is for data that is never accessed. We tag the
1436 /// empty lifetime with a universe -- the idea is that we don't
1437 /// want `exists<'a> { forall<'b> { 'b: 'a } }` to be satisfiable.
1438 /// Therefore, the `'empty` in a universe `U` is less than all
1439 /// regions visible from `U`, but not less than regions not visible
1441 ReEmpty(ty::UniverseIndex),
1443 /// Erased region, used by trait selection, in MIR and during codegen.
1446 /// These are regions bound in the "defining type" for a
1447 /// closure. They are used ONLY as part of the
1448 /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1449 /// See `ClosureRegionRequirements` for more details.
1450 ReClosureBound(RegionVid),
1453 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Region<'tcx> {}
1455 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1456 pub struct EarlyBoundRegion {
1462 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1467 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1468 pub struct ConstVid<'tcx> {
1470 pub phantom: PhantomData<&'tcx ()>,
1473 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1478 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1479 pub struct FloatVid {
1483 rustc_index::newtype_index! {
1484 pub struct RegionVid {
1485 DEBUG_FORMAT = custom,
1489 impl Atom for RegionVid {
1490 fn index(self) -> usize {
1512 /// A `FreshTy` is one that is generated as a replacement for an
1513 /// unbound type variable. This is convenient for caching etc. See
1514 /// `infer::freshen` for more details.
1520 rustc_index::newtype_index! {
1521 pub struct BoundVar { .. }
1537 pub struct BoundTy {
1539 pub kind: BoundTyKind,
1555 pub enum BoundTyKind {
1560 impl From<BoundVar> for BoundTy {
1561 fn from(var: BoundVar) -> Self {
1562 BoundTy { var, kind: BoundTyKind::Anon }
1566 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1567 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1568 #[derive(HashStable, TypeFoldable)]
1569 pub struct ExistentialProjection<'tcx> {
1570 pub item_def_id: DefId,
1571 pub substs: SubstsRef<'tcx>,
1575 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1577 impl<'tcx> ExistentialProjection<'tcx> {
1578 /// Extracts the underlying existential trait reference from this projection.
1579 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1580 /// then this function would return a `exists T. T: Iterator` existential trait
1582 pub fn trait_ref(&self, tcx: TyCtxt<'_>) -> ty::ExistentialTraitRef<'tcx> {
1583 let def_id = tcx.associated_item(self.item_def_id).container.id();
1584 ty::ExistentialTraitRef { def_id, substs: self.substs }
1587 pub fn with_self_ty(
1591 ) -> ty::ProjectionPredicate<'tcx> {
1592 // otherwise the escaping regions would be captured by the binders
1593 debug_assert!(!self_ty.has_escaping_bound_vars());
1595 ty::ProjectionPredicate {
1596 projection_ty: ty::ProjectionTy {
1597 item_def_id: self.item_def_id,
1598 substs: tcx.mk_substs_trait(self_ty, self.substs),
1605 impl<'tcx> PolyExistentialProjection<'tcx> {
1606 pub fn with_self_ty(
1610 ) -> ty::PolyProjectionPredicate<'tcx> {
1611 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1614 pub fn item_def_id(&self) -> DefId {
1615 return self.skip_binder().item_def_id;
1619 impl DebruijnIndex {
1620 /// Returns the resulting index when this value is moved into
1621 /// `amount` number of new binders. So, e.g., if you had
1623 /// for<'a> fn(&'a x)
1625 /// and you wanted to change it to
1627 /// for<'a> fn(for<'b> fn(&'a x))
1629 /// you would need to shift the index for `'a` into a new binder.
1631 pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
1632 DebruijnIndex::from_u32(self.as_u32() + amount)
1635 /// Update this index in place by shifting it "in" through
1636 /// `amount` number of binders.
1637 pub fn shift_in(&mut self, amount: u32) {
1638 *self = self.shifted_in(amount);
1641 /// Returns the resulting index when this value is moved out from
1642 /// `amount` number of new binders.
1644 pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
1645 DebruijnIndex::from_u32(self.as_u32() - amount)
1648 /// Update in place by shifting out from `amount` binders.
1649 pub fn shift_out(&mut self, amount: u32) {
1650 *self = self.shifted_out(amount);
1653 /// Adjusts any De Bruijn indices so as to make `to_binder` the
1654 /// innermost binder. That is, if we have something bound at `to_binder`,
1655 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1656 /// when moving a region out from inside binders:
1659 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1660 /// // Binder: D3 D2 D1 ^^
1663 /// Here, the region `'a` would have the De Bruijn index D3,
1664 /// because it is the bound 3 binders out. However, if we wanted
1665 /// to refer to that region `'a` in the second argument (the `_`),
1666 /// those two binders would not be in scope. In that case, we
1667 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1668 /// De Bruijn index of `'a` to D1 (the innermost binder).
1670 /// If we invoke `shift_out_to_binder` and the region is in fact
1671 /// bound by one of the binders we are shifting out of, that is an
1672 /// error (and should fail an assertion failure).
1673 pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
1674 self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
1678 /// Region utilities
1680 /// Is this region named by the user?
1681 pub fn has_name(&self) -> bool {
1683 RegionKind::ReEarlyBound(ebr) => ebr.has_name(),
1684 RegionKind::ReLateBound(_, br) => br.is_named(),
1685 RegionKind::ReFree(fr) => fr.bound_region.is_named(),
1686 RegionKind::ReScope(..) => false,
1687 RegionKind::ReStatic => true,
1688 RegionKind::ReVar(..) => false,
1689 RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(),
1690 RegionKind::ReEmpty(_) => false,
1691 RegionKind::ReErased => false,
1692 RegionKind::ReClosureBound(..) => false,
1696 pub fn is_late_bound(&self) -> bool {
1698 ty::ReLateBound(..) => true,
1703 pub fn is_placeholder(&self) -> bool {
1705 ty::RePlaceholder(..) => true,
1710 pub fn bound_at_or_above_binder(&self, index: DebruijnIndex) -> bool {
1712 ty::ReLateBound(debruijn, _) => debruijn >= index,
1717 /// Adjusts any De Bruijn indices so as to make `to_binder` the
1718 /// innermost binder. That is, if we have something bound at `to_binder`,
1719 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1720 /// when moving a region out from inside binders:
1723 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1724 /// // Binder: D3 D2 D1 ^^
1727 /// Here, the region `'a` would have the De Bruijn index D3,
1728 /// because it is the bound 3 binders out. However, if we wanted
1729 /// to refer to that region `'a` in the second argument (the `_`),
1730 /// those two binders would not be in scope. In that case, we
1731 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1732 /// De Bruijn index of `'a` to D1 (the innermost binder).
1734 /// If we invoke `shift_out_to_binder` and the region is in fact
1735 /// bound by one of the binders we are shifting out of, that is an
1736 /// error (and should fail an assertion failure).
1737 pub fn shifted_out_to_binder(&self, to_binder: ty::DebruijnIndex) -> RegionKind {
1739 ty::ReLateBound(debruijn, r) => {
1740 ty::ReLateBound(debruijn.shifted_out_to_binder(to_binder), r)
1746 pub fn keep_in_local_tcx(&self) -> bool {
1747 if let ty::ReVar(..) = self { true } else { false }
1750 pub fn type_flags(&self) -> TypeFlags {
1751 let mut flags = TypeFlags::empty();
1753 if self.keep_in_local_tcx() {
1754 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1759 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1760 flags = flags | TypeFlags::HAS_RE_INFER;
1762 ty::RePlaceholder(..) => {
1763 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1764 flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
1766 ty::ReLateBound(..) => {
1767 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1769 ty::ReEarlyBound(..) => {
1770 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1771 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1773 ty::ReEmpty(_) | ty::ReStatic | ty::ReFree { .. } | ty::ReScope { .. } => {
1774 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1777 flags = flags | TypeFlags::HAS_RE_ERASED;
1779 ty::ReClosureBound(..) => {
1780 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1785 ty::ReStatic | ty::ReEmpty(_) | ty::ReErased | ty::ReLateBound(..) => (),
1786 _ => flags = flags | TypeFlags::HAS_FREE_LOCAL_NAMES,
1789 debug!("type_flags({:?}) = {:?}", self, flags);
1794 /// Given an early-bound or free region, returns the `DefId` where it was bound.
1795 /// For example, consider the regions in this snippet of code:
1799 /// ^^ -- early bound, declared on an impl
1801 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1802 /// ^^ ^^ ^ anonymous, late-bound
1803 /// | early-bound, appears in where-clauses
1804 /// late-bound, appears only in fn args
1809 /// Here, `free_region_binding_scope('a)` would return the `DefId`
1810 /// of the impl, and for all the other highlighted regions, it
1811 /// would return the `DefId` of the function. In other cases (not shown), this
1812 /// function might return the `DefId` of a closure.
1813 pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_>) -> DefId {
1815 ty::ReEarlyBound(br) => tcx.parent(br.def_id).unwrap(),
1816 ty::ReFree(fr) => fr.scope,
1817 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1823 impl<'tcx> TyS<'tcx> {
1825 pub fn is_unit(&self) -> bool {
1827 Tuple(ref tys) => tys.is_empty(),
1833 pub fn is_never(&self) -> bool {
1840 /// Checks whether a type is definitely uninhabited. This is
1841 /// conservative: for some types that are uninhabited we return `false`,
1842 /// but we only return `true` for types that are definitely uninhabited.
1843 /// `ty.conservative_is_privately_uninhabited` implies that any value of type `ty`
1844 /// will be `Abi::Uninhabited`. (Note that uninhabited types may have nonzero
1845 /// size, to account for partial initialisation. See #49298 for details.)
1846 pub fn conservative_is_privately_uninhabited(&self, tcx: TyCtxt<'tcx>) -> bool {
1847 // FIXME(varkor): we can make this less conversative by substituting concrete
1851 ty::Adt(def, _) if def.is_union() => {
1852 // For now, `union`s are never considered uninhabited.
1855 ty::Adt(def, _) => {
1856 // Any ADT is uninhabited if either:
1857 // (a) It has no variants (i.e. an empty `enum`);
1858 // (b) Each of its variants (a single one in the case of a `struct`) has at least
1859 // one uninhabited field.
1860 def.variants.iter().all(|var| {
1861 var.fields.iter().any(|field| {
1862 tcx.type_of(field.did).conservative_is_privately_uninhabited(tcx)
1867 self.tuple_fields().any(|ty| ty.conservative_is_privately_uninhabited(tcx))
1869 ty::Array(ty, len) => {
1870 match len.try_eval_usize(tcx, ParamEnv::empty()) {
1871 // If the array is definitely non-empty, it's uninhabited if
1872 // the type of its elements is uninhabited.
1873 Some(n) if n != 0 => ty.conservative_is_privately_uninhabited(tcx),
1878 // References to uninitialised memory is valid for any type, including
1879 // uninhabited types, in unsafe code, so we treat all references as
1888 pub fn is_primitive(&self) -> bool {
1890 Bool | Char | Int(_) | Uint(_) | Float(_) => true,
1896 pub fn is_ty_var(&self) -> bool {
1898 Infer(TyVar(_)) => true,
1904 pub fn is_ty_infer(&self) -> bool {
1912 pub fn is_phantom_data(&self) -> bool {
1913 if let Adt(def, _) = self.kind { def.is_phantom_data() } else { false }
1917 pub fn is_bool(&self) -> bool {
1921 /// Returns `true` if this type is a `str`.
1923 pub fn is_str(&self) -> bool {
1928 pub fn is_param(&self, index: u32) -> bool {
1930 ty::Param(ref data) => data.index == index,
1936 pub fn is_slice(&self) -> bool {
1938 RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => match ty.kind {
1939 Slice(_) | Str => true,
1947 pub fn is_simd(&self) -> bool {
1949 Adt(def, _) => def.repr.simd(),
1954 pub fn sequence_element_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1956 Array(ty, _) | Slice(ty) => ty,
1957 Str => tcx.mk_mach_uint(ast::UintTy::U8),
1958 _ => bug!("`sequence_element_type` called on non-sequence value: {}", self),
1962 pub fn simd_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1964 Adt(def, substs) => def.non_enum_variant().fields[0].ty(tcx, substs),
1965 _ => bug!("`simd_type` called on invalid type"),
1969 pub fn simd_size(&self, _tcx: TyCtxt<'tcx>) -> u64 {
1970 // Parameter currently unused, but probably needed in the future to
1971 // allow `#[repr(simd)] struct Simd<T, const N: usize>([T; N]);`.
1973 Adt(def, _) => def.non_enum_variant().fields.len() as u64,
1974 _ => bug!("`simd_size` called on invalid type"),
1978 pub fn simd_size_and_type(&self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1980 Adt(def, substs) => {
1981 let variant = def.non_enum_variant();
1982 (variant.fields.len() as u64, variant.fields[0].ty(tcx, substs))
1984 _ => bug!("`simd_size_and_type` called on invalid type"),
1989 pub fn is_region_ptr(&self) -> bool {
1997 pub fn is_mutable_ptr(&self) -> bool {
1999 RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. })
2000 | Ref(_, _, hir::Mutability::Mut) => true,
2006 pub fn is_unsafe_ptr(&self) -> bool {
2008 RawPtr(_) => return true,
2013 /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
2015 pub fn is_any_ptr(&self) -> bool {
2016 self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr()
2019 /// Returns `true` if this type is an `Arc<T>`.
2021 pub fn is_arc(&self) -> bool {
2023 Adt(def, _) => def.is_arc(),
2028 /// Returns `true` if this type is an `Rc<T>`.
2030 pub fn is_rc(&self) -> bool {
2032 Adt(def, _) => def.is_rc(),
2038 pub fn is_box(&self) -> bool {
2040 Adt(def, _) => def.is_box(),
2045 /// Panics if called on any type other than `Box<T>`.
2046 pub fn boxed_ty(&self) -> Ty<'tcx> {
2048 Adt(def, substs) if def.is_box() => substs.type_at(0),
2049 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
2053 /// A scalar type is one that denotes an atomic datum, with no sub-components.
2054 /// (A RawPtr is scalar because it represents a non-managed pointer, so its
2055 /// contents are abstract to rustc.)
2057 pub fn is_scalar(&self) -> bool {
2059 Bool | Char | Int(_) | Float(_) | Uint(_) | Infer(IntVar(_)) | Infer(FloatVar(_))
2060 | FnDef(..) | FnPtr(_) | RawPtr(_) => true,
2065 /// Returns `true` if this type is a floating point type.
2067 pub fn is_floating_point(&self) -> bool {
2069 Float(_) | Infer(FloatVar(_)) => true,
2075 pub fn is_trait(&self) -> bool {
2077 Dynamic(..) => true,
2083 pub fn is_enum(&self) -> bool {
2085 Adt(adt_def, _) => adt_def.is_enum(),
2091 pub fn is_closure(&self) -> bool {
2093 Closure(..) => true,
2099 pub fn is_generator(&self) -> bool {
2101 Generator(..) => true,
2107 pub fn is_integral(&self) -> bool {
2109 Infer(IntVar(_)) | Int(_) | Uint(_) => true,
2115 pub fn is_fresh_ty(&self) -> bool {
2117 Infer(FreshTy(_)) => true,
2123 pub fn is_fresh(&self) -> bool {
2125 Infer(FreshTy(_)) => true,
2126 Infer(FreshIntTy(_)) => true,
2127 Infer(FreshFloatTy(_)) => true,
2133 pub fn is_char(&self) -> bool {
2141 pub fn is_numeric(&self) -> bool {
2142 self.is_integral() || self.is_floating_point()
2146 pub fn is_signed(&self) -> bool {
2154 pub fn is_ptr_sized_integral(&self) -> bool {
2156 Int(ast::IntTy::Isize) | Uint(ast::UintTy::Usize) => true,
2162 pub fn is_machine(&self) -> bool {
2164 Int(..) | Uint(..) | Float(..) => true,
2170 pub fn has_concrete_skeleton(&self) -> bool {
2172 Param(_) | Infer(_) | Error => false,
2177 /// Returns the type and mutability of `*ty`.
2179 /// The parameter `explicit` indicates if this is an *explicit* dereference.
2180 /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
2181 pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
2183 Adt(def, _) if def.is_box() => {
2184 Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not })
2186 Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
2187 RawPtr(mt) if explicit => Some(mt),
2192 /// Returns the type of `ty[i]`.
2193 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
2195 Array(ty, _) | Slice(ty) => Some(ty),
2200 pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
2202 FnDef(def_id, substs) => tcx.fn_sig(def_id).subst(tcx, substs),
2205 // ignore errors (#54954)
2206 ty::Binder::dummy(FnSig::fake())
2209 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`",)
2211 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self),
2216 pub fn is_fn(&self) -> bool {
2218 FnDef(..) | FnPtr(_) => true,
2224 pub fn is_fn_ptr(&self) -> bool {
2232 pub fn is_impl_trait(&self) -> bool {
2240 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
2242 Adt(adt, _) => Some(adt),
2247 /// Iterates over tuple fields.
2248 /// Panics when called on anything but a tuple.
2249 pub fn tuple_fields(&self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> {
2251 Tuple(substs) => substs.iter().map(|field| field.expect_ty()),
2252 _ => bug!("tuple_fields called on non-tuple"),
2256 /// If the type contains variants, returns the valid range of variant indices.
2258 // FIXME: This requires the optimized MIR in the case of generators.
2260 pub fn variant_range(&self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
2262 TyKind::Adt(adt, _) => Some(adt.variant_range()),
2263 TyKind::Generator(def_id, substs, _) => {
2264 Some(substs.as_generator().variant_range(def_id, tcx))
2270 /// If the type contains variants, returns the variant for `variant_index`.
2271 /// Panics if `variant_index` is out of range.
2273 // FIXME: This requires the optimized MIR in the case of generators.
2275 pub fn discriminant_for_variant(
2278 variant_index: VariantIdx,
2279 ) -> Option<Discr<'tcx>> {
2281 TyKind::Adt(adt, _) => Some(adt.discriminant_for_variant(tcx, variant_index)),
2282 TyKind::Generator(def_id, substs, _) => {
2283 Some(substs.as_generator().discriminant_for_variant(def_id, tcx, variant_index))
2289 /// Pushes onto `out` the regions directly referenced from this type (but not
2290 /// types reachable from this type via `walk_tys`). This ignores late-bound
2291 /// regions binders.
2292 pub fn push_regions(&self, out: &mut SmallVec<[ty::Region<'tcx>; 4]>) {
2294 Ref(region, _, _) => {
2297 Dynamic(ref obj, region) => {
2299 if let Some(principal) = obj.principal() {
2300 out.extend(principal.skip_binder().substs.regions());
2303 Adt(_, substs) | Opaque(_, substs) => out.extend(substs.regions()),
2304 Closure(_, ref substs) | Generator(_, ref substs, _) => out.extend(substs.regions()),
2305 Projection(ref data) | UnnormalizedProjection(ref data) => {
2306 out.extend(data.substs.regions())
2308 FnDef(..) | FnPtr(_) | GeneratorWitness(..) | Bool | Char | Int(_) | Uint(_)
2309 | Float(_) | Str | Array(..) | Slice(_) | RawPtr(_) | Never | Tuple(..)
2310 | Foreign(..) | Param(_) | Bound(..) | Placeholder(..) | Infer(_) | Error => {}
2314 /// When we create a closure, we record its kind (i.e., what trait
2315 /// it implements) into its `ClosureSubsts` using a type
2316 /// parameter. This is kind of a phantom type, except that the
2317 /// most convenient thing for us to are the integral types. This
2318 /// function converts such a special type into the closure
2319 /// kind. To go the other way, use
2320 /// `tcx.closure_kind_ty(closure_kind)`.
2322 /// Note that during type checking, we use an inference variable
2323 /// to represent the closure kind, because it has not yet been
2324 /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
2325 /// is complete, that type variable will be unified.
2326 pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
2328 Int(int_ty) => match int_ty {
2329 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
2330 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
2331 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
2332 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2335 // "Bound" types appear in canonical queries when the
2336 // closure type is not yet known
2337 Bound(..) | Infer(_) => None,
2339 Error => Some(ty::ClosureKind::Fn),
2341 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2345 /// Fast path helper for testing if a type is `Sized`.
2347 /// Returning true means the type is known to be sized. Returning
2348 /// `false` means nothing -- could be sized, might not be.
2349 pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool {
2351 ty::Infer(ty::IntVar(_))
2352 | ty::Infer(ty::FloatVar(_))
2363 | ty::GeneratorWitness(..)
2367 | ty::Error => true,
2369 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => false,
2371 ty::Tuple(tys) => tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx)),
2373 ty::Adt(def, _substs) => def.sized_constraint(tcx).is_empty(),
2375 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
2377 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
2379 ty::Infer(ty::TyVar(_)) => false,
2382 | ty::Placeholder(..)
2383 | ty::Infer(ty::FreshTy(_))
2384 | ty::Infer(ty::FreshIntTy(_))
2385 | ty::Infer(ty::FreshFloatTy(_)) => {
2386 bug!("`is_trivially_sized` applied to unexpected type: {:?}", self)
2392 /// Typed constant value.
2406 pub struct Const<'tcx> {
2409 pub val: ConstKind<'tcx>,
2412 #[cfg(target_arch = "x86_64")]
2413 static_assert_size!(Const<'_>, 48);
2415 impl<'tcx> Const<'tcx> {
2417 pub fn from_value(tcx: TyCtxt<'tcx>, val: ConstValue<'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
2418 tcx.mk_const(Self { val: ConstKind::Value(val), ty })
2422 pub fn from_scalar(tcx: TyCtxt<'tcx>, val: Scalar, ty: Ty<'tcx>) -> &'tcx Self {
2423 Self::from_value(tcx, ConstValue::Scalar(val), ty)
2427 pub fn from_bits(tcx: TyCtxt<'tcx>, bits: u128, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> &'tcx Self {
2430 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
2432 Self::from_scalar(tcx, Scalar::from_uint(bits, size), ty.value)
2436 pub fn zero_sized(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
2437 Self::from_scalar(tcx, Scalar::zst(), ty)
2441 pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> &'tcx Self {
2442 Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
2446 pub fn from_usize(tcx: TyCtxt<'tcx>, n: u64) -> &'tcx Self {
2447 Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
2451 pub fn try_eval_bits(
2454 param_env: ParamEnv<'tcx>,
2457 assert_eq!(self.ty, ty);
2458 let size = tcx.layout_of(param_env.with_reveal_all().and(ty)).ok()?.size;
2459 // if `ty` does not depend on generic parameters, use an empty param_env
2460 self.eval(tcx, param_env).val.try_to_bits(size)
2464 pub fn eval(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> &Const<'tcx> {
2465 let try_const_eval = |did, param_env: ParamEnv<'tcx>, substs, promoted| {
2466 let param_env_and_substs = param_env.with_reveal_all().and(substs);
2468 // Avoid querying `tcx.const_eval(...)` with any e.g. inference vars.
2469 if param_env_and_substs.has_local_value() {
2473 let (param_env, substs) = param_env_and_substs.into_parts();
2475 // try to resolve e.g. associated constants to their definition on an impl, and then
2476 // evaluate the const.
2477 tcx.const_eval_resolve(param_env, did, substs, promoted, None)
2479 .map(|val| Const::from_value(tcx, val, self.ty))
2483 ConstKind::Unevaluated(did, substs, promoted) => {
2484 // HACK(eddyb) when substs contain e.g. inference variables,
2485 // attempt using identity substs instead, that will succeed
2486 // when the expression doesn't depend on any parameters.
2487 // FIXME(eddyb) make `const_eval` a canonical query instead,
2488 // that would properly handle inference variables in `substs`.
2489 if substs.has_local_value() {
2490 let identity_substs = InternalSubsts::identity_for_item(tcx, did);
2491 // The `ParamEnv` needs to match the `identity_substs`.
2492 let identity_param_env = tcx.param_env(did);
2493 match try_const_eval(did, identity_param_env, identity_substs, promoted) {
2494 Some(ct) => ct.subst(tcx, substs),
2498 try_const_eval(did, param_env, substs, promoted).unwrap_or(self)
2506 pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<bool> {
2507 self.try_eval_bits(tcx, param_env, tcx.types.bool).and_then(|v| match v {
2515 pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<u64> {
2516 self.try_eval_bits(tcx, param_env, tcx.types.usize).map(|v| v as u64)
2520 pub fn eval_bits(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: Ty<'tcx>) -> u128 {
2521 self.try_eval_bits(tcx, param_env, ty)
2522 .unwrap_or_else(|| bug!("expected bits of {:#?}, got {:#?}", ty, self))
2526 pub fn eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> u64 {
2527 self.eval_bits(tcx, param_env, tcx.types.usize) as u64
2531 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}
2533 /// Represents a constant in Rust.
2547 pub enum ConstKind<'tcx> {
2548 /// A const generic parameter.
2551 /// Infer the value of the const.
2552 Infer(InferConst<'tcx>),
2554 /// Bound const variable, used only when preparing a trait query.
2555 Bound(DebruijnIndex, BoundVar),
2557 /// A placeholder const - universally quantified higher-ranked const.
2558 Placeholder(ty::PlaceholderConst),
2560 /// Used in the HIR by using `Unevaluated` everywhere and later normalizing to one of the other
2561 /// variants when the code is monomorphic enough for that.
2562 Unevaluated(DefId, SubstsRef<'tcx>, Option<Promoted>),
2564 /// Used to hold computed value.
2565 Value(ConstValue<'tcx>),
2568 #[cfg(target_arch = "x86_64")]
2569 static_assert_size!(ConstKind<'_>, 40);
2571 impl<'tcx> ConstKind<'tcx> {
2573 pub fn try_to_scalar(&self) -> Option<Scalar> {
2574 if let ConstKind::Value(val) = self { val.try_to_scalar() } else { None }
2578 pub fn try_to_bits(&self, size: ty::layout::Size) -> Option<u128> {
2579 self.try_to_scalar()?.to_bits(size).ok()
2583 /// An inference variable for a const, for use in const generics.
2597 pub enum InferConst<'tcx> {
2598 /// Infer the value of the const.
2599 Var(ConstVid<'tcx>),
2600 /// A fresh const variable. See `infer::freshen` for more details.