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_index::vec::Idx;
12 use rustc_macros::HashStable;
13 use crate::ty::subst::{InternalSubsts, Subst, SubstsRef, GenericArg, GenericArgKind};
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::{Size, Integer, IntegerExt, 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::attr::{SignedInt, UnsignedInt};
28 use syntax::symbol::{kw, InternedString};
33 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
34 Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
35 pub struct TypeAndMut<'tcx> {
37 pub mutbl: hir::Mutability,
40 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
41 RustcEncodable, RustcDecodable, Copy, HashStable)]
42 /// A "free" region `fr` can be interpreted as "some region
43 /// at least as big as the scope `fr.scope`".
44 pub struct FreeRegion {
46 pub bound_region: BoundRegion,
49 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
50 RustcEncodable, RustcDecodable, Copy, HashStable)]
51 pub enum BoundRegion {
52 /// An anonymous region parameter for a given fn (&T)
55 /// Named region parameters for functions (a in &'a T)
57 /// The `DefId` is needed to distinguish free regions in
58 /// the event of shadowing.
59 BrNamed(DefId, InternedString),
61 /// Anonymous region for the implicit env pointer parameter
67 pub fn is_named(&self) -> bool {
69 BoundRegion::BrNamed(..) => true,
74 /// When canonicalizing, we replace unbound inference variables and free
75 /// regions with anonymous late bound regions. This method asserts that
76 /// we have an anonymous late bound region, which hence may refer to
77 /// a canonical variable.
78 pub fn assert_bound_var(&self) -> BoundVar {
80 BoundRegion::BrAnon(var) => BoundVar::from_u32(var),
81 _ => bug!("bound region is not anonymous"),
86 /// N.B., if you change this, you'll probably want to change the corresponding
87 /// AST structure in `libsyntax/ast.rs` as well.
88 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
89 RustcEncodable, RustcDecodable, HashStable, Debug)]
90 #[rustc_diagnostic_item = "TyKind"]
91 pub enum TyKind<'tcx> {
92 /// The primitive boolean type. Written as `bool`.
95 /// The primitive character type; holds a Unicode scalar value
96 /// (a non-surrogate code point). Written as `char`.
99 /// A primitive signed integer type. For example, `i32`.
102 /// A primitive unsigned integer type. For example, `u32`.
105 /// A primitive floating-point type. For example, `f64`.
108 /// Structures, enumerations and unions.
110 /// InternalSubsts here, possibly against intuition, *may* contain `Param`s.
111 /// That is, even after substitution it is possible that there are type
112 /// variables. This happens when the `Adt` corresponds to an ADT
113 /// definition and not a concrete use of it.
114 Adt(&'tcx AdtDef, SubstsRef<'tcx>),
116 /// An unsized FFI type that is opaque to Rust. Written as `extern type T`.
119 /// The pointee of a string slice. Written as `str`.
122 /// An array with the given length. Written as `[T; n]`.
123 Array(Ty<'tcx>, &'tcx ty::Const<'tcx>),
125 /// The pointee of an array slice. Written as `[T]`.
128 /// A raw pointer. Written as `*mut T` or `*const T`
129 RawPtr(TypeAndMut<'tcx>),
131 /// A reference; a pointer with an associated lifetime. Written as
132 /// `&'a mut T` or `&'a T`.
133 Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability),
135 /// The anonymous type of a function declaration/definition. Each
136 /// function has a unique type, which is output (for a function
137 /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
139 /// For example the type of `bar` here:
142 /// fn foo() -> i32 { 1 }
143 /// let bar = foo; // bar: fn() -> i32 {foo}
145 FnDef(DefId, SubstsRef<'tcx>),
147 /// A pointer to a function. Written as `fn() -> i32`.
149 /// For example the type of `bar` here:
152 /// fn foo() -> i32 { 1 }
153 /// let bar: fn() -> i32 = foo;
155 FnPtr(PolyFnSig<'tcx>),
157 /// A trait, defined with `trait`.
158 Dynamic(Binder<&'tcx List<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
160 /// The anonymous type of a closure. Used to represent the type of
162 Closure(DefId, SubstsRef<'tcx>),
164 /// The anonymous type of a generator. Used to represent the type of
166 Generator(DefId, SubstsRef<'tcx>, hir::GeneratorMovability),
168 /// A type representin the types stored inside a generator.
169 /// This should only appear in GeneratorInteriors.
170 GeneratorWitness(Binder<&'tcx List<Ty<'tcx>>>),
172 /// The never type `!`
175 /// A tuple type. For example, `(i32, bool)`.
176 /// Use `TyS::tuple_fields` to iterate over the field types.
177 Tuple(SubstsRef<'tcx>),
179 /// The projection of an associated type. For example,
180 /// `<T as Trait<..>>::N`.
181 Projection(ProjectionTy<'tcx>),
183 /// A placeholder type used when we do not have enough information
184 /// to normalize the projection of an associated type to an
185 /// existing concrete type. Currently only used with chalk-engine.
186 UnnormalizedProjection(ProjectionTy<'tcx>),
188 /// Opaque (`impl Trait`) type found in a return type.
189 /// The `DefId` comes either from
190 /// * the `impl Trait` ast::Ty node,
191 /// * or the `type Foo = impl Trait` declaration
192 /// The substitutions are for the generics of the function in question.
193 /// After typeck, the concrete type can be found in the `types` map.
194 Opaque(DefId, SubstsRef<'tcx>),
196 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
199 /// Bound type variable, used only when preparing a trait query.
200 Bound(ty::DebruijnIndex, BoundTy),
202 /// A placeholder type - universally quantified higher-ranked type.
203 Placeholder(ty::PlaceholderType),
205 /// A type variable used during type checking.
208 /// A placeholder for a type which could not be computed; this is
209 /// propagated to avoid useless error messages.
213 // `TyKind` is used a lot. Make sure it doesn't unintentionally get bigger.
214 #[cfg(target_arch = "x86_64")]
215 static_assert_size!(TyKind<'_>, 24);
217 /// A closure can be modeled as a struct that looks like:
219 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
227 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
228 /// in scope on the function that defined the closure,
229 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
230 /// is rather hackily encoded via a scalar type. See
231 /// `TyS::to_opt_closure_kind` for details.
232 /// - CS represents the *closure signature*, representing as a `fn()`
233 /// type. For example, `fn(u32, u32) -> u32` would mean that the closure
234 /// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
236 /// - U0...Uk are type parameters representing the types of its upvars
237 /// (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
238 /// and the up-var has the type `Foo`, then `Ui = &Foo`).
240 /// So, for example, given this function:
242 /// fn foo<'a, T>(data: &'a mut T) {
243 /// do(|| data.count += 1)
246 /// the type of the closure would be something like:
248 /// struct Closure<'a, T, U0> {
252 /// Note that the type of the upvar is not specified in the struct.
253 /// You may wonder how the impl would then be able to use the upvar,
254 /// if it doesn't know it's type? The answer is that the impl is
255 /// (conceptually) not fully generic over Closure but rather tied to
256 /// instances with the expected upvar types:
258 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
262 /// You can see that the *impl* fully specified the type of the upvar
263 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
264 /// (Here, I am assuming that `data` is mut-borrowed.)
266 /// Now, the last question you may ask is: Why include the upvar types
267 /// as extra type parameters? The reason for this design is that the
268 /// upvar types can reference lifetimes that are internal to the
269 /// creating function. In my example above, for example, the lifetime
270 /// `'b` represents the scope of the closure itself; this is some
271 /// subset of `foo`, probably just the scope of the call to the to
272 /// `do()`. If we just had the lifetime/type parameters from the
273 /// enclosing function, we couldn't name this lifetime `'b`. Note that
274 /// there can also be lifetimes in the types of the upvars themselves,
275 /// if one of them happens to be a reference to something that the
276 /// creating fn owns.
278 /// OK, you say, so why not create a more minimal set of parameters
279 /// that just includes the extra lifetime parameters? The answer is
280 /// primarily that it would be hard --- we don't know at the time when
281 /// we create the closure type what the full types of the upvars are,
282 /// nor do we know which are borrowed and which are not. In this
283 /// design, we can just supply a fresh type parameter and figure that
286 /// All right, you say, but why include the type parameters from the
287 /// original function then? The answer is that codegen may need them
288 /// when monomorphizing, and they may not appear in the upvars. A
289 /// closure could capture no variables but still make use of some
290 /// in-scope type parameter with a bound (e.g., if our example above
291 /// had an extra `U: Default`, and the closure called `U::default()`).
293 /// There is another reason. This design (implicitly) prohibits
294 /// closures from capturing themselves (except via a trait
295 /// object). This simplifies closure inference considerably, since it
296 /// means that when we infer the kind of a closure or its upvars, we
297 /// don't have to handle cycles where the decisions we make for
298 /// closure C wind up influencing the decisions we ought to make for
299 /// closure C (which would then require fixed point iteration to
300 /// handle). Plus it fixes an ICE. :P
304 /// Generators are handled similarly in `GeneratorSubsts`. The set of
305 /// type parameters is similar, but the role of CK and CS are
306 /// different. CK represents the "yield type" and CS represents the
307 /// "return type" of the generator.
308 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug,
309 RustcEncodable, RustcDecodable, HashStable)]
310 pub struct ClosureSubsts<'tcx> {
311 /// Lifetime and type parameters from the enclosing function,
312 /// concatenated with the types of the upvars.
314 /// These are separated out because codegen wants to pass them around
315 /// when monomorphizing.
316 pub substs: SubstsRef<'tcx>,
319 /// Struct returned by `split()`. Note that these are subslices of the
320 /// parent slice and not canonical substs themselves.
321 struct SplitClosureSubsts<'tcx> {
322 closure_kind_ty: Ty<'tcx>,
323 closure_sig_ty: Ty<'tcx>,
324 upvar_kinds: &'tcx [GenericArg<'tcx>],
327 impl<'tcx> ClosureSubsts<'tcx> {
328 /// Divides the closure substs into their respective
329 /// components. Single source of truth with respect to the
331 fn split(self, def_id: DefId, tcx: TyCtxt<'_>) -> SplitClosureSubsts<'tcx> {
332 let generics = tcx.generics_of(def_id);
333 let parent_len = generics.parent_count;
335 closure_kind_ty: self.substs.type_at(parent_len),
336 closure_sig_ty: self.substs.type_at(parent_len + 1),
337 upvar_kinds: &self.substs[parent_len + 2..],
346 ) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
347 let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
348 upvar_kinds.iter().map(|t| {
349 if let GenericArgKind::Type(ty) = t.unpack() {
352 bug!("upvar should be type")
357 /// Returns the closure kind for this closure; may return a type
358 /// variable during inference. To get the closure kind during
359 /// inference, use `infcx.closure_kind(def_id, substs)`.
360 pub fn kind_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
361 self.split(def_id, tcx).closure_kind_ty
364 /// Returns the type representing the closure signature for this
365 /// closure; may contain type variables during inference. To get
366 /// the closure signature during inference, use
367 /// `infcx.fn_sig(def_id)`.
368 pub fn sig_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
369 self.split(def_id, tcx).closure_sig_ty
372 /// Returns the closure kind for this closure; only usable outside
373 /// of an inference context, because in that context we know that
374 /// there are no type variables.
376 /// If you have an inference context, use `infcx.closure_kind()`.
377 pub fn kind(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::ClosureKind {
378 self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
381 /// Extracts the signature from the closure; only usable outside
382 /// of an inference context, because in that context we know that
383 /// there are no type variables.
385 /// If you have an inference context, use `infcx.closure_sig()`.
386 pub fn sig(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
387 let ty = self.sig_ty(def_id, tcx);
389 ty::FnPtr(sig) => sig,
390 _ => bug!("closure_sig_ty is not a fn-ptr: {:?}", ty.kind),
395 /// Similar to `ClosureSubsts`; see the above documentation for more.
396 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug,
397 RustcEncodable, RustcDecodable, HashStable)]
398 pub struct GeneratorSubsts<'tcx> {
399 pub substs: SubstsRef<'tcx>,
402 struct SplitGeneratorSubsts<'tcx> {
406 upvar_kinds: &'tcx [GenericArg<'tcx>],
409 impl<'tcx> GeneratorSubsts<'tcx> {
410 fn split(self, def_id: DefId, tcx: TyCtxt<'_>) -> SplitGeneratorSubsts<'tcx> {
411 let generics = tcx.generics_of(def_id);
412 let parent_len = generics.parent_count;
413 SplitGeneratorSubsts {
414 yield_ty: self.substs.type_at(parent_len),
415 return_ty: self.substs.type_at(parent_len + 1),
416 witness: self.substs.type_at(parent_len + 2),
417 upvar_kinds: &self.substs[parent_len + 3..],
421 /// This describes the types that can be contained in a generator.
422 /// It will be a type variable initially and unified in the last stages of typeck of a body.
423 /// It contains a tuple of all the types that could end up on a generator frame.
424 /// The state transformation MIR pass may only produce layouts which mention types
425 /// in this tuple. Upvars are not counted here.
426 pub fn witness(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
427 self.split(def_id, tcx).witness
435 ) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
436 let SplitGeneratorSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
437 upvar_kinds.iter().map(|t| {
438 if let GenericArgKind::Type(ty) = t.unpack() {
441 bug!("upvar should be type")
446 /// Returns the type representing the yield type of the generator.
447 pub fn yield_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
448 self.split(def_id, tcx).yield_ty
451 /// Returns the type representing the return type of the generator.
452 pub fn return_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
453 self.split(def_id, tcx).return_ty
456 /// Returns the "generator signature", which consists of its yield
457 /// and return types.
459 /// N.B., some bits of the code prefers to see this wrapped in a
460 /// binder, but it never contains bound regions. Probably this
461 /// function should be removed.
462 pub fn poly_sig(self, def_id: DefId, tcx: TyCtxt<'_>) -> PolyGenSig<'tcx> {
463 ty::Binder::dummy(self.sig(def_id, tcx))
466 /// Returns the "generator signature", which consists of its yield
467 /// and return types.
468 pub fn sig(self, def_id: DefId, tcx: TyCtxt<'_>) -> GenSig<'tcx> {
470 yield_ty: self.yield_ty(def_id, tcx),
471 return_ty: self.return_ty(def_id, tcx),
476 impl<'tcx> GeneratorSubsts<'tcx> {
477 /// Generator have not been resumed yet
478 pub const UNRESUMED: usize = 0;
479 /// Generator has returned / is completed
480 pub const RETURNED: usize = 1;
481 /// Generator has been poisoned
482 pub const POISONED: usize = 2;
484 const UNRESUMED_NAME: &'static str = "Unresumed";
485 const RETURNED_NAME: &'static str = "Returned";
486 const POISONED_NAME: &'static str = "Panicked";
488 /// The valid variant indices of this Generator.
490 pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
491 // FIXME requires optimized MIR
492 let num_variants = tcx.generator_layout(def_id).variant_fields.len();
493 (VariantIdx::new(0)..VariantIdx::new(num_variants))
496 /// The discriminant for the given variant. Panics if the variant_index is
499 pub fn discriminant_for_variant(
503 variant_index: VariantIdx,
505 // Generators don't support explicit discriminant values, so they are
506 // the same as the variant index.
507 assert!(self.variant_range(def_id, tcx).contains(&variant_index));
508 Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
511 /// The set of all discriminants for the Generator, enumerated with their
514 pub fn discriminants(
518 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
519 self.variant_range(def_id, tcx).map(move |index| {
520 (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
524 /// Calls `f` with a reference to the name of the enumerator for the given
527 pub fn variant_name(self, v: VariantIdx) -> Cow<'static, str> {
529 Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
530 Self::RETURNED => Cow::from(Self::RETURNED_NAME),
531 Self::POISONED => Cow::from(Self::POISONED_NAME),
532 _ => Cow::from(format!("Suspend{}", v.as_usize() - 3))
536 /// The type of the state discriminant used in the generator type.
538 pub fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
542 /// This returns the types of the MIR locals which had to be stored across suspension points.
543 /// It is calculated in rustc_mir::transform::generator::StateTransform.
544 /// All the types here must be in the tuple in GeneratorInterior.
546 /// The locals are grouped by their variant number. Note that some locals may
547 /// be repeated in multiple variants.
553 ) -> impl Iterator<Item = impl Iterator<Item = Ty<'tcx>> + Captures<'tcx>> {
554 let layout = tcx.generator_layout(def_id);
555 layout.variant_fields.iter().map(move |variant| {
556 variant.iter().map(move |field| {
557 layout.field_tys[*field].subst(tcx, self.substs)
562 /// This is the types of the fields of a generator which are not stored in a
565 pub fn prefix_tys(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> impl Iterator<Item = Ty<'tcx>> {
566 self.upvar_tys(def_id, tcx)
570 #[derive(Debug, Copy, Clone)]
571 pub enum UpvarSubsts<'tcx> {
572 Closure(SubstsRef<'tcx>),
573 Generator(SubstsRef<'tcx>),
576 impl<'tcx> UpvarSubsts<'tcx> {
582 ) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
583 let upvar_kinds = match self {
584 UpvarSubsts::Closure(substs) => substs.as_closure().split(def_id, tcx).upvar_kinds,
585 UpvarSubsts::Generator(substs) => substs.as_generator().split(def_id, tcx).upvar_kinds,
587 upvar_kinds.iter().map(|t| {
588 if let GenericArgKind::Type(ty) = t.unpack() {
591 bug!("upvar should be type")
597 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash,
598 RustcEncodable, RustcDecodable, HashStable)]
599 pub enum ExistentialPredicate<'tcx> {
600 /// E.g., `Iterator`.
601 Trait(ExistentialTraitRef<'tcx>),
602 /// E.g., `Iterator::Item = T`.
603 Projection(ExistentialProjection<'tcx>),
608 impl<'tcx> ExistentialPredicate<'tcx> {
609 /// Compares via an ordering that will not change if modules are reordered or other changes are
610 /// made to the tree. In particular, this ordering is preserved across incremental compilations.
611 pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering {
612 use self::ExistentialPredicate::*;
613 match (*self, *other) {
614 (Trait(_), Trait(_)) => Ordering::Equal,
615 (Projection(ref a), Projection(ref b)) =>
616 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
617 (AutoTrait(ref a), AutoTrait(ref b)) =>
618 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
619 (Trait(_), _) => Ordering::Less,
620 (Projection(_), Trait(_)) => Ordering::Greater,
621 (Projection(_), _) => Ordering::Less,
622 (AutoTrait(_), _) => Ordering::Greater,
627 impl<'tcx> Binder<ExistentialPredicate<'tcx>> {
628 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> {
629 use crate::ty::ToPredicate;
630 match *self.skip_binder() {
631 ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
632 ExistentialPredicate::Projection(p) =>
633 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
634 ExistentialPredicate::AutoTrait(did) => {
635 let trait_ref = Binder(ty::TraitRef {
637 substs: tcx.mk_substs_trait(self_ty, &[]),
639 trait_ref.to_predicate()
645 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<ExistentialPredicate<'tcx>> {}
647 impl<'tcx> List<ExistentialPredicate<'tcx>> {
648 /// Returns the "principal `DefId`" of this set of existential predicates.
650 /// A Rust trait object type consists (in addition to a lifetime bound)
651 /// of a set of trait bounds, which are separated into any number
652 /// of auto-trait bounds, and at most one non-auto-trait bound. The
653 /// non-auto-trait bound is called the "principal" of the trait
656 /// Only the principal can have methods or type parameters (because
657 /// auto traits can have neither of them). This is important, because
658 /// it means the auto traits can be treated as an unordered set (methods
659 /// would force an order for the vtable, while relating traits with
660 /// type parameters without knowing the order to relate them in is
661 /// a rather non-trivial task).
663 /// For example, in the trait object `dyn fmt::Debug + Sync`, the
664 /// principal bound is `Some(fmt::Debug)`, while the auto-trait bounds
665 /// are the set `{Sync}`.
667 /// It is also possible to have a "trivial" trait object that
668 /// consists only of auto traits, with no principal - for example,
669 /// `dyn Send + Sync`. In that case, the set of auto-trait bounds
670 /// is `{Send, Sync}`, while there is no principal. These trait objects
671 /// have a "trivial" vtable consisting of just the size, alignment,
673 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
675 ExistentialPredicate::Trait(tr) => Some(tr),
680 pub fn principal_def_id(&self) -> Option<DefId> {
681 self.principal().map(|d| d.def_id)
685 pub fn projection_bounds<'a>(&'a self) ->
686 impl Iterator<Item = ExistentialProjection<'tcx>> + 'a
688 self.iter().filter_map(|predicate| {
690 ExistentialPredicate::Projection(p) => Some(p),
697 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item = DefId> + 'a {
698 self.iter().filter_map(|predicate| {
700 ExistentialPredicate::AutoTrait(d) => Some(d),
707 impl<'tcx> Binder<&'tcx List<ExistentialPredicate<'tcx>>> {
708 pub fn principal(&self) -> Option<ty::Binder<ExistentialTraitRef<'tcx>>> {
709 self.skip_binder().principal().map(Binder::bind)
712 pub fn principal_def_id(&self) -> Option<DefId> {
713 self.skip_binder().principal_def_id()
717 pub fn projection_bounds<'a>(&'a self) ->
718 impl Iterator<Item = PolyExistentialProjection<'tcx>> + 'a {
719 self.skip_binder().projection_bounds().map(Binder::bind)
723 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item = DefId> + 'a {
724 self.skip_binder().auto_traits()
727 pub fn iter<'a>(&'a self)
728 -> impl DoubleEndedIterator<Item = Binder<ExistentialPredicate<'tcx>>> + 'tcx {
729 self.skip_binder().iter().cloned().map(Binder::bind)
733 /// A complete reference to a trait. These take numerous guises in syntax,
734 /// but perhaps the most recognizable form is in a where-clause:
738 /// This would be represented by a trait-reference where the `DefId` is the
739 /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0,
740 /// and `U` as parameter 1.
742 /// Trait references also appear in object types like `Foo<U>`, but in
743 /// that case the `Self` parameter is absent from the substitutions.
745 /// Note that a `TraitRef` introduces a level of region binding, to
746 /// account for higher-ranked trait bounds like `T: for<'a> Foo<&'a U>`
747 /// or higher-ranked object types.
748 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
749 pub struct TraitRef<'tcx> {
751 pub substs: SubstsRef<'tcx>,
754 impl<'tcx> TraitRef<'tcx> {
755 pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> {
756 TraitRef { def_id: def_id, substs: substs }
759 /// Returns a `TraitRef` of the form `P0: Foo<P1..Pn>` where `Pi`
760 /// are the parameters defined on trait.
761 pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> TraitRef<'tcx> {
764 substs: InternalSubsts::identity_for_item(tcx, def_id),
769 pub fn self_ty(&self) -> Ty<'tcx> {
770 self.substs.type_at(0)
773 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
774 // Select only the "input types" from a trait-reference. For
775 // now this is all the types that appear in the
776 // trait-reference, but it should eventually exclude
784 substs: SubstsRef<'tcx>,
785 ) -> ty::TraitRef<'tcx> {
786 let defs = tcx.generics_of(trait_id);
790 substs: tcx.intern_substs(&substs[..defs.params.len()])
795 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
797 impl<'tcx> PolyTraitRef<'tcx> {
798 pub fn self_ty(&self) -> Ty<'tcx> {
799 self.skip_binder().self_ty()
802 pub fn def_id(&self) -> DefId {
803 self.skip_binder().def_id
806 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
807 // Note that we preserve binding levels
808 Binder(ty::TraitPredicate { trait_ref: self.skip_binder().clone() })
812 /// An existential reference to a trait, where `Self` is erased.
813 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
815 /// exists T. T: Trait<'a, 'b, X, Y>
817 /// The substitutions don't include the erased `Self`, only trait
818 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
819 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
820 RustcEncodable, RustcDecodable, HashStable)]
821 pub struct ExistentialTraitRef<'tcx> {
823 pub substs: SubstsRef<'tcx>,
826 impl<'tcx> ExistentialTraitRef<'tcx> {
827 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
828 // Select only the "input types" from a trait-reference. For
829 // now this is all the types that appear in the
830 // trait-reference, but it should eventually exclude
835 pub fn erase_self_ty(
837 trait_ref: ty::TraitRef<'tcx>,
838 ) -> ty::ExistentialTraitRef<'tcx> {
839 // Assert there is a Self.
840 trait_ref.substs.type_at(0);
842 ty::ExistentialTraitRef {
843 def_id: trait_ref.def_id,
844 substs: tcx.intern_substs(&trait_ref.substs[1..])
848 /// Object types don't have a self type specified. Therefore, when
849 /// we convert the principal trait-ref into a normal trait-ref,
850 /// you must give *some* self type. A common choice is `mk_err()`
851 /// or some placeholder type.
852 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> {
853 // otherwise the escaping vars would be captured by the binder
854 // debug_assert!(!self_ty.has_escaping_bound_vars());
858 substs: tcx.mk_substs_trait(self_ty, self.substs)
863 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
865 impl<'tcx> PolyExistentialTraitRef<'tcx> {
866 pub fn def_id(&self) -> DefId {
867 self.skip_binder().def_id
870 /// Object types don't have a self type specified. Therefore, when
871 /// we convert the principal trait-ref into a normal trait-ref,
872 /// you must give *some* self type. A common choice is `mk_err()`
873 /// or some placeholder type.
874 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> {
875 self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
879 /// Binder is a binder for higher-ranked lifetimes or types. It is part of the
880 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
881 /// (which would be represented by the type `PolyTraitRef ==
882 /// Binder<TraitRef>`). Note that when we instantiate,
883 /// erase, or otherwise "discharge" these bound vars, we change the
884 /// type from `Binder<T>` to just `T` (see
885 /// e.g., `liberate_late_bound_regions`).
886 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
887 pub struct Binder<T>(T);
890 /// Wraps `value` in a binder, asserting that `value` does not
891 /// contain any bound vars that would be bound by the
892 /// binder. This is commonly used to 'inject' a value T into a
893 /// different binding level.
894 pub fn dummy<'tcx>(value: T) -> Binder<T>
895 where T: TypeFoldable<'tcx>
897 debug_assert!(!value.has_escaping_bound_vars());
901 /// Wraps `value` in a binder, binding higher-ranked vars (if any).
902 pub fn bind(value: T) -> Binder<T> {
906 /// Skips the binder and returns the "bound" value. This is a
907 /// risky thing to do because it's easy to get confused about
908 /// De Bruijn indices and the like. It is usually better to
909 /// discharge the binder using `no_bound_vars` or
910 /// `replace_late_bound_regions` or something like
911 /// that. `skip_binder` is only valid when you are either
912 /// extracting data that has nothing to do with bound vars, you
913 /// are doing some sort of test that does not involve bound
914 /// regions, or you are being very careful about your depth
917 /// Some examples where `skip_binder` is reasonable:
919 /// - extracting the `DefId` from a PolyTraitRef;
920 /// - comparing the self type of a PolyTraitRef to see if it is equal to
921 /// a type parameter `X`, since the type `X` does not reference any regions
922 pub fn skip_binder(&self) -> &T {
926 pub fn as_ref(&self) -> Binder<&T> {
930 pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
931 where F: FnOnce(&T) -> U
933 self.as_ref().map_bound(f)
936 pub fn map_bound<F, U>(self, f: F) -> Binder<U>
937 where F: FnOnce(T) -> U
942 /// Unwraps and returns the value within, but only if it contains
943 /// no bound vars at all. (In other words, if this binder --
944 /// and indeed any enclosing binder -- doesn't bind anything at
945 /// all.) Otherwise, returns `None`.
947 /// (One could imagine having a method that just unwraps a single
948 /// binder, but permits late-bound vars bound by enclosing
949 /// binders, but that would require adjusting the debruijn
950 /// indices, and given the shallow binding structure we often use,
951 /// would not be that useful.)
952 pub fn no_bound_vars<'tcx>(self) -> Option<T>
953 where T: TypeFoldable<'tcx>
955 if self.skip_binder().has_escaping_bound_vars() {
958 Some(self.skip_binder().clone())
962 /// Given two things that have the same binder level,
963 /// and an operation that wraps on their contents, executes the operation
964 /// and then wraps its result.
966 /// `f` should consider bound regions at depth 1 to be free, and
967 /// anything it produces with bound regions at depth 1 will be
968 /// bound in the resulting return value.
969 pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
970 where F: FnOnce(T, U) -> R
972 Binder(f(self.0, u.0))
975 /// Splits the contents into two things that share the same binder
976 /// level as the original, returning two distinct binders.
978 /// `f` should consider bound regions at depth 1 to be free, and
979 /// anything it produces with bound regions at depth 1 will be
980 /// bound in the resulting return values.
981 pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
982 where F: FnOnce(T) -> (U, V)
984 let (u, v) = f(self.0);
985 (Binder(u), Binder(v))
989 /// Represents the projection of an associated type. In explicit UFCS
990 /// form this would be written `<T as Trait<..>>::N`.
991 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord,
992 Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
993 pub struct ProjectionTy<'tcx> {
994 /// The parameters of the associated item.
995 pub substs: SubstsRef<'tcx>,
997 /// The `DefId` of the `TraitItem` for the associated type `N`.
999 /// Note that this is not the `DefId` of the `TraitRef` containing this
1000 /// associated type, which is in `tcx.associated_item(item_def_id).container`.
1001 pub item_def_id: DefId,
1004 impl<'tcx> ProjectionTy<'tcx> {
1005 /// Construct a `ProjectionTy` by searching the trait from `trait_ref` for the
1006 /// associated item named `item_name`.
1007 pub fn from_ref_and_name(
1009 trait_ref: ty::TraitRef<'tcx>,
1011 ) -> ProjectionTy<'tcx> {
1012 let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
1013 item.kind == ty::AssocKind::Type &&
1014 tcx.hygienic_eq(item_name, item.ident, trait_ref.def_id)
1018 substs: trait_ref.substs,
1023 /// Extracts the underlying trait reference from this projection.
1024 /// For example, if this is a projection of `<T as Iterator>::Item`,
1025 /// then this function would return a `T: Iterator` trait reference.
1026 pub fn trait_ref(&self, tcx: TyCtxt<'_>) -> ty::TraitRef<'tcx> {
1027 let def_id = tcx.associated_item(self.item_def_id).container.id();
1030 substs: self.substs,
1034 pub fn self_ty(&self) -> Ty<'tcx> {
1035 self.substs.type_at(0)
1039 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
1040 pub struct GenSig<'tcx> {
1041 pub yield_ty: Ty<'tcx>,
1042 pub return_ty: Ty<'tcx>,
1045 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
1047 impl<'tcx> PolyGenSig<'tcx> {
1048 pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
1049 self.map_bound_ref(|sig| sig.yield_ty)
1051 pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
1052 self.map_bound_ref(|sig| sig.return_ty)
1056 /// Signature of a function type, which we have arbitrarily
1057 /// decided to use to refer to the input/output types.
1059 /// - `inputs`: is the list of arguments and their modes.
1060 /// - `output`: is the return type.
1061 /// - `c_variadic`: indicates whether this is a C-variadic function.
1062 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord,
1063 Hash, RustcEncodable, RustcDecodable, HashStable)]
1064 pub struct FnSig<'tcx> {
1065 pub inputs_and_output: &'tcx List<Ty<'tcx>>,
1066 pub c_variadic: bool,
1067 pub unsafety: hir::Unsafety,
1071 impl<'tcx> FnSig<'tcx> {
1072 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
1073 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
1076 pub fn output(&self) -> Ty<'tcx> {
1077 self.inputs_and_output[self.inputs_and_output.len() - 1]
1080 // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible
1082 fn fake() -> FnSig<'tcx> {
1084 inputs_and_output: List::empty(),
1086 unsafety: hir::Unsafety::Normal,
1087 abi: abi::Abi::Rust,
1092 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1094 impl<'tcx> PolyFnSig<'tcx> {
1096 pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
1097 self.map_bound_ref(|fn_sig| fn_sig.inputs())
1100 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
1101 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
1103 pub fn inputs_and_output(&self) -> ty::Binder<&'tcx List<Ty<'tcx>>> {
1104 self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
1107 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
1108 self.map_bound_ref(|fn_sig| fn_sig.output())
1110 pub fn c_variadic(&self) -> bool {
1111 self.skip_binder().c_variadic
1113 pub fn unsafety(&self) -> hir::Unsafety {
1114 self.skip_binder().unsafety
1116 pub fn abi(&self) -> abi::Abi {
1117 self.skip_binder().abi
1121 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<FnSig<'tcx>>>;
1123 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
1124 Hash, RustcEncodable, RustcDecodable, HashStable)]
1125 pub struct ParamTy {
1127 pub name: InternedString,
1130 impl<'tcx> ParamTy {
1131 pub fn new(index: u32, name: InternedString) -> ParamTy {
1132 ParamTy { index, name: name }
1135 pub fn for_self() -> ParamTy {
1136 ParamTy::new(0, kw::SelfUpper.as_interned_str())
1139 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1140 ParamTy::new(def.index, def.name)
1143 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1144 tcx.mk_ty_param(self.index, self.name)
1148 #[derive(Copy, Clone, Hash, RustcEncodable, RustcDecodable,
1149 Eq, PartialEq, Ord, PartialOrd, HashStable)]
1150 pub struct ParamConst {
1152 pub name: InternedString,
1155 impl<'tcx> ParamConst {
1156 pub fn new(index: u32, name: InternedString) -> ParamConst {
1157 ParamConst { index, name }
1160 pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
1161 ParamConst::new(def.index, def.name)
1164 pub fn to_const(self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
1165 tcx.mk_const_param(self.index, self.name, ty)
1169 rustc_index::newtype_index! {
1170 /// A [De Bruijn index][dbi] is a standard means of representing
1171 /// regions (and perhaps later types) in a higher-ranked setting. In
1172 /// particular, imagine a type like this:
1174 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1177 /// | +------------+ 0 | |
1179 /// +--------------------------------+ 1 |
1181 /// +------------------------------------------+ 0
1183 /// In this type, there are two binders (the outer fn and the inner
1184 /// fn). We need to be able to determine, for any given region, which
1185 /// fn type it is bound by, the inner or the outer one. There are
1186 /// various ways you can do this, but a De Bruijn index is one of the
1187 /// more convenient and has some nice properties. The basic idea is to
1188 /// count the number of binders, inside out. Some examples should help
1189 /// clarify what I mean.
1191 /// Let's start with the reference type `&'b isize` that is the first
1192 /// argument to the inner function. This region `'b` is assigned a De
1193 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
1194 /// fn). The region `'a` that appears in the second argument type (`&'a
1195 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
1196 /// second-innermost binder". (These indices are written on the arrays
1197 /// in the diagram).
1199 /// What is interesting is that De Bruijn index attached to a particular
1200 /// variable will vary depending on where it appears. For example,
1201 /// the final type `&'a char` also refers to the region `'a` declared on
1202 /// the outermost fn. But this time, this reference is not nested within
1203 /// any other binders (i.e., it is not an argument to the inner fn, but
1204 /// rather the outer one). Therefore, in this case, it is assigned a
1205 /// De Bruijn index of 0, because the innermost binder in that location
1206 /// is the outer fn.
1208 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1209 pub struct DebruijnIndex {
1210 DEBUG_FORMAT = "DebruijnIndex({})",
1211 const INNERMOST = 0,
1215 pub type Region<'tcx> = &'tcx RegionKind;
1217 /// Representation of regions.
1219 /// Unlike types, most region variants are "fictitious", not concrete,
1220 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1221 /// ones representing concrete regions.
1223 /// ## Bound Regions
1225 /// These are regions that are stored behind a binder and must be substituted
1226 /// with some concrete region before being used. There are two kind of
1227 /// bound regions: early-bound, which are bound in an item's `Generics`,
1228 /// and are substituted by a `InternalSubsts`, and late-bound, which are part of
1229 /// higher-ranked types (e.g., `for<'a> fn(&'a ())`), and are substituted by
1230 /// the likes of `liberate_late_bound_regions`. The distinction exists
1231 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1233 /// Unlike `Param`s, bound regions are not supposed to exist "in the wild"
1234 /// outside their binder, e.g., in types passed to type inference, and
1235 /// should first be substituted (by placeholder regions, free regions,
1236 /// or region variables).
1238 /// ## Placeholder and Free Regions
1240 /// One often wants to work with bound regions without knowing their precise
1241 /// identity. For example, when checking a function, the lifetime of a borrow
1242 /// can end up being assigned to some region parameter. In these cases,
1243 /// it must be ensured that bounds on the region can't be accidentally
1244 /// assumed without being checked.
1246 /// To do this, we replace the bound regions with placeholder markers,
1247 /// which don't satisfy any relation not explicitly provided.
1249 /// There are two kinds of placeholder regions in rustc: `ReFree` and
1250 /// `RePlaceholder`. When checking an item's body, `ReFree` is supposed
1251 /// to be used. These also support explicit bounds: both the internally-stored
1252 /// *scope*, which the region is assumed to outlive, as well as other
1253 /// relations stored in the `FreeRegionMap`. Note that these relations
1254 /// aren't checked when you `make_subregion` (or `eq_types`), only by
1255 /// `resolve_regions_and_report_errors`.
1257 /// When working with higher-ranked types, some region relations aren't
1258 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1259 /// `RePlaceholder` is designed for this purpose. In these contexts,
1260 /// there's also the risk that some inference variable laying around will
1261 /// get unified with your placeholder region: if you want to check whether
1262 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1263 /// with a placeholder region `'%a`, the variable `'_` would just be
1264 /// instantiated to the placeholder region `'%a`, which is wrong because
1265 /// the inference variable is supposed to satisfy the relation
1266 /// *for every value of the placeholder region*. To ensure that doesn't
1267 /// happen, you can use `leak_check`. This is more clearly explained
1268 /// by the [rustc guide].
1270 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1271 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1272 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/hrtb.html
1273 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1274 pub enum RegionKind {
1275 /// Region bound in a type or fn declaration which will be
1276 /// substituted 'early' -- that is, at the same time when type
1277 /// parameters are substituted.
1278 ReEarlyBound(EarlyBoundRegion),
1280 /// Region bound in a function scope, which will be substituted when the
1281 /// function is called.
1282 ReLateBound(DebruijnIndex, BoundRegion),
1284 /// When checking a function body, the types of all arguments and so forth
1285 /// that refer to bound region parameters are modified to refer to free
1286 /// region parameters.
1289 /// A concrete region naming some statically determined scope
1290 /// (e.g., an expression or sequence of statements) within the
1291 /// current function.
1292 ReScope(region::Scope),
1294 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1297 /// A region variable. Should not exist after typeck.
1300 /// A placeholder region - basically the higher-ranked version of ReFree.
1301 /// Should not exist after typeck.
1302 RePlaceholder(ty::PlaceholderRegion),
1304 /// Empty lifetime is for data that is never accessed.
1305 /// Bottom in the region lattice. We treat ReEmpty somewhat
1306 /// specially; at least right now, we do not generate instances of
1307 /// it during the GLB computations, but rather
1308 /// generate an error instead. This is to improve error messages.
1309 /// The only way to get an instance of ReEmpty is to have a region
1310 /// variable with no constraints.
1313 /// Erased region, used by trait selection, in MIR and during codegen.
1316 /// These are regions bound in the "defining type" for a
1317 /// closure. They are used ONLY as part of the
1318 /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1319 /// See `ClosureRegionRequirements` for more details.
1320 ReClosureBound(RegionVid),
1323 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Region<'tcx> {}
1325 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1326 pub struct EarlyBoundRegion {
1329 pub name: InternedString,
1332 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1337 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1338 pub struct ConstVid<'tcx> {
1340 pub phantom: PhantomData<&'tcx ()>,
1343 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1348 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1349 pub struct FloatVid {
1353 rustc_index::newtype_index! {
1354 pub struct RegionVid {
1355 DEBUG_FORMAT = custom,
1359 impl Atom for RegionVid {
1360 fn index(self) -> usize {
1365 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
1366 Hash, RustcEncodable, RustcDecodable, HashStable)]
1372 /// A `FreshTy` is one that is generated as a replacement for an
1373 /// unbound type variable. This is convenient for caching etc. See
1374 /// `infer::freshen` for more details.
1380 rustc_index::newtype_index! {
1381 pub struct BoundVar { .. }
1384 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1385 pub struct BoundTy {
1387 pub kind: BoundTyKind,
1390 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1391 pub enum BoundTyKind {
1393 Param(InternedString),
1396 impl_stable_hash_for!(struct BoundTy { var, kind });
1397 impl_stable_hash_for!(enum self::BoundTyKind { Anon, Param(a) });
1399 impl From<BoundVar> for BoundTy {
1400 fn from(var: BoundVar) -> Self {
1403 kind: BoundTyKind::Anon,
1408 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1409 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash,
1410 Debug, RustcEncodable, RustcDecodable, HashStable)]
1411 pub struct ExistentialProjection<'tcx> {
1412 pub item_def_id: DefId,
1413 pub substs: SubstsRef<'tcx>,
1417 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1419 impl<'tcx> ExistentialProjection<'tcx> {
1420 /// Extracts the underlying existential trait reference from this projection.
1421 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1422 /// then this function would return a `exists T. T: Iterator` existential trait
1424 pub fn trait_ref(&self, tcx: TyCtxt<'_>) -> ty::ExistentialTraitRef<'tcx> {
1425 let def_id = tcx.associated_item(self.item_def_id).container.id();
1426 ty::ExistentialTraitRef{
1428 substs: self.substs,
1432 pub fn with_self_ty(
1436 ) -> ty::ProjectionPredicate<'tcx> {
1437 // otherwise the escaping regions would be captured by the binders
1438 debug_assert!(!self_ty.has_escaping_bound_vars());
1440 ty::ProjectionPredicate {
1441 projection_ty: ty::ProjectionTy {
1442 item_def_id: self.item_def_id,
1443 substs: tcx.mk_substs_trait(self_ty, self.substs),
1450 impl<'tcx> PolyExistentialProjection<'tcx> {
1451 pub fn with_self_ty(
1455 ) -> ty::PolyProjectionPredicate<'tcx> {
1456 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1459 pub fn item_def_id(&self) -> DefId {
1460 return self.skip_binder().item_def_id;
1464 impl DebruijnIndex {
1465 /// Returns the resulting index when this value is moved into
1466 /// `amount` number of new binders. So, e.g., if you had
1468 /// for<'a> fn(&'a x)
1470 /// and you wanted to change it to
1472 /// for<'a> fn(for<'b> fn(&'a x))
1474 /// you would need to shift the index for `'a` into a new binder.
1476 pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
1477 DebruijnIndex::from_u32(self.as_u32() + amount)
1480 /// Update this index in place by shifting it "in" through
1481 /// `amount` number of binders.
1482 pub fn shift_in(&mut self, amount: u32) {
1483 *self = self.shifted_in(amount);
1486 /// Returns the resulting index when this value is moved out from
1487 /// `amount` number of new binders.
1489 pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
1490 DebruijnIndex::from_u32(self.as_u32() - amount)
1493 /// Update in place by shifting out from `amount` binders.
1494 pub fn shift_out(&mut self, amount: u32) {
1495 *self = self.shifted_out(amount);
1498 /// Adjusts any De Bruijn indices so as to make `to_binder` the
1499 /// innermost binder. That is, if we have something bound at `to_binder`,
1500 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1501 /// when moving a region out from inside binders:
1504 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1505 /// // Binder: D3 D2 D1 ^^
1508 /// Here, the region `'a` would have the De Bruijn index D3,
1509 /// because it is the bound 3 binders out. However, if we wanted
1510 /// to refer to that region `'a` in the second argument (the `_`),
1511 /// those two binders would not be in scope. In that case, we
1512 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1513 /// De Bruijn index of `'a` to D1 (the innermost binder).
1515 /// If we invoke `shift_out_to_binder` and the region is in fact
1516 /// bound by one of the binders we are shifting out of, that is an
1517 /// error (and should fail an assertion failure).
1518 pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
1519 self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
1523 impl_stable_hash_for!(struct DebruijnIndex { private });
1525 /// Region utilities
1527 /// Is this region named by the user?
1528 pub fn has_name(&self) -> bool {
1530 RegionKind::ReEarlyBound(ebr) => ebr.has_name(),
1531 RegionKind::ReLateBound(_, br) => br.is_named(),
1532 RegionKind::ReFree(fr) => fr.bound_region.is_named(),
1533 RegionKind::ReScope(..) => false,
1534 RegionKind::ReStatic => true,
1535 RegionKind::ReVar(..) => false,
1536 RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(),
1537 RegionKind::ReEmpty => false,
1538 RegionKind::ReErased => false,
1539 RegionKind::ReClosureBound(..) => false,
1543 pub fn is_late_bound(&self) -> bool {
1545 ty::ReLateBound(..) => true,
1550 pub fn is_placeholder(&self) -> bool {
1552 ty::RePlaceholder(..) => true,
1557 pub fn bound_at_or_above_binder(&self, index: DebruijnIndex) -> bool {
1559 ty::ReLateBound(debruijn, _) => debruijn >= index,
1564 /// Adjusts any De Bruijn indices so as to make `to_binder` the
1565 /// innermost binder. That is, if we have something bound at `to_binder`,
1566 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1567 /// when moving a region out from inside binders:
1570 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1571 /// // Binder: D3 D2 D1 ^^
1574 /// Here, the region `'a` would have the De Bruijn index D3,
1575 /// because it is the bound 3 binders out. However, if we wanted
1576 /// to refer to that region `'a` in the second argument (the `_`),
1577 /// those two binders would not be in scope. In that case, we
1578 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1579 /// De Bruijn index of `'a` to D1 (the innermost binder).
1581 /// If we invoke `shift_out_to_binder` and the region is in fact
1582 /// bound by one of the binders we are shifting out of, that is an
1583 /// error (and should fail an assertion failure).
1584 pub fn shifted_out_to_binder(&self, to_binder: ty::DebruijnIndex) -> RegionKind {
1586 ty::ReLateBound(debruijn, r) => ty::ReLateBound(
1587 debruijn.shifted_out_to_binder(to_binder),
1594 pub fn keep_in_local_tcx(&self) -> bool {
1595 if let ty::ReVar(..) = self {
1602 pub fn type_flags(&self) -> TypeFlags {
1603 let mut flags = TypeFlags::empty();
1605 if self.keep_in_local_tcx() {
1606 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1611 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1612 flags = flags | TypeFlags::HAS_RE_INFER;
1614 ty::RePlaceholder(..) => {
1615 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1616 flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
1618 ty::ReLateBound(..) => {
1619 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1621 ty::ReEarlyBound(..) => {
1622 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1623 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1628 ty::ReScope { .. } => {
1629 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1633 ty::ReClosureBound(..) => {
1634 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1639 ty::ReStatic | ty::ReEmpty | ty::ReErased | ty::ReLateBound(..) => (),
1640 _ => flags = flags | TypeFlags::HAS_FREE_LOCAL_NAMES,
1643 debug!("type_flags({:?}) = {:?}", self, flags);
1648 /// Given an early-bound or free region, returns the `DefId` where it was bound.
1649 /// For example, consider the regions in this snippet of code:
1653 /// ^^ -- early bound, declared on an impl
1655 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1656 /// ^^ ^^ ^ anonymous, late-bound
1657 /// | early-bound, appears in where-clauses
1658 /// late-bound, appears only in fn args
1663 /// Here, `free_region_binding_scope('a)` would return the `DefId`
1664 /// of the impl, and for all the other highlighted regions, it
1665 /// would return the `DefId` of the function. In other cases (not shown), this
1666 /// function might return the `DefId` of a closure.
1667 pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_>) -> DefId {
1669 ty::ReEarlyBound(br) => {
1670 tcx.parent(br.def_id).unwrap()
1672 ty::ReFree(fr) => fr.scope,
1673 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1679 impl<'tcx> TyS<'tcx> {
1681 pub fn is_unit(&self) -> bool {
1683 Tuple(ref tys) => tys.is_empty(),
1689 pub fn is_never(&self) -> bool {
1696 /// Checks whether a type is definitely uninhabited. This is
1697 /// conservative: for some types that are uninhabited we return `false`,
1698 /// but we only return `true` for types that are definitely uninhabited.
1699 /// `ty.conservative_is_privately_uninhabited` implies that any value of type `ty`
1700 /// will be `Abi::Uninhabited`. (Note that uninhabited types may have nonzero
1701 /// size, to account for partial initialisation. See #49298 for details.)
1702 pub fn conservative_is_privately_uninhabited(&self, tcx: TyCtxt<'tcx>) -> bool {
1703 // FIXME(varkor): we can make this less conversative by substituting concrete
1707 ty::Adt(def, _) if def.is_union() => {
1708 // For now, `union`s are never considered uninhabited.
1711 ty::Adt(def, _) => {
1712 // Any ADT is uninhabited if either:
1713 // (a) It has no variants (i.e. an empty `enum`);
1714 // (b) Each of its variants (a single one in the case of a `struct`) has at least
1715 // one uninhabited field.
1716 def.variants.iter().all(|var| {
1717 var.fields.iter().any(|field| {
1718 tcx.type_of(field.did).conservative_is_privately_uninhabited(tcx)
1722 ty::Tuple(..) => self.tuple_fields().any(|ty| {
1723 ty.conservative_is_privately_uninhabited(tcx)
1725 ty::Array(ty, len) => {
1726 match len.try_eval_usize(tcx, ParamEnv::empty()) {
1727 // If the array is definitely non-empty, it's uninhabited if
1728 // the type of its elements is uninhabited.
1729 Some(n) if n != 0 => ty.conservative_is_privately_uninhabited(tcx),
1734 // References to uninitialised memory is valid for any type, including
1735 // uninhabited types, in unsafe code, so we treat all references as
1744 pub fn is_primitive(&self) -> bool {
1746 Bool | Char | Int(_) | Uint(_) | Float(_) => true,
1752 pub fn is_ty_var(&self) -> bool {
1754 Infer(TyVar(_)) => true,
1760 pub fn is_ty_infer(&self) -> bool {
1768 pub fn is_phantom_data(&self) -> bool {
1769 if let Adt(def, _) = self.kind {
1770 def.is_phantom_data()
1777 pub fn is_bool(&self) -> bool { self.kind == Bool }
1780 pub fn is_param(&self, index: u32) -> bool {
1782 ty::Param(ref data) => data.index == index,
1788 pub fn is_slice(&self) -> bool {
1790 RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => match ty.kind {
1791 Slice(_) | Str => true,
1799 pub fn is_simd(&self) -> bool {
1801 Adt(def, _) => def.repr.simd(),
1806 pub fn sequence_element_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1808 Array(ty, _) | Slice(ty) => ty,
1809 Str => tcx.mk_mach_uint(ast::UintTy::U8),
1810 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1814 pub fn simd_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1816 Adt(def, substs) => {
1817 def.non_enum_variant().fields[0].ty(tcx, substs)
1819 _ => bug!("simd_type called on invalid type")
1823 pub fn simd_size(&self, _cx: TyCtxt<'_>) -> usize {
1825 Adt(def, _) => def.non_enum_variant().fields.len(),
1826 _ => bug!("simd_size called on invalid type")
1831 pub fn is_region_ptr(&self) -> bool {
1839 pub fn is_mutable_ptr(&self) -> bool {
1841 RawPtr(TypeAndMut { mutbl: hir::Mutability::MutMutable, .. }) |
1842 Ref(_, _, hir::Mutability::MutMutable) => true,
1848 pub fn is_unsafe_ptr(&self) -> bool {
1850 RawPtr(_) => return true,
1855 /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1857 pub fn is_any_ptr(&self) -> bool {
1858 self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr()
1861 /// Returns `true` if this type is an `Arc<T>`.
1863 pub fn is_arc(&self) -> bool {
1865 Adt(def, _) => def.is_arc(),
1870 /// Returns `true` if this type is an `Rc<T>`.
1872 pub fn is_rc(&self) -> bool {
1874 Adt(def, _) => def.is_rc(),
1880 pub fn is_box(&self) -> bool {
1882 Adt(def, _) => def.is_box(),
1887 /// panics if called on any type other than `Box<T>`
1888 pub fn boxed_ty(&self) -> Ty<'tcx> {
1890 Adt(def, substs) if def.is_box() => substs.type_at(0),
1891 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1895 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1896 /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1897 /// contents are abstract to rustc.)
1899 pub fn is_scalar(&self) -> bool {
1901 Bool | Char | Int(_) | Float(_) | Uint(_) |
1902 Infer(IntVar(_)) | Infer(FloatVar(_)) |
1903 FnDef(..) | FnPtr(_) | RawPtr(_) => true,
1908 /// Returns `true` if this type is a floating point type.
1910 pub fn is_floating_point(&self) -> bool {
1913 Infer(FloatVar(_)) => true,
1919 pub fn is_trait(&self) -> bool {
1921 Dynamic(..) => true,
1927 pub fn is_enum(&self) -> bool {
1929 Adt(adt_def, _) => {
1937 pub fn is_closure(&self) -> bool {
1939 Closure(..) => true,
1945 pub fn is_generator(&self) -> bool {
1947 Generator(..) => true,
1953 pub fn is_integral(&self) -> bool {
1955 Infer(IntVar(_)) | Int(_) | Uint(_) => true,
1961 pub fn is_fresh_ty(&self) -> bool {
1963 Infer(FreshTy(_)) => true,
1969 pub fn is_fresh(&self) -> bool {
1971 Infer(FreshTy(_)) => true,
1972 Infer(FreshIntTy(_)) => true,
1973 Infer(FreshFloatTy(_)) => true,
1979 pub fn is_char(&self) -> bool {
1987 pub fn is_numeric(&self) -> bool {
1988 self.is_integral() || self.is_floating_point()
1992 pub fn is_signed(&self) -> bool {
2000 pub fn is_ptr_sized_integral(&self) -> bool {
2002 Int(ast::IntTy::Isize) | Uint(ast::UintTy::Usize) => true,
2008 pub fn is_machine(&self) -> bool {
2010 Int(..) | Uint(..) | Float(..) => true,
2016 pub fn has_concrete_skeleton(&self) -> bool {
2018 Param(_) | Infer(_) | Error => false,
2023 /// Returns the type and mutability of `*ty`.
2025 /// The parameter `explicit` indicates if this is an *explicit* dereference.
2026 /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
2027 pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
2029 Adt(def, _) if def.is_box() => {
2031 ty: self.boxed_ty(),
2032 mutbl: hir::MutImmutable,
2035 Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
2036 RawPtr(mt) if explicit => Some(mt),
2041 /// Returns the type of `ty[i]`.
2042 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
2044 Array(ty, _) | Slice(ty) => Some(ty),
2049 pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
2051 FnDef(def_id, substs) => {
2052 tcx.fn_sig(def_id).subst(tcx, substs)
2055 Error => { // ignore errors (#54954)
2056 ty::Binder::dummy(FnSig::fake())
2058 Closure(..) => bug!(
2059 "to get the signature of a closure, use `closure_sig()` not `fn_sig()`",
2061 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
2066 pub fn is_fn(&self) -> bool {
2068 FnDef(..) | FnPtr(_) => true,
2074 pub fn is_fn_ptr(&self) -> bool {
2082 pub fn is_impl_trait(&self) -> bool {
2090 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
2092 Adt(adt, _) => Some(adt),
2097 /// Iterates over tuple fields.
2098 /// Panics when called on anything but a tuple.
2099 pub fn tuple_fields(&self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> {
2101 Tuple(substs) => substs.iter().map(|field| field.expect_ty()),
2102 _ => bug!("tuple_fields called on non-tuple"),
2106 /// If the type contains variants, returns the valid range of variant indices.
2107 /// FIXME This requires the optimized MIR in the case of generators.
2109 pub fn variant_range(&self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
2111 TyKind::Adt(adt, _) => Some(adt.variant_range()),
2112 TyKind::Generator(def_id, substs, _) =>
2113 Some(substs.as_generator().variant_range(def_id, tcx)),
2118 /// If the type contains variants, returns the variant for `variant_index`.
2119 /// Panics if `variant_index` is out of range.
2120 /// FIXME This requires the optimized MIR in the case of generators.
2122 pub fn discriminant_for_variant(
2125 variant_index: VariantIdx,
2126 ) -> Option<Discr<'tcx>> {
2128 TyKind::Adt(adt, _) => Some(adt.discriminant_for_variant(tcx, variant_index)),
2129 TyKind::Generator(def_id, substs, _) =>
2130 Some(substs.as_generator().discriminant_for_variant(def_id, tcx, variant_index)),
2135 /// Push onto `out` the regions directly referenced from this type (but not
2136 /// types reachable from this type via `walk_tys`). This ignores late-bound
2137 /// regions binders.
2138 pub fn push_regions(&self, out: &mut SmallVec<[ty::Region<'tcx>; 4]>) {
2140 Ref(region, _, _) => {
2143 Dynamic(ref obj, region) => {
2145 if let Some(principal) = obj.principal() {
2146 out.extend(principal.skip_binder().substs.regions());
2149 Adt(_, substs) | Opaque(_, substs) => {
2150 out.extend(substs.regions())
2152 Closure(_, ref substs ) |
2153 Generator(_, ref substs, _) => {
2154 out.extend(substs.regions())
2156 Projection(ref data) | UnnormalizedProjection(ref data) => {
2157 out.extend(data.substs.regions())
2161 GeneratorWitness(..) |
2182 /// When we create a closure, we record its kind (i.e., what trait
2183 /// it implements) into its `ClosureSubsts` using a type
2184 /// parameter. This is kind of a phantom type, except that the
2185 /// most convenient thing for us to are the integral types. This
2186 /// function converts such a special type into the closure
2187 /// kind. To go the other way, use
2188 /// `tcx.closure_kind_ty(closure_kind)`.
2190 /// Note that during type checking, we use an inference variable
2191 /// to represent the closure kind, because it has not yet been
2192 /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
2193 /// is complete, that type variable will be unified.
2194 pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
2196 Int(int_ty) => match int_ty {
2197 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
2198 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
2199 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
2200 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2205 Error => Some(ty::ClosureKind::Fn),
2207 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2211 /// Fast path helper for testing if a type is `Sized`.
2213 /// Returning true means the type is known to be sized. Returning
2214 /// `false` means nothing -- could be sized, might not be.
2215 pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool {
2217 ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
2218 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
2219 ty::FnDef(..) | ty::FnPtr(_) | ty::RawPtr(..) |
2220 ty::Char | ty::Ref(..) | ty::Generator(..) |
2221 ty::GeneratorWitness(..) | ty::Array(..) | ty::Closure(..) |
2222 ty::Never | ty::Error =>
2225 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) =>
2229 tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx))
2232 ty::Adt(def, _substs) =>
2233 def.sized_constraint(tcx).is_empty(),
2235 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
2237 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
2239 ty::Infer(ty::TyVar(_)) => false,
2242 ty::Placeholder(..) |
2243 ty::Infer(ty::FreshTy(_)) |
2244 ty::Infer(ty::FreshIntTy(_)) |
2245 ty::Infer(ty::FreshFloatTy(_)) =>
2246 bug!("is_trivially_sized applied to unexpected type: {:?}", self),
2251 /// Typed constant value.
2252 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable,
2253 Eq, PartialEq, Ord, PartialOrd, HashStable)]
2254 pub struct Const<'tcx> {
2257 pub val: ConstValue<'tcx>,
2260 #[cfg(target_arch = "x86_64")]
2261 static_assert_size!(Const<'_>, 40);
2263 impl<'tcx> Const<'tcx> {
2265 pub fn from_scalar(tcx: TyCtxt<'tcx>, val: Scalar, ty: Ty<'tcx>) -> &'tcx Self {
2267 val: ConstValue::Scalar(val),
2273 pub fn from_bits(tcx: TyCtxt<'tcx>, bits: u128, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> &'tcx Self {
2274 let size = tcx.layout_of(ty).unwrap_or_else(|e| {
2275 panic!("could not compute layout for {:?}: {:?}", ty, e)
2277 Self::from_scalar(tcx, Scalar::from_uint(bits, size), ty.value)
2281 pub fn zero_sized(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
2282 Self::from_scalar(tcx, Scalar::zst(), ty)
2286 pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> &'tcx Self {
2287 Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
2291 pub fn from_usize(tcx: TyCtxt<'tcx>, n: u64) -> &'tcx Self {
2292 Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
2296 pub fn try_eval_bits(
2299 param_env: ParamEnv<'tcx>,
2302 assert_eq!(self.ty, ty);
2303 // This is purely an optimization -- layout_of is a pretty expensive operation,
2304 // but if we can determine the size without calling it, we don't need all that complexity
2305 // (hashing, caching, etc.). As such, try to skip it.
2306 let size = match ty.kind {
2307 ty::Bool => Size::from_bytes(1),
2308 ty::Char => Size::from_bytes(4),
2310 Integer::from_attr(&tcx, SignedInt(ity)).size()
2313 Integer::from_attr(&tcx, UnsignedInt(uty)).size()
2315 _ => tcx.layout_of(param_env.with_reveal_all().and(ty)).ok()?.size,
2317 // if `ty` does not depend on generic parameters, use an empty param_env
2318 self.eval(tcx, param_env).val.try_to_bits(size)
2325 param_env: ParamEnv<'tcx>,
2327 // FIXME(const_generics): this doesn't work right now,
2328 // because it tries to relate an `Infer` to a `Param`.
2330 ConstValue::Unevaluated(did, substs) => {
2331 // if `substs` has no unresolved components, use and empty param_env
2332 let (param_env, substs) = param_env.with_reveal_all().and(substs).into_parts();
2333 // try to resolve e.g. associated constants to their definition on an impl
2334 let instance = match ty::Instance::resolve(tcx, param_env, did, substs) {
2335 Some(instance) => instance,
2336 None => return self,
2338 let gid = GlobalId {
2342 tcx.const_eval(param_env.and(gid)).unwrap_or(self)
2349 pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<bool> {
2350 self.try_eval_bits(tcx, param_env, tcx.types.bool).and_then(|v| match v {
2358 pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<u64> {
2359 self.try_eval_bits(tcx, param_env, tcx.types.usize).map(|v| v as u64)
2363 pub fn eval_bits(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: Ty<'tcx>) -> u128 {
2364 self.try_eval_bits(tcx, param_env, ty).unwrap_or_else(||
2365 bug!("expected bits of {:#?}, got {:#?}", ty, self))
2369 pub fn eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> u64 {
2370 self.eval_bits(tcx, param_env, tcx.types.usize) as u64
2374 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}
2376 /// An inference variable for a const, for use in const generics.
2377 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd,
2378 Ord, RustcEncodable, RustcDecodable, Hash, HashStable)]
2379 pub enum InferConst<'tcx> {
2380 /// Infer the value of the const.
2381 Var(ConstVid<'tcx>),
2382 /// A fresh const variable. See `infer::freshen` for more details.
2384 /// Canonicalized const variable, used only when preparing a trait query.
2385 Canonical(DebruijnIndex, BoundVar),