1 //! This module contains `TyKind` and its major components.
3 #![allow(rustc::usage_of_ty_tykind)]
6 use crate::hir::def_id::DefId;
7 use crate::infer::canonical::Canonical;
8 use crate::mir::interpret::ConstValue;
9 use crate::middle::region;
10 use polonius_engine::Atom;
11 use rustc_data_structures::indexed_vec::Idx;
12 use rustc_macros::HashStable;
13 use crate::ty::subst::{InternalSubsts, Subst, SubstsRef, Kind, UnpackedKind};
14 use crate::ty::{self, AdtDef, Discr, DefIdTree, TypeFlags, Ty, TyCtxt, TypeFoldable};
15 use crate::ty::{List, TyS, ParamEnvAnd, ParamEnv};
16 use crate::ty::layout::VariantIdx;
17 use crate::util::captures::Captures;
18 use crate::mir::interpret::{Scalar, GlobalId};
20 use smallvec::SmallVec;
22 use std::cmp::Ordering;
23 use std::marker::PhantomData;
25 use rustc_target::spec::abi;
26 use syntax::ast::{self, Ident};
27 use syntax::symbol::{kw, InternedString};
32 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
33 Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
34 pub struct TypeAndMut<'tcx> {
36 pub mutbl: hir::Mutability,
39 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
40 RustcEncodable, RustcDecodable, Copy, HashStable)]
41 /// A "free" region `fr` can be interpreted as "some region
42 /// at least as big as the scope `fr.scope`".
43 pub struct FreeRegion {
45 pub bound_region: BoundRegion,
48 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
49 RustcEncodable, RustcDecodable, Copy, HashStable)]
50 pub enum BoundRegion {
51 /// An anonymous region parameter for a given fn (&T)
54 /// Named region parameters for functions (a in &'a T)
56 /// The `DefId` is needed to distinguish free regions in
57 /// the event of shadowing.
58 BrNamed(DefId, InternedString),
60 /// Anonymous region for the implicit env pointer parameter
66 pub fn is_named(&self) -> bool {
68 BoundRegion::BrNamed(..) => true,
73 /// When canonicalizing, we replace unbound inference variables and free
74 /// regions with anonymous late bound regions. This method asserts that
75 /// we have an anonymous late bound region, which hence may refer to
76 /// a canonical variable.
77 pub fn assert_bound_var(&self) -> BoundVar {
79 BoundRegion::BrAnon(var) => BoundVar::from_u32(var),
80 _ => bug!("bound region is not anonymous"),
85 /// N.B., if you change this, you'll probably want to change the corresponding
86 /// AST structure in `libsyntax/ast.rs` as well.
87 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
88 RustcEncodable, RustcDecodable, HashStable, Debug)]
89 #[cfg_attr(not(bootstrap), rustc_diagnostic_item = "TyKind")]
90 pub enum TyKind<'tcx> {
91 /// The primitive boolean type. Written as `bool`.
94 /// The primitive character type; holds a Unicode scalar value
95 /// (a non-surrogate code point). Written as `char`.
98 /// A primitive signed integer type. For example, `i32`.
101 /// A primitive unsigned integer type. For example, `u32`.
104 /// A primitive floating-point type. For example, `f64`.
107 /// Structures, enumerations and unions.
109 /// InternalSubsts here, possibly against intuition, *may* contain `Param`s.
110 /// That is, even after substitution it is possible that there are type
111 /// variables. This happens when the `Adt` corresponds to an ADT
112 /// definition and not a concrete use of it.
113 Adt(&'tcx AdtDef, SubstsRef<'tcx>),
115 /// An unsized FFI type that is opaque to Rust. Written as `extern type T`.
118 /// The pointee of a string slice. Written as `str`.
121 /// An array with the given length. Written as `[T; n]`.
122 Array(Ty<'tcx>, &'tcx ty::Const<'tcx>),
124 /// The pointee of an array slice. Written as `[T]`.
127 /// A raw pointer. Written as `*mut T` or `*const T`
128 RawPtr(TypeAndMut<'tcx>),
130 /// A reference; a pointer with an associated lifetime. Written as
131 /// `&'a mut T` or `&'a T`.
132 Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability),
134 /// The anonymous type of a function declaration/definition. Each
135 /// function has a unique type, which is output (for a function
136 /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
138 /// For example the type of `bar` here:
141 /// fn foo() -> i32 { 1 }
142 /// let bar = foo; // bar: fn() -> i32 {foo}
144 FnDef(DefId, SubstsRef<'tcx>),
146 /// A pointer to a function. Written as `fn() -> i32`.
148 /// For example the type of `bar` here:
151 /// fn foo() -> i32 { 1 }
152 /// let bar: fn() -> i32 = foo;
154 FnPtr(PolyFnSig<'tcx>),
156 /// A trait, defined with `trait`.
157 Dynamic(Binder<&'tcx List<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
159 /// The anonymous type of a closure. Used to represent the type of
161 Closure(DefId, ClosureSubsts<'tcx>),
163 /// The anonymous type of a generator. Used to represent the type of
165 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
167 /// A type representin the types stored inside a generator.
168 /// This should only appear in GeneratorInteriors.
169 GeneratorWitness(Binder<&'tcx List<Ty<'tcx>>>),
171 /// The never type `!`
174 /// A tuple type. For example, `(i32, bool)`.
175 /// Use `TyS::tuple_fields` to iterate over the field types.
176 Tuple(SubstsRef<'tcx>),
178 /// The projection of an associated type. For example,
179 /// `<T as Trait<..>>::N`.
180 Projection(ProjectionTy<'tcx>),
182 /// A placeholder type used when we do not have enough information
183 /// to normalize the projection of an associated type to an
184 /// existing concrete type. Currently only used with chalk-engine.
185 UnnormalizedProjection(ProjectionTy<'tcx>),
187 /// Opaque (`impl Trait`) type found in a return type.
188 /// The `DefId` comes either from
189 /// * the `impl Trait` ast::Ty node,
190 /// * or the `type Foo = impl Trait` declaration
191 /// The substitutions are for the generics of the function in question.
192 /// After typeck, the concrete type can be found in the `types` map.
193 Opaque(DefId, SubstsRef<'tcx>),
195 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
198 /// Bound type variable, used only when preparing a trait query.
199 Bound(ty::DebruijnIndex, BoundTy),
201 /// A placeholder type - universally quantified higher-ranked type.
202 Placeholder(ty::PlaceholderType),
204 /// A type variable used during type checking.
207 /// A placeholder for a type which could not be computed; this is
208 /// propagated to avoid useless error messages.
212 // `TyKind` is used a lot. Make sure it doesn't unintentionally get bigger.
213 #[cfg(target_arch = "x86_64")]
214 static_assert_size!(TyKind<'_>, 24);
216 /// A closure can be modeled as a struct that looks like:
218 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
226 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
227 /// in scope on the function that defined the closure,
228 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
229 /// is rather hackily encoded via a scalar type. See
230 /// `TyS::to_opt_closure_kind` for details.
231 /// - CS represents the *closure signature*, representing as a `fn()`
232 /// type. For example, `fn(u32, u32) -> u32` would mean that the closure
233 /// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
235 /// - U0...Uk are type parameters representing the types of its upvars
236 /// (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
237 /// and the up-var has the type `Foo`, then `Ui = &Foo`).
239 /// So, for example, given this function:
241 /// fn foo<'a, T>(data: &'a mut T) {
242 /// do(|| data.count += 1)
245 /// the type of the closure would be something like:
247 /// struct Closure<'a, T, U0> {
251 /// Note that the type of the upvar is not specified in the struct.
252 /// You may wonder how the impl would then be able to use the upvar,
253 /// if it doesn't know it's type? The answer is that the impl is
254 /// (conceptually) not fully generic over Closure but rather tied to
255 /// instances with the expected upvar types:
257 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
261 /// You can see that the *impl* fully specified the type of the upvar
262 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
263 /// (Here, I am assuming that `data` is mut-borrowed.)
265 /// Now, the last question you may ask is: Why include the upvar types
266 /// as extra type parameters? The reason for this design is that the
267 /// upvar types can reference lifetimes that are internal to the
268 /// creating function. In my example above, for example, the lifetime
269 /// `'b` represents the scope of the closure itself; this is some
270 /// subset of `foo`, probably just the scope of the call to the to
271 /// `do()`. If we just had the lifetime/type parameters from the
272 /// enclosing function, we couldn't name this lifetime `'b`. Note that
273 /// there can also be lifetimes in the types of the upvars themselves,
274 /// if one of them happens to be a reference to something that the
275 /// creating fn owns.
277 /// OK, you say, so why not create a more minimal set of parameters
278 /// that just includes the extra lifetime parameters? The answer is
279 /// primarily that it would be hard --- we don't know at the time when
280 /// we create the closure type what the full types of the upvars are,
281 /// nor do we know which are borrowed and which are not. In this
282 /// design, we can just supply a fresh type parameter and figure that
285 /// All right, you say, but why include the type parameters from the
286 /// original function then? The answer is that codegen may need them
287 /// when monomorphizing, and they may not appear in the upvars. A
288 /// closure could capture no variables but still make use of some
289 /// in-scope type parameter with a bound (e.g., if our example above
290 /// had an extra `U: Default`, and the closure called `U::default()`).
292 /// There is another reason. This design (implicitly) prohibits
293 /// closures from capturing themselves (except via a trait
294 /// object). This simplifies closure inference considerably, since it
295 /// means that when we infer the kind of a closure or its upvars, we
296 /// don't have to handle cycles where the decisions we make for
297 /// closure C wind up influencing the decisions we ought to make for
298 /// closure C (which would then require fixed point iteration to
299 /// handle). Plus it fixes an ICE. :P
303 /// Generators are handled similarly in `GeneratorSubsts`. The set of
304 /// type parameters is similar, but the role of CK and CS are
305 /// different. CK represents the "yield type" and CS represents the
306 /// "return type" of the generator.
307 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
308 Debug, RustcEncodable, RustcDecodable, HashStable)]
309 pub struct ClosureSubsts<'tcx> {
310 /// Lifetime and type parameters from the enclosing function,
311 /// concatenated with the types of the upvars.
313 /// These are separated out because codegen wants to pass them around
314 /// when monomorphizing.
315 pub substs: SubstsRef<'tcx>,
318 /// Struct returned by `split()`. Note that these are subslices of the
319 /// parent slice and not canonical substs themselves.
320 struct SplitClosureSubsts<'tcx> {
321 closure_kind_ty: Ty<'tcx>,
322 closure_sig_ty: Ty<'tcx>,
323 upvar_kinds: &'tcx [Kind<'tcx>],
326 impl<'tcx> ClosureSubsts<'tcx> {
327 /// Divides the closure substs into their respective
328 /// components. Single source of truth with respect to the
330 fn split(self, def_id: DefId, tcx: TyCtxt<'_>) -> SplitClosureSubsts<'tcx> {
331 let generics = tcx.generics_of(def_id);
332 let parent_len = generics.parent_count;
334 closure_kind_ty: self.substs.type_at(parent_len),
335 closure_sig_ty: self.substs.type_at(parent_len + 1),
336 upvar_kinds: &self.substs[parent_len + 2..],
345 ) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
346 let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
347 upvar_kinds.iter().map(|t| {
348 if let UnpackedKind::Type(ty) = t.unpack() {
351 bug!("upvar should be type")
356 /// Returns the closure kind for this closure; may return a type
357 /// variable during inference. To get the closure kind during
358 /// inference, use `infcx.closure_kind(def_id, substs)`.
359 pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
360 self.split(def_id, tcx).closure_kind_ty
363 /// Returns the type representing the closure signature for this
364 /// closure; may contain type variables during inference. To get
365 /// the closure signature during inference, use
366 /// `infcx.fn_sig(def_id)`.
367 pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
368 self.split(def_id, tcx).closure_sig_ty
371 /// Returns the closure kind for this closure; only usable outside
372 /// of an inference context, because in that context we know that
373 /// there are no type variables.
375 /// If you have an inference context, use `infcx.closure_kind()`.
376 pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::ClosureKind {
377 self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
380 /// Extracts the signature from the closure; only usable outside
381 /// of an inference context, because in that context we know that
382 /// there are no type variables.
384 /// If you have an inference context, use `infcx.closure_sig()`.
385 pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
386 let ty = self.closure_sig_ty(def_id, tcx);
388 ty::FnPtr(sig) => sig,
389 _ => bug!("closure_sig_ty is not a fn-ptr: {:?}", ty.sty),
394 /// Similar to `ClosureSubsts`; see the above documentation for more.
395 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug,
396 RustcEncodable, RustcDecodable, HashStable)]
397 pub struct GeneratorSubsts<'tcx> {
398 pub substs: SubstsRef<'tcx>,
401 struct SplitGeneratorSubsts<'tcx> {
405 upvar_kinds: &'tcx [Kind<'tcx>],
408 impl<'tcx> GeneratorSubsts<'tcx> {
409 fn split(self, def_id: DefId, tcx: TyCtxt<'_>) -> SplitGeneratorSubsts<'tcx> {
410 let generics = tcx.generics_of(def_id);
411 let parent_len = generics.parent_count;
412 SplitGeneratorSubsts {
413 yield_ty: self.substs.type_at(parent_len),
414 return_ty: self.substs.type_at(parent_len + 1),
415 witness: self.substs.type_at(parent_len + 2),
416 upvar_kinds: &self.substs[parent_len + 3..],
420 /// This describes the types that can be contained in a generator.
421 /// It will be a type variable initially and unified in the last stages of typeck of a body.
422 /// It contains a tuple of all the types that could end up on a generator frame.
423 /// The state transformation MIR pass may only produce layouts which mention types
424 /// in this tuple. Upvars are not counted here.
425 pub fn witness(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
426 self.split(def_id, tcx).witness
434 ) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
435 let SplitGeneratorSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
436 upvar_kinds.iter().map(|t| {
437 if let UnpackedKind::Type(ty) = t.unpack() {
440 bug!("upvar should be type")
445 /// Returns the type representing the yield type of the generator.
446 pub fn yield_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
447 self.split(def_id, tcx).yield_ty
450 /// Returns the type representing the return type of the generator.
451 pub fn return_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
452 self.split(def_id, tcx).return_ty
455 /// Returns the "generator signature", which consists of its yield
456 /// and return types.
458 /// N.B., some bits of the code prefers to see this wrapped in a
459 /// binder, but it never contains bound regions. Probably this
460 /// function should be removed.
461 pub fn poly_sig(self, def_id: DefId, tcx: TyCtxt<'_>) -> PolyGenSig<'tcx> {
462 ty::Binder::dummy(self.sig(def_id, tcx))
465 /// Returns the "generator signature", which consists of its yield
466 /// and return types.
467 pub fn sig(self, def_id: DefId, tcx: TyCtxt<'_>) -> GenSig<'tcx> {
469 yield_ty: self.yield_ty(def_id, tcx),
470 return_ty: self.return_ty(def_id, tcx),
475 impl<'tcx> GeneratorSubsts<'tcx> {
476 /// Generator have not been resumed yet
477 pub const UNRESUMED: usize = 0;
478 /// Generator has returned / is completed
479 pub const RETURNED: usize = 1;
480 /// Generator has been poisoned
481 pub const POISONED: usize = 2;
483 const UNRESUMED_NAME: &'static str = "Unresumed";
484 const RETURNED_NAME: &'static str = "Returned";
485 const POISONED_NAME: &'static str = "Panicked";
487 /// The valid variant indices of this Generator.
489 pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
490 // FIXME requires optimized MIR
491 let num_variants = tcx.generator_layout(def_id).variant_fields.len();
492 (VariantIdx::new(0)..VariantIdx::new(num_variants))
495 /// The discriminant for the given variant. Panics if the variant_index is
498 pub fn discriminant_for_variant(
502 variant_index: VariantIdx,
504 // Generators don't support explicit discriminant values, so they are
505 // the same as the variant index.
506 assert!(self.variant_range(def_id, tcx).contains(&variant_index));
507 Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
510 /// The set of all discriminants for the Generator, enumerated with their
513 pub fn discriminants(
517 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
518 self.variant_range(def_id, tcx).map(move |index| {
519 (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
523 /// Calls `f` with a reference to the name of the enumerator for the given
526 pub fn variant_name(&self, v: VariantIdx) -> Cow<'static, str> {
528 Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
529 Self::RETURNED => Cow::from(Self::RETURNED_NAME),
530 Self::POISONED => Cow::from(Self::POISONED_NAME),
531 _ => Cow::from(format!("Suspend{}", v.as_usize() - 3))
535 /// The type of the state discriminant used in the generator type.
537 pub fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
541 /// This returns the types of the MIR locals which had to be stored across suspension points.
542 /// It is calculated in rustc_mir::transform::generator::StateTransform.
543 /// All the types here must be in the tuple in GeneratorInterior.
545 /// The locals are grouped by their variant number. Note that some locals may
546 /// be repeated in multiple variants.
552 ) -> impl Iterator<Item = impl Iterator<Item = Ty<'tcx>> + Captures<'tcx>> {
553 let layout = tcx.generator_layout(def_id);
554 layout.variant_fields.iter().map(move |variant| {
555 variant.iter().map(move |field| {
556 layout.field_tys[*field].subst(tcx, self.substs)
561 /// This is the types of the fields of a generator which are not stored in a
564 pub fn prefix_tys(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> impl Iterator<Item = Ty<'tcx>> {
565 self.upvar_tys(def_id, tcx)
569 #[derive(Debug, Copy, Clone)]
570 pub enum UpvarSubsts<'tcx> {
571 Closure(ClosureSubsts<'tcx>),
572 Generator(GeneratorSubsts<'tcx>),
575 impl<'tcx> UpvarSubsts<'tcx> {
581 ) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
582 let upvar_kinds = match self {
583 UpvarSubsts::Closure(substs) => substs.split(def_id, tcx).upvar_kinds,
584 UpvarSubsts::Generator(substs) => substs.split(def_id, tcx).upvar_kinds,
586 upvar_kinds.iter().map(|t| {
587 if let UnpackedKind::Type(ty) = t.unpack() {
590 bug!("upvar should be type")
596 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash,
597 RustcEncodable, RustcDecodable, HashStable)]
598 pub enum ExistentialPredicate<'tcx> {
599 /// E.g., `Iterator`.
600 Trait(ExistentialTraitRef<'tcx>),
601 /// E.g., `Iterator::Item = T`.
602 Projection(ExistentialProjection<'tcx>),
607 impl<'tcx> ExistentialPredicate<'tcx> {
608 /// Compares via an ordering that will not change if modules are reordered or other changes are
609 /// made to the tree. In particular, this ordering is preserved across incremental compilations.
610 pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering {
611 use self::ExistentialPredicate::*;
612 match (*self, *other) {
613 (Trait(_), Trait(_)) => Ordering::Equal,
614 (Projection(ref a), Projection(ref b)) =>
615 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
616 (AutoTrait(ref a), AutoTrait(ref b)) =>
617 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
618 (Trait(_), _) => Ordering::Less,
619 (Projection(_), Trait(_)) => Ordering::Greater,
620 (Projection(_), _) => Ordering::Less,
621 (AutoTrait(_), _) => Ordering::Greater,
626 impl<'tcx> Binder<ExistentialPredicate<'tcx>> {
627 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> {
628 use crate::ty::ToPredicate;
629 match *self.skip_binder() {
630 ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
631 ExistentialPredicate::Projection(p) =>
632 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
633 ExistentialPredicate::AutoTrait(did) => {
634 let trait_ref = Binder(ty::TraitRef {
636 substs: tcx.mk_substs_trait(self_ty, &[]),
638 trait_ref.to_predicate()
644 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<ExistentialPredicate<'tcx>> {}
646 impl<'tcx> List<ExistentialPredicate<'tcx>> {
647 /// Returns the "principal def id" of this set of existential predicates.
649 /// A Rust trait object type consists (in addition to a lifetime bound)
650 /// of a set of trait bounds, which are separated into any number
651 /// of auto-trait bounds, and at most one non-auto-trait bound. The
652 /// non-auto-trait bound is called the "principal" of the trait
655 /// Only the principal can have methods or type parameters (because
656 /// auto traits can have neither of them). This is important, because
657 /// it means the auto traits can be treated as an unordered set (methods
658 /// would force an order for the vtable, while relating traits with
659 /// type parameters without knowing the order to relate them in is
660 /// a rather non-trivial task).
662 /// For example, in the trait object `dyn fmt::Debug + Sync`, the
663 /// principal bound is `Some(fmt::Debug)`, while the auto-trait bounds
664 /// are the set `{Sync}`.
666 /// It is also possible to have a "trivial" trait object that
667 /// consists only of auto traits, with no principal - for example,
668 /// `dyn Send + Sync`. In that case, the set of auto-trait bounds
669 /// is `{Send, Sync}`, while there is no principal. These trait objects
670 /// have a "trivial" vtable consisting of just the size, alignment,
672 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
674 ExistentialPredicate::Trait(tr) => Some(tr),
679 pub fn principal_def_id(&self) -> Option<DefId> {
680 self.principal().map(|d| d.def_id)
684 pub fn projection_bounds<'a>(&'a self) ->
685 impl Iterator<Item = ExistentialProjection<'tcx>> + 'a
687 self.iter().filter_map(|predicate| {
689 ExistentialPredicate::Projection(p) => Some(p),
696 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item = DefId> + 'a {
697 self.iter().filter_map(|predicate| {
699 ExistentialPredicate::AutoTrait(d) => Some(d),
706 impl<'tcx> Binder<&'tcx List<ExistentialPredicate<'tcx>>> {
707 pub fn principal(&self) -> Option<ty::Binder<ExistentialTraitRef<'tcx>>> {
708 self.skip_binder().principal().map(Binder::bind)
711 pub fn principal_def_id(&self) -> Option<DefId> {
712 self.skip_binder().principal_def_id()
716 pub fn projection_bounds<'a>(&'a self) ->
717 impl Iterator<Item = PolyExistentialProjection<'tcx>> + 'a {
718 self.skip_binder().projection_bounds().map(Binder::bind)
722 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item = DefId> + 'a {
723 self.skip_binder().auto_traits()
726 pub fn iter<'a>(&'a self)
727 -> impl DoubleEndedIterator<Item = Binder<ExistentialPredicate<'tcx>>> + 'tcx {
728 self.skip_binder().iter().cloned().map(Binder::bind)
732 /// A complete reference to a trait. These take numerous guises in syntax,
733 /// but perhaps the most recognizable form is in a where-clause:
737 /// This would be represented by a trait-reference where the `DefId` is the
738 /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0,
739 /// and `U` as parameter 1.
741 /// Trait references also appear in object types like `Foo<U>`, but in
742 /// that case the `Self` parameter is absent from the substitutions.
744 /// Note that a `TraitRef` introduces a level of region binding, to
745 /// account for higher-ranked trait bounds like `T: for<'a> Foo<&'a U>`
746 /// or higher-ranked object types.
747 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
748 pub struct TraitRef<'tcx> {
750 pub substs: SubstsRef<'tcx>,
753 impl<'tcx> TraitRef<'tcx> {
754 pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> {
755 TraitRef { def_id: def_id, substs: substs }
758 /// Returns a `TraitRef` of the form `P0: Foo<P1..Pn>` where `Pi`
759 /// are the parameters defined on trait.
760 pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> TraitRef<'tcx> {
763 substs: InternalSubsts::identity_for_item(tcx, def_id),
768 pub fn self_ty(&self) -> Ty<'tcx> {
769 self.substs.type_at(0)
772 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
773 // Select only the "input types" from a trait-reference. For
774 // now this is all the types that appear in the
775 // trait-reference, but it should eventually exclude
783 substs: SubstsRef<'tcx>,
784 ) -> ty::TraitRef<'tcx> {
785 let defs = tcx.generics_of(trait_id);
789 substs: tcx.intern_substs(&substs[..defs.params.len()])
794 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
796 impl<'tcx> PolyTraitRef<'tcx> {
797 pub fn self_ty(&self) -> Ty<'tcx> {
798 self.skip_binder().self_ty()
801 pub fn def_id(&self) -> DefId {
802 self.skip_binder().def_id
805 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
806 // Note that we preserve binding levels
807 Binder(ty::TraitPredicate { trait_ref: self.skip_binder().clone() })
811 /// An existential reference to a trait, where `Self` is erased.
812 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
814 /// exists T. T: Trait<'a, 'b, X, Y>
816 /// The substitutions don't include the erased `Self`, only trait
817 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
818 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
819 RustcEncodable, RustcDecodable, HashStable)]
820 pub struct ExistentialTraitRef<'tcx> {
822 pub substs: SubstsRef<'tcx>,
825 impl<'tcx> ExistentialTraitRef<'tcx> {
826 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
827 // Select only the "input types" from a trait-reference. For
828 // now this is all the types that appear in the
829 // trait-reference, but it should eventually exclude
834 pub fn erase_self_ty(
836 trait_ref: ty::TraitRef<'tcx>,
837 ) -> ty::ExistentialTraitRef<'tcx> {
838 // Assert there is a Self.
839 trait_ref.substs.type_at(0);
841 ty::ExistentialTraitRef {
842 def_id: trait_ref.def_id,
843 substs: tcx.intern_substs(&trait_ref.substs[1..])
847 /// Object types don't have a self type specified. Therefore, when
848 /// we convert the principal trait-ref into a normal trait-ref,
849 /// you must give *some* self type. A common choice is `mk_err()`
850 /// or some placeholder type.
851 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> {
852 // otherwise the escaping vars would be captured by the binder
853 // debug_assert!(!self_ty.has_escaping_bound_vars());
857 substs: tcx.mk_substs_trait(self_ty, self.substs)
862 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
864 impl<'tcx> PolyExistentialTraitRef<'tcx> {
865 pub fn def_id(&self) -> DefId {
866 self.skip_binder().def_id
869 /// Object types don't have a self type specified. Therefore, when
870 /// we convert the principal trait-ref into a normal trait-ref,
871 /// you must give *some* self type. A common choice is `mk_err()`
872 /// or some placeholder type.
873 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> {
874 self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
878 /// Binder is a binder for higher-ranked lifetimes or types. It is part of the
879 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
880 /// (which would be represented by the type `PolyTraitRef ==
881 /// Binder<TraitRef>`). Note that when we instantiate,
882 /// erase, or otherwise "discharge" these bound vars, we change the
883 /// type from `Binder<T>` to just `T` (see
884 /// e.g., `liberate_late_bound_regions`).
885 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
886 pub struct Binder<T>(T);
889 /// Wraps `value` in a binder, asserting that `value` does not
890 /// contain any bound vars that would be bound by the
891 /// binder. This is commonly used to 'inject' a value T into a
892 /// different binding level.
893 pub fn dummy<'tcx>(value: T) -> Binder<T>
894 where T: TypeFoldable<'tcx>
896 debug_assert!(!value.has_escaping_bound_vars());
900 /// Wraps `value` in a binder, binding higher-ranked vars (if any).
901 pub fn bind(value: T) -> Binder<T> {
905 /// Skips the binder and returns the "bound" value. This is a
906 /// risky thing to do because it's easy to get confused about
907 /// De Bruijn indices and the like. It is usually better to
908 /// discharge the binder using `no_bound_vars` or
909 /// `replace_late_bound_regions` or something like
910 /// that. `skip_binder` is only valid when you are either
911 /// extracting data that has nothing to do with bound vars, you
912 /// are doing some sort of test that does not involve bound
913 /// regions, or you are being very careful about your depth
916 /// Some examples where `skip_binder` is reasonable:
918 /// - extracting the `DefId` from a PolyTraitRef;
919 /// - comparing the self type of a PolyTraitRef to see if it is equal to
920 /// a type parameter `X`, since the type `X` does not reference any regions
921 pub fn skip_binder(&self) -> &T {
925 pub fn as_ref(&self) -> Binder<&T> {
929 pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
930 where F: FnOnce(&T) -> U
932 self.as_ref().map_bound(f)
935 pub fn map_bound<F, U>(self, f: F) -> Binder<U>
936 where F: FnOnce(T) -> U
941 /// Unwraps and returns the value within, but only if it contains
942 /// no bound vars at all. (In other words, if this binder --
943 /// and indeed any enclosing binder -- doesn't bind anything at
944 /// all.) Otherwise, returns `None`.
946 /// (One could imagine having a method that just unwraps a single
947 /// binder, but permits late-bound vars bound by enclosing
948 /// binders, but that would require adjusting the debruijn
949 /// indices, and given the shallow binding structure we often use,
950 /// would not be that useful.)
951 pub fn no_bound_vars<'tcx>(self) -> Option<T>
952 where T: TypeFoldable<'tcx>
954 if self.skip_binder().has_escaping_bound_vars() {
957 Some(self.skip_binder().clone())
961 /// Given two things that have the same binder level,
962 /// and an operation that wraps on their contents, executes the operation
963 /// and then wraps its result.
965 /// `f` should consider bound regions at depth 1 to be free, and
966 /// anything it produces with bound regions at depth 1 will be
967 /// bound in the resulting return value.
968 pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
969 where F: FnOnce(T, U) -> R
971 Binder(f(self.0, u.0))
974 /// Splits the contents into two things that share the same binder
975 /// level as the original, returning two distinct binders.
977 /// `f` should consider bound regions at depth 1 to be free, and
978 /// anything it produces with bound regions at depth 1 will be
979 /// bound in the resulting return values.
980 pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
981 where F: FnOnce(T) -> (U, V)
983 let (u, v) = f(self.0);
984 (Binder(u), Binder(v))
988 /// Represents the projection of an associated type. In explicit UFCS
989 /// form this would be written `<T as Trait<..>>::N`.
990 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord,
991 Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
992 pub struct ProjectionTy<'tcx> {
993 /// The parameters of the associated item.
994 pub substs: SubstsRef<'tcx>,
996 /// The `DefId` of the `TraitItem` for the associated type `N`.
998 /// Note that this is not the `DefId` of the `TraitRef` containing this
999 /// associated type, which is in `tcx.associated_item(item_def_id).container`.
1000 pub item_def_id: DefId,
1003 impl<'tcx> ProjectionTy<'tcx> {
1004 /// Construct a `ProjectionTy` by searching the trait from `trait_ref` for the
1005 /// associated item named `item_name`.
1006 pub fn from_ref_and_name(
1008 trait_ref: ty::TraitRef<'tcx>,
1010 ) -> ProjectionTy<'tcx> {
1011 let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
1012 item.kind == ty::AssocKind::Type &&
1013 tcx.hygienic_eq(item_name, item.ident, trait_ref.def_id)
1017 substs: trait_ref.substs,
1022 /// Extracts the underlying trait reference from this projection.
1023 /// For example, if this is a projection of `<T as Iterator>::Item`,
1024 /// then this function would return a `T: Iterator` trait reference.
1025 pub fn trait_ref(&self, tcx: TyCtxt<'_>) -> ty::TraitRef<'tcx> {
1026 let def_id = tcx.associated_item(self.item_def_id).container.id();
1029 substs: self.substs,
1033 pub fn self_ty(&self) -> Ty<'tcx> {
1034 self.substs.type_at(0)
1038 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
1039 pub struct GenSig<'tcx> {
1040 pub yield_ty: Ty<'tcx>,
1041 pub return_ty: Ty<'tcx>,
1044 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
1046 impl<'tcx> PolyGenSig<'tcx> {
1047 pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
1048 self.map_bound_ref(|sig| sig.yield_ty)
1050 pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
1051 self.map_bound_ref(|sig| sig.return_ty)
1055 /// Signature of a function type, which I have arbitrarily
1056 /// decided to use to refer to the input/output types.
1058 /// - `inputs`: is the list of arguments and their modes.
1059 /// - `output`: is the return type.
1060 /// - `c_variadic`: indicates whether this is a C-variadic function.
1061 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord,
1062 Hash, RustcEncodable, RustcDecodable, HashStable)]
1063 pub struct FnSig<'tcx> {
1064 pub inputs_and_output: &'tcx List<Ty<'tcx>>,
1065 pub c_variadic: bool,
1066 pub unsafety: hir::Unsafety,
1070 impl<'tcx> FnSig<'tcx> {
1071 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
1072 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
1075 pub fn output(&self) -> Ty<'tcx> {
1076 self.inputs_and_output[self.inputs_and_output.len() - 1]
1079 // Create a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible method
1080 fn fake() -> FnSig<'tcx> {
1082 inputs_and_output: List::empty(),
1084 unsafety: hir::Unsafety::Normal,
1085 abi: abi::Abi::Rust,
1090 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1092 impl<'tcx> PolyFnSig<'tcx> {
1094 pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
1095 self.map_bound_ref(|fn_sig| fn_sig.inputs())
1098 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
1099 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
1101 pub fn inputs_and_output(&self) -> ty::Binder<&'tcx List<Ty<'tcx>>> {
1102 self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
1105 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
1106 self.map_bound_ref(|fn_sig| fn_sig.output())
1108 pub fn c_variadic(&self) -> bool {
1109 self.skip_binder().c_variadic
1111 pub fn unsafety(&self) -> hir::Unsafety {
1112 self.skip_binder().unsafety
1114 pub fn abi(&self) -> abi::Abi {
1115 self.skip_binder().abi
1119 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<FnSig<'tcx>>>;
1122 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
1123 Hash, RustcEncodable, RustcDecodable, HashStable)]
1124 pub struct ParamTy {
1126 pub name: InternedString,
1129 impl<'tcx> ParamTy {
1130 pub fn new(index: u32, name: InternedString) -> ParamTy {
1131 ParamTy { index, name: name }
1134 pub fn for_self() -> ParamTy {
1135 ParamTy::new(0, kw::SelfUpper.as_interned_str())
1138 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1139 ParamTy::new(def.index, def.name)
1142 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1143 tcx.mk_ty_param(self.index, self.name)
1147 #[derive(Copy, Clone, Hash, RustcEncodable, RustcDecodable,
1148 Eq, PartialEq, Ord, PartialOrd, HashStable)]
1149 pub struct ParamConst {
1151 pub name: InternedString,
1154 impl<'tcx> ParamConst {
1155 pub fn new(index: u32, name: InternedString) -> ParamConst {
1156 ParamConst { index, name }
1159 pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
1160 ParamConst::new(def.index, def.name)
1163 pub fn to_const(self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
1164 tcx.mk_const_param(self.index, self.name, ty)
1169 /// A [De Bruijn index][dbi] is a standard means of representing
1170 /// regions (and perhaps later types) in a higher-ranked setting. In
1171 /// particular, imagine a type like this:
1173 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1176 /// | +------------+ 0 | |
1178 /// +--------------------------------+ 1 |
1180 /// +------------------------------------------+ 0
1182 /// In this type, there are two binders (the outer fn and the inner
1183 /// fn). We need to be able to determine, for any given region, which
1184 /// fn type it is bound by, the inner or the outer one. There are
1185 /// various ways you can do this, but a De Bruijn index is one of the
1186 /// more convenient and has some nice properties. The basic idea is to
1187 /// count the number of binders, inside out. Some examples should help
1188 /// clarify what I mean.
1190 /// Let's start with the reference type `&'b isize` that is the first
1191 /// argument to the inner function. This region `'b` is assigned a De
1192 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
1193 /// fn). The region `'a` that appears in the second argument type (`&'a
1194 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
1195 /// second-innermost binder". (These indices are written on the arrays
1196 /// in the diagram).
1198 /// What is interesting is that De Bruijn index attached to a particular
1199 /// variable will vary depending on where it appears. For example,
1200 /// the final type `&'a char` also refers to the region `'a` declared on
1201 /// the outermost fn. But this time, this reference is not nested within
1202 /// any other binders (i.e., it is not an argument to the inner fn, but
1203 /// rather the outer one). Therefore, in this case, it is assigned a
1204 /// De Bruijn index of 0, because the innermost binder in that location
1205 /// is the outer fn.
1207 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1208 pub struct DebruijnIndex {
1209 DEBUG_FORMAT = "DebruijnIndex({})",
1210 const INNERMOST = 0,
1214 pub type Region<'tcx> = &'tcx RegionKind;
1216 /// Representation of regions.
1218 /// Unlike types, most region variants are "fictitious", not concrete,
1219 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1220 /// ones representing concrete regions.
1222 /// ## Bound Regions
1224 /// These are regions that are stored behind a binder and must be substituted
1225 /// with some concrete region before being used. There are two kind of
1226 /// bound regions: early-bound, which are bound in an item's `Generics`,
1227 /// and are substituted by a `InternalSubsts`, and late-bound, which are part of
1228 /// higher-ranked types (e.g., `for<'a> fn(&'a ())`), and are substituted by
1229 /// the likes of `liberate_late_bound_regions`. The distinction exists
1230 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1232 /// Unlike `Param`s, bound regions are not supposed to exist "in the wild"
1233 /// outside their binder, e.g., in types passed to type inference, and
1234 /// should first be substituted (by placeholder regions, free regions,
1235 /// or region variables).
1237 /// ## Placeholder and Free Regions
1239 /// One often wants to work with bound regions without knowing their precise
1240 /// identity. For example, when checking a function, the lifetime of a borrow
1241 /// can end up being assigned to some region parameter. In these cases,
1242 /// it must be ensured that bounds on the region can't be accidentally
1243 /// assumed without being checked.
1245 /// To do this, we replace the bound regions with placeholder markers,
1246 /// which don't satisfy any relation not explicitly provided.
1248 /// There are two kinds of placeholder regions in rustc: `ReFree` and
1249 /// `RePlaceholder`. When checking an item's body, `ReFree` is supposed
1250 /// to be used. These also support explicit bounds: both the internally-stored
1251 /// *scope*, which the region is assumed to outlive, as well as other
1252 /// relations stored in the `FreeRegionMap`. Note that these relations
1253 /// aren't checked when you `make_subregion` (or `eq_types`), only by
1254 /// `resolve_regions_and_report_errors`.
1256 /// When working with higher-ranked types, some region relations aren't
1257 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1258 /// `RePlaceholder` is designed for this purpose. In these contexts,
1259 /// there's also the risk that some inference variable laying around will
1260 /// get unified with your placeholder region: if you want to check whether
1261 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1262 /// with a placeholder region `'%a`, the variable `'_` would just be
1263 /// instantiated to the placeholder region `'%a`, which is wrong because
1264 /// the inference variable is supposed to satisfy the relation
1265 /// *for every value of the placeholder region*. To ensure that doesn't
1266 /// happen, you can use `leak_check`. This is more clearly explained
1267 /// by the [rustc guide].
1269 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1270 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1271 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/hrtb.html
1272 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1273 pub enum RegionKind {
1274 /// Region bound in a type or fn declaration which will be
1275 /// substituted 'early' -- that is, at the same time when type
1276 /// parameters are substituted.
1277 ReEarlyBound(EarlyBoundRegion),
1279 /// Region bound in a function scope, which will be substituted when the
1280 /// function is called.
1281 ReLateBound(DebruijnIndex, BoundRegion),
1283 /// When checking a function body, the types of all arguments and so forth
1284 /// that refer to bound region parameters are modified to refer to free
1285 /// region parameters.
1288 /// A concrete region naming some statically determined scope
1289 /// (e.g., an expression or sequence of statements) within the
1290 /// current function.
1291 ReScope(region::Scope),
1293 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1296 /// A region variable. Should not exist after typeck.
1299 /// A placeholder region - basically the higher-ranked version of ReFree.
1300 /// Should not exist after typeck.
1301 RePlaceholder(ty::PlaceholderRegion),
1303 /// Empty lifetime is for data that is never accessed.
1304 /// Bottom in the region lattice. We treat ReEmpty somewhat
1305 /// specially; at least right now, we do not generate instances of
1306 /// it during the GLB computations, but rather
1307 /// generate an error instead. This is to improve error messages.
1308 /// The only way to get an instance of ReEmpty is to have a region
1309 /// variable with no constraints.
1312 /// Erased region, used by trait selection, in MIR and during codegen.
1315 /// These are regions bound in the "defining type" for a
1316 /// closure. They are used ONLY as part of the
1317 /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1318 /// See `ClosureRegionRequirements` for more details.
1319 ReClosureBound(RegionVid),
1322 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Region<'tcx> {}
1324 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1325 pub struct EarlyBoundRegion {
1328 pub name: InternedString,
1331 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1336 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1337 pub struct ConstVid<'tcx> {
1339 pub phantom: PhantomData<&'tcx ()>,
1342 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1347 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1348 pub struct FloatVid {
1353 pub struct RegionVid {
1354 DEBUG_FORMAT = custom,
1358 impl Atom for RegionVid {
1359 fn index(self) -> usize {
1364 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
1365 Hash, RustcEncodable, RustcDecodable, HashStable)]
1371 /// A `FreshTy` is one that is generated as a replacement for an
1372 /// unbound type variable. This is convenient for caching etc. See
1373 /// `infer::freshen` for more details.
1380 pub struct BoundVar { .. }
1383 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1384 pub struct BoundTy {
1386 pub kind: BoundTyKind,
1389 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1390 pub enum BoundTyKind {
1392 Param(InternedString),
1395 impl_stable_hash_for!(struct BoundTy { var, kind });
1396 impl_stable_hash_for!(enum self::BoundTyKind { Anon, Param(a) });
1398 impl From<BoundVar> for BoundTy {
1399 fn from(var: BoundVar) -> Self {
1402 kind: BoundTyKind::Anon,
1407 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1408 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash,
1409 Debug, RustcEncodable, RustcDecodable, HashStable)]
1410 pub struct ExistentialProjection<'tcx> {
1411 pub item_def_id: DefId,
1412 pub substs: SubstsRef<'tcx>,
1416 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1418 impl<'tcx> ExistentialProjection<'tcx> {
1419 /// Extracts the underlying existential trait reference from this projection.
1420 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1421 /// then this function would return a `exists T. T: Iterator` existential trait
1423 pub fn trait_ref(&self, tcx: TyCtxt<'_>) -> ty::ExistentialTraitRef<'tcx> {
1424 let def_id = tcx.associated_item(self.item_def_id).container.id();
1425 ty::ExistentialTraitRef{
1427 substs: self.substs,
1431 pub fn with_self_ty(
1435 ) -> ty::ProjectionPredicate<'tcx> {
1436 // otherwise the escaping regions would be captured by the binders
1437 debug_assert!(!self_ty.has_escaping_bound_vars());
1439 ty::ProjectionPredicate {
1440 projection_ty: ty::ProjectionTy {
1441 item_def_id: self.item_def_id,
1442 substs: tcx.mk_substs_trait(self_ty, self.substs),
1449 impl<'tcx> PolyExistentialProjection<'tcx> {
1450 pub fn with_self_ty(
1454 ) -> ty::PolyProjectionPredicate<'tcx> {
1455 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1458 pub fn item_def_id(&self) -> DefId {
1459 return self.skip_binder().item_def_id;
1463 impl DebruijnIndex {
1464 /// Returns the resulting index when this value is moved into
1465 /// `amount` number of new binders. So, e.g., if you had
1467 /// for<'a> fn(&'a x)
1469 /// and you wanted to change it to
1471 /// for<'a> fn(for<'b> fn(&'a x))
1473 /// you would need to shift the index for `'a` into a new binder.
1475 pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
1476 DebruijnIndex::from_u32(self.as_u32() + amount)
1479 /// Update this index in place by shifting it "in" through
1480 /// `amount` number of binders.
1481 pub fn shift_in(&mut self, amount: u32) {
1482 *self = self.shifted_in(amount);
1485 /// Returns the resulting index when this value is moved out from
1486 /// `amount` number of new binders.
1488 pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
1489 DebruijnIndex::from_u32(self.as_u32() - amount)
1492 /// Update in place by shifting out from `amount` binders.
1493 pub fn shift_out(&mut self, amount: u32) {
1494 *self = self.shifted_out(amount);
1497 /// Adjusts any De Bruijn indices so as to make `to_binder` the
1498 /// innermost binder. That is, if we have something bound at `to_binder`,
1499 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1500 /// when moving a region out from inside binders:
1503 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1504 /// // Binder: D3 D2 D1 ^^
1507 /// Here, the region `'a` would have the De Bruijn index D3,
1508 /// because it is the bound 3 binders out. However, if we wanted
1509 /// to refer to that region `'a` in the second argument (the `_`),
1510 /// those two binders would not be in scope. In that case, we
1511 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1512 /// De Bruijn index of `'a` to D1 (the innermost binder).
1514 /// If we invoke `shift_out_to_binder` and the region is in fact
1515 /// bound by one of the binders we are shifting out of, that is an
1516 /// error (and should fail an assertion failure).
1517 pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
1518 self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
1522 impl_stable_hash_for!(struct DebruijnIndex { private });
1524 /// Region utilities
1526 /// Is this region named by the user?
1527 pub fn has_name(&self) -> bool {
1529 RegionKind::ReEarlyBound(ebr) => ebr.has_name(),
1530 RegionKind::ReLateBound(_, br) => br.is_named(),
1531 RegionKind::ReFree(fr) => fr.bound_region.is_named(),
1532 RegionKind::ReScope(..) => false,
1533 RegionKind::ReStatic => true,
1534 RegionKind::ReVar(..) => false,
1535 RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(),
1536 RegionKind::ReEmpty => false,
1537 RegionKind::ReErased => false,
1538 RegionKind::ReClosureBound(..) => false,
1542 pub fn is_late_bound(&self) -> bool {
1544 ty::ReLateBound(..) => true,
1549 pub fn is_placeholder(&self) -> bool {
1551 ty::RePlaceholder(..) => true,
1556 pub fn bound_at_or_above_binder(&self, index: DebruijnIndex) -> bool {
1558 ty::ReLateBound(debruijn, _) => debruijn >= index,
1563 /// Adjusts any De Bruijn indices so as to make `to_binder` the
1564 /// innermost binder. That is, if we have something bound at `to_binder`,
1565 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1566 /// when moving a region out from inside binders:
1569 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1570 /// // Binder: D3 D2 D1 ^^
1573 /// Here, the region `'a` would have the De Bruijn index D3,
1574 /// because it is the bound 3 binders out. However, if we wanted
1575 /// to refer to that region `'a` in the second argument (the `_`),
1576 /// those two binders would not be in scope. In that case, we
1577 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1578 /// De Bruijn index of `'a` to D1 (the innermost binder).
1580 /// If we invoke `shift_out_to_binder` and the region is in fact
1581 /// bound by one of the binders we are shifting out of, that is an
1582 /// error (and should fail an assertion failure).
1583 pub fn shifted_out_to_binder(&self, to_binder: ty::DebruijnIndex) -> RegionKind {
1585 ty::ReLateBound(debruijn, r) => ty::ReLateBound(
1586 debruijn.shifted_out_to_binder(to_binder),
1593 pub fn keep_in_local_tcx(&self) -> bool {
1594 if let ty::ReVar(..) = self {
1601 pub fn type_flags(&self) -> TypeFlags {
1602 let mut flags = TypeFlags::empty();
1604 if self.keep_in_local_tcx() {
1605 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1610 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1611 flags = flags | TypeFlags::HAS_RE_INFER;
1613 ty::RePlaceholder(..) => {
1614 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1615 flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
1617 ty::ReLateBound(..) => {
1618 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1620 ty::ReEarlyBound(..) => {
1621 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1622 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1627 ty::ReScope { .. } => {
1628 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1632 ty::ReClosureBound(..) => {
1633 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1638 ty::ReStatic | ty::ReEmpty | ty::ReErased | ty::ReLateBound(..) => (),
1639 _ => flags = flags | TypeFlags::HAS_FREE_LOCAL_NAMES,
1642 debug!("type_flags({:?}) = {:?}", self, flags);
1647 /// Given an early-bound or free region, returns the `DefId` where it was bound.
1648 /// For example, consider the regions in this snippet of code:
1652 /// ^^ -- early bound, declared on an impl
1654 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1655 /// ^^ ^^ ^ anonymous, late-bound
1656 /// | early-bound, appears in where-clauses
1657 /// late-bound, appears only in fn args
1662 /// Here, `free_region_binding_scope('a)` would return the `DefId`
1663 /// of the impl, and for all the other highlighted regions, it
1664 /// would return the `DefId` of the function. In other cases (not shown), this
1665 /// function might return the `DefId` of a closure.
1666 pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_>) -> DefId {
1668 ty::ReEarlyBound(br) => {
1669 tcx.parent(br.def_id).unwrap()
1671 ty::ReFree(fr) => fr.scope,
1672 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1678 impl<'tcx> TyS<'tcx> {
1680 pub fn is_unit(&self) -> bool {
1682 Tuple(ref tys) => tys.is_empty(),
1688 pub fn is_never(&self) -> bool {
1695 /// Checks whether a type is definitely uninhabited. This is
1696 /// conservative: for some types that are uninhabited we return `false`,
1697 /// but we only return `true` for types that are definitely uninhabited.
1698 /// `ty.conservative_is_privately_uninhabited` implies that any value of type `ty`
1699 /// will be `Abi::Uninhabited`. (Note that uninhabited types may have nonzero
1700 /// size, to account for partial initialisation. See #49298 for details.)
1701 pub fn conservative_is_privately_uninhabited(&self, tcx: TyCtxt<'tcx>) -> bool {
1702 // FIXME(varkor): we can make this less conversative by substituting concrete
1706 ty::Adt(def, _) if def.is_union() => {
1707 // For now, `union`s are never considered uninhabited.
1710 ty::Adt(def, _) => {
1711 // Any ADT is uninhabited if either:
1712 // (a) It has no variants (i.e. an empty `enum`);
1713 // (b) Each of its variants (a single one in the case of a `struct`) has at least
1714 // one uninhabited field.
1715 def.variants.iter().all(|var| {
1716 var.fields.iter().any(|field| {
1717 tcx.type_of(field.did).conservative_is_privately_uninhabited(tcx)
1721 ty::Tuple(..) => self.tuple_fields().any(|ty| {
1722 ty.conservative_is_privately_uninhabited(tcx)
1724 ty::Array(ty, len) => {
1725 match len.try_eval_usize(tcx, ParamEnv::empty()) {
1726 // If the array is definitely non-empty, it's uninhabited if
1727 // the type of its elements is uninhabited.
1728 Some(n) if n != 0 => ty.conservative_is_privately_uninhabited(tcx),
1733 // References to uninitialised memory is valid for any type, including
1734 // uninhabited types, in unsafe code, so we treat all references as
1743 pub fn is_primitive(&self) -> bool {
1745 Bool | Char | Int(_) | Uint(_) | Float(_) => true,
1751 pub fn is_ty_var(&self) -> bool {
1753 Infer(TyVar(_)) => true,
1759 pub fn is_ty_infer(&self) -> bool {
1767 pub fn is_phantom_data(&self) -> bool {
1768 if let Adt(def, _) = self.sty {
1769 def.is_phantom_data()
1776 pub fn is_bool(&self) -> bool { self.sty == Bool }
1779 pub fn is_param(&self, index: u32) -> bool {
1781 ty::Param(ref data) => data.index == index,
1787 pub fn is_slice(&self) -> bool {
1789 RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => match ty.sty {
1790 Slice(_) | Str => true,
1798 pub fn is_simd(&self) -> bool {
1800 Adt(def, _) => def.repr.simd(),
1805 pub fn sequence_element_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1807 Array(ty, _) | Slice(ty) => ty,
1808 Str => tcx.mk_mach_uint(ast::UintTy::U8),
1809 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1813 pub fn simd_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1815 Adt(def, substs) => {
1816 def.non_enum_variant().fields[0].ty(tcx, substs)
1818 _ => bug!("simd_type called on invalid type")
1822 pub fn simd_size(&self, _cx: TyCtxt<'_>) -> usize {
1824 Adt(def, _) => def.non_enum_variant().fields.len(),
1825 _ => bug!("simd_size called on invalid type")
1830 pub fn is_region_ptr(&self) -> bool {
1838 pub fn is_mutable_ptr(&self) -> bool {
1840 RawPtr(TypeAndMut { mutbl: hir::Mutability::MutMutable, .. }) |
1841 Ref(_, _, hir::Mutability::MutMutable) => true,
1847 pub fn is_unsafe_ptr(&self) -> bool {
1849 RawPtr(_) => return true,
1854 /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1856 pub fn is_any_ptr(&self) -> bool {
1857 self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr()
1860 /// Returns `true` if this type is an `Arc<T>`.
1862 pub fn is_arc(&self) -> bool {
1864 Adt(def, _) => def.is_arc(),
1869 /// Returns `true` if this type is an `Rc<T>`.
1871 pub fn is_rc(&self) -> bool {
1873 Adt(def, _) => def.is_rc(),
1879 pub fn is_box(&self) -> bool {
1881 Adt(def, _) => def.is_box(),
1886 /// panics if called on any type other than `Box<T>`
1887 pub fn boxed_ty(&self) -> Ty<'tcx> {
1889 Adt(def, substs) if def.is_box() => substs.type_at(0),
1890 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1894 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1895 /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1896 /// contents are abstract to rustc.)
1898 pub fn is_scalar(&self) -> bool {
1900 Bool | Char | Int(_) | Float(_) | Uint(_) |
1901 Infer(IntVar(_)) | Infer(FloatVar(_)) |
1902 FnDef(..) | FnPtr(_) | RawPtr(_) => true,
1907 /// Returns `true` if this type is a floating point type.
1909 pub fn is_floating_point(&self) -> bool {
1912 Infer(FloatVar(_)) => true,
1918 pub fn is_trait(&self) -> bool {
1920 Dynamic(..) => true,
1926 pub fn is_enum(&self) -> bool {
1928 Adt(adt_def, _) => {
1936 pub fn is_closure(&self) -> bool {
1938 Closure(..) => true,
1944 pub fn is_generator(&self) -> bool {
1946 Generator(..) => true,
1952 pub fn is_integral(&self) -> bool {
1954 Infer(IntVar(_)) | Int(_) | Uint(_) => true,
1960 pub fn is_fresh_ty(&self) -> bool {
1962 Infer(FreshTy(_)) => true,
1968 pub fn is_fresh(&self) -> bool {
1970 Infer(FreshTy(_)) => true,
1971 Infer(FreshIntTy(_)) => true,
1972 Infer(FreshFloatTy(_)) => true,
1978 pub fn is_char(&self) -> bool {
1986 pub fn is_numeric(&self) -> bool {
1987 self.is_integral() || self.is_floating_point()
1991 pub fn is_signed(&self) -> bool {
1999 pub fn is_ptr_sized_integral(&self) -> bool {
2001 Int(ast::IntTy::Isize) | Uint(ast::UintTy::Usize) => true,
2007 pub fn is_machine(&self) -> bool {
2009 Int(..) | Uint(..) | Float(..) => true,
2015 pub fn has_concrete_skeleton(&self) -> bool {
2017 Param(_) | Infer(_) | Error => false,
2022 /// Returns the type and mutability of `*ty`.
2024 /// The parameter `explicit` indicates if this is an *explicit* dereference.
2025 /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
2026 pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
2028 Adt(def, _) if def.is_box() => {
2030 ty: self.boxed_ty(),
2031 mutbl: hir::MutImmutable,
2034 Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
2035 RawPtr(mt) if explicit => Some(mt),
2040 /// Returns the type of `ty[i]`.
2041 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
2043 Array(ty, _) | Slice(ty) => Some(ty),
2048 pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
2050 FnDef(def_id, substs) => {
2051 tcx.fn_sig(def_id).subst(tcx, substs)
2054 Error => { // ignore errors (#54954)
2055 ty::Binder::dummy(FnSig::fake())
2057 Closure(..) => bug!(
2058 "to get the signature of a closure, use `closure_sig()` not `fn_sig()`",
2060 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
2065 pub fn is_fn(&self) -> bool {
2067 FnDef(..) | FnPtr(_) => true,
2073 pub fn is_fn_ptr(&self) -> bool {
2081 pub fn is_impl_trait(&self) -> bool {
2089 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
2091 Adt(adt, _) => Some(adt),
2096 /// Iterates over tuple fields.
2097 /// Panics when called on anything but a tuple.
2098 pub fn tuple_fields(&self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> {
2100 Tuple(substs) => substs.iter().map(|field| field.expect_ty()),
2101 _ => bug!("tuple_fields called on non-tuple"),
2105 /// If the type contains variants, returns the valid range of variant indices.
2106 /// FIXME This requires the optimized MIR in the case of generators.
2108 pub fn variant_range(&self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
2110 TyKind::Adt(adt, _) => Some(adt.variant_range()),
2111 TyKind::Generator(def_id, substs, _) => Some(substs.variant_range(def_id, tcx)),
2116 /// If the type contains variants, returns the variant for `variant_index`.
2117 /// Panics if `variant_index` is out of range.
2118 /// FIXME This requires the optimized MIR in the case of generators.
2120 pub fn discriminant_for_variant(
2123 variant_index: VariantIdx,
2124 ) -> Option<Discr<'tcx>> {
2126 TyKind::Adt(adt, _) => Some(adt.discriminant_for_variant(tcx, variant_index)),
2127 TyKind::Generator(def_id, substs, _) =>
2128 Some(substs.discriminant_for_variant(def_id, tcx, variant_index)),
2133 /// Push onto `out` the regions directly referenced from this type (but not
2134 /// types reachable from this type via `walk_tys`). This ignores late-bound
2135 /// regions binders.
2136 pub fn push_regions(&self, out: &mut SmallVec<[ty::Region<'tcx>; 4]>) {
2138 Ref(region, _, _) => {
2141 Dynamic(ref obj, region) => {
2143 if let Some(principal) = obj.principal() {
2144 out.extend(principal.skip_binder().substs.regions());
2147 Adt(_, substs) | Opaque(_, substs) => {
2148 out.extend(substs.regions())
2150 Closure(_, ClosureSubsts { ref substs }) |
2151 Generator(_, GeneratorSubsts { ref substs }, _) => {
2152 out.extend(substs.regions())
2154 Projection(ref data) | UnnormalizedProjection(ref data) => {
2155 out.extend(data.substs.regions())
2159 GeneratorWitness(..) |
2180 /// When we create a closure, we record its kind (i.e., what trait
2181 /// it implements) into its `ClosureSubsts` using a type
2182 /// parameter. This is kind of a phantom type, except that the
2183 /// most convenient thing for us to are the integral types. This
2184 /// function converts such a special type into the closure
2185 /// kind. To go the other way, use
2186 /// `tcx.closure_kind_ty(closure_kind)`.
2188 /// Note that during type checking, we use an inference variable
2189 /// to represent the closure kind, because it has not yet been
2190 /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
2191 /// is complete, that type variable will be unified.
2192 pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
2194 Int(int_ty) => match int_ty {
2195 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
2196 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
2197 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
2198 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2203 Error => Some(ty::ClosureKind::Fn),
2205 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2209 /// Fast path helper for testing if a type is `Sized`.
2211 /// Returning true means the type is known to be sized. Returning
2212 /// `false` means nothing -- could be sized, might not be.
2213 pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool {
2215 ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
2216 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
2217 ty::FnDef(..) | ty::FnPtr(_) | ty::RawPtr(..) |
2218 ty::Char | ty::Ref(..) | ty::Generator(..) |
2219 ty::GeneratorWitness(..) | ty::Array(..) | ty::Closure(..) |
2220 ty::Never | ty::Error =>
2223 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) =>
2227 tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx))
2230 ty::Adt(def, _substs) =>
2231 def.sized_constraint(tcx).is_empty(),
2233 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
2235 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
2237 ty::Infer(ty::TyVar(_)) => false,
2240 ty::Placeholder(..) |
2241 ty::Infer(ty::FreshTy(_)) |
2242 ty::Infer(ty::FreshIntTy(_)) |
2243 ty::Infer(ty::FreshFloatTy(_)) =>
2244 bug!("is_trivially_sized applied to unexpected type: {:?}", self),
2249 /// Typed constant value.
2250 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable,
2251 Eq, PartialEq, Ord, PartialOrd, HashStable)]
2252 pub struct Const<'tcx> {
2255 pub val: ConstValue<'tcx>,
2258 #[cfg(target_arch = "x86_64")]
2259 static_assert_size!(Const<'_>, 40);
2261 impl<'tcx> Const<'tcx> {
2263 pub fn from_scalar(tcx: TyCtxt<'tcx>, val: Scalar, ty: Ty<'tcx>) -> &'tcx Self {
2265 val: ConstValue::Scalar(val),
2271 pub fn from_bits(tcx: TyCtxt<'tcx>, bits: u128, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> &'tcx Self {
2272 let size = tcx.layout_of(ty).unwrap_or_else(|e| {
2273 panic!("could not compute layout for {:?}: {:?}", ty, e)
2275 Self::from_scalar(tcx, Scalar::from_uint(bits, size), ty.value)
2279 pub fn zero_sized(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
2280 Self::from_scalar(tcx, Scalar::zst(), ty)
2284 pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> &'tcx Self {
2285 Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
2289 pub fn from_usize(tcx: TyCtxt<'tcx>, n: u64) -> &'tcx Self {
2290 Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
2294 pub fn try_eval_bits(
2297 param_env: ParamEnv<'tcx>,
2300 assert_eq!(self.ty, ty);
2301 // if `ty` does not depend on generic parameters, use an empty param_env
2302 let size = tcx.layout_of(param_env.with_reveal_all().and(ty)).ok()?.size;
2303 self.eval(tcx, param_env).val.try_to_bits(size)
2310 param_env: ParamEnv<'tcx>,
2312 // FIXME(const_generics): this doesn't work right now,
2313 // because it tries to relate an `Infer` to a `Param`.
2315 ConstValue::Unevaluated(did, substs) => {
2316 // if `substs` has no unresolved components, use and empty param_env
2317 let (param_env, substs) = param_env.with_reveal_all().and(substs).into_parts();
2318 // try to resolve e.g. associated constants to their definition on an impl
2319 let instance = match ty::Instance::resolve(tcx, param_env, did, substs) {
2320 Some(instance) => instance,
2321 None => return self,
2323 let gid = GlobalId {
2327 tcx.const_eval(param_env.and(gid)).unwrap_or(self)
2334 pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<bool> {
2335 self.try_eval_bits(tcx, param_env, tcx.types.bool).and_then(|v| match v {
2343 pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<u64> {
2344 self.try_eval_bits(tcx, param_env, tcx.types.usize).map(|v| v as u64)
2348 pub fn eval_bits(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: Ty<'tcx>) -> u128 {
2349 self.try_eval_bits(tcx, param_env, ty).unwrap_or_else(||
2350 bug!("expected bits of {:#?}, got {:#?}", ty, self))
2354 pub fn eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> u64 {
2355 self.eval_bits(tcx, param_env, tcx.types.usize) as u64
2359 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}
2361 /// An inference variable for a const, for use in const generics.
2362 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd,
2363 Ord, RustcEncodable, RustcDecodable, Hash, HashStable)]
2364 pub enum InferConst<'tcx> {
2365 /// Infer the value of the const.
2366 Var(ConstVid<'tcx>),
2367 /// A fresh const variable. See `infer::freshen` for more details.
2369 /// Canonicalized const variable, used only when preparing a trait query.
2370 Canonical(DebruijnIndex, BoundVar),