1 //! This module contains `TyKind` and its major components.
4 use crate::hir::def_id::DefId;
5 use crate::infer::canonical::Canonical;
6 use crate::mir::interpret::ConstValue;
7 use crate::middle::region;
8 use polonius_engine::Atom;
9 use rustc_data_structures::indexed_vec::Idx;
10 use rustc_macros::HashStable;
11 use crate::ty::subst::{InternalSubsts, Subst, SubstsRef, Kind, UnpackedKind};
12 use crate::ty::{self, AdtDef, Discr, DefIdTree, TypeFlags, Ty, TyCtxt, TypeFoldable};
13 use crate::ty::{List, TyS, ParamEnvAnd, ParamEnv};
14 use crate::ty::layout::VariantIdx;
15 use crate::util::captures::Captures;
16 use crate::mir::interpret::{Scalar, Pointer};
18 use smallvec::SmallVec;
20 use std::cmp::Ordering;
21 use std::marker::PhantomData;
23 use rustc_target::spec::abi;
24 use syntax::ast::{self, Ident};
25 use syntax::symbol::{kw, InternedString};
31 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
32 Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
33 pub struct TypeAndMut<'tcx> {
35 pub mutbl: hir::Mutability,
38 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
39 RustcEncodable, RustcDecodable, Copy, HashStable)]
40 /// A "free" region `fr` can be interpreted as "some region
41 /// at least as big as the scope `fr.scope`".
42 pub struct FreeRegion {
44 pub bound_region: BoundRegion,
47 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
48 RustcEncodable, RustcDecodable, Copy, HashStable)]
49 pub enum BoundRegion {
50 /// An anonymous region parameter for a given fn (&T)
53 /// Named region parameters for functions (a in &'a T)
55 /// The `DefId` is needed to distinguish free regions in
56 /// the event of shadowing.
57 BrNamed(DefId, InternedString),
59 /// Anonymous region for the implicit env pointer parameter
65 pub fn is_named(&self) -> bool {
67 BoundRegion::BrNamed(..) => true,
72 /// When canonicalizing, we replace unbound inference variables and free
73 /// regions with anonymous late bound regions. This method asserts that
74 /// we have an anonymous late bound region, which hence may refer to
75 /// a canonical variable.
76 pub fn assert_bound_var(&self) -> BoundVar {
78 BoundRegion::BrAnon(var) => BoundVar::from_u32(var),
79 _ => bug!("bound region is not anonymous"),
84 /// N.B., if you change this, you'll probably want to change the corresponding
85 /// AST structure in `libsyntax/ast.rs` as well.
86 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
87 RustcEncodable, RustcDecodable, HashStable, Debug)]
88 pub enum TyKind<'tcx> {
89 /// The primitive boolean type. Written as `bool`.
92 /// The primitive character type; holds a Unicode scalar value
93 /// (a non-surrogate code point). Written as `char`.
96 /// A primitive signed integer type. For example, `i32`.
99 /// A primitive unsigned integer type. For example, `u32`.
102 /// A primitive floating-point type. For example, `f64`.
105 /// Structures, enumerations and unions.
107 /// InternalSubsts here, possibly against intuition, *may* contain `Param`s.
108 /// That is, even after substitution it is possible that there are type
109 /// variables. This happens when the `Adt` corresponds to an ADT
110 /// definition and not a concrete use of it.
111 Adt(&'tcx AdtDef, SubstsRef<'tcx>),
113 /// An unsized FFI type that is opaque to Rust. Written as `extern type T`.
116 /// The pointee of a string slice. Written as `str`.
119 /// An array with the given length. Written as `[T; n]`.
120 Array(Ty<'tcx>, &'tcx ty::Const<'tcx>),
122 /// The pointee of an array slice. Written as `[T]`.
125 /// A raw pointer. Written as `*mut T` or `*const T`
126 RawPtr(TypeAndMut<'tcx>),
128 /// A reference; a pointer with an associated lifetime. Written as
129 /// `&'a mut T` or `&'a T`.
130 Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability),
132 /// The anonymous type of a function declaration/definition. Each
133 /// function has a unique type, which is output (for a function
134 /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
136 /// For example the type of `bar` here:
139 /// fn foo() -> i32 { 1 }
140 /// let bar = foo; // bar: fn() -> i32 {foo}
142 FnDef(DefId, SubstsRef<'tcx>),
144 /// A pointer to a function. Written as `fn() -> i32`.
146 /// For example the type of `bar` here:
149 /// fn foo() -> i32 { 1 }
150 /// let bar: fn() -> i32 = foo;
152 FnPtr(PolyFnSig<'tcx>),
154 /// A trait, defined with `trait`.
155 Dynamic(Binder<&'tcx List<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
157 /// The anonymous type of a closure. Used to represent the type of
159 Closure(DefId, ClosureSubsts<'tcx>),
161 /// The anonymous type of a generator. Used to represent the type of
163 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
165 /// A type representin the types stored inside a generator.
166 /// This should only appear in GeneratorInteriors.
167 GeneratorWitness(Binder<&'tcx List<Ty<'tcx>>>),
169 /// The never type `!`
172 /// A tuple type. For example, `(i32, bool)`.
173 Tuple(SubstsRef<'tcx>),
175 /// The projection of an associated type. For example,
176 /// `<T as Trait<..>>::N`.
177 Projection(ProjectionTy<'tcx>),
179 /// A placeholder type used when we do not have enough information
180 /// to normalize the projection of an associated type to an
181 /// existing concrete type. Currently only used with chalk-engine.
182 UnnormalizedProjection(ProjectionTy<'tcx>),
184 /// Opaque (`impl Trait`) type found in a return type.
185 /// The `DefId` comes either from
186 /// * the `impl Trait` ast::Ty node,
187 /// * or the `existential type` declaration
188 /// The substitutions are for the generics of the function in question.
189 /// After typeck, the concrete type can be found in the `types` map.
190 Opaque(DefId, SubstsRef<'tcx>),
192 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
195 /// Bound type variable, used only when preparing a trait query.
196 Bound(ty::DebruijnIndex, BoundTy),
198 /// A placeholder type - universally quantified higher-ranked type.
199 Placeholder(ty::PlaceholderType),
201 /// A type variable used during type checking.
204 /// A placeholder for a type which could not be computed; this is
205 /// propagated to avoid useless error messages.
209 // `TyKind` is used a lot. Make sure it doesn't unintentionally get bigger.
210 #[cfg(target_arch = "x86_64")]
211 static_assert_size!(TyKind<'_>, 24);
213 /// A closure can be modeled as a struct that looks like:
215 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
223 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
224 /// in scope on the function that defined the closure,
225 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
226 /// is rather hackily encoded via a scalar type. See
227 /// `TyS::to_opt_closure_kind` for details.
228 /// - CS represents the *closure signature*, representing as a `fn()`
229 /// type. For example, `fn(u32, u32) -> u32` would mean that the closure
230 /// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
232 /// - U0...Uk are type parameters representing the types of its upvars
233 /// (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
234 /// and the up-var has the type `Foo`, then `Ui = &Foo`).
236 /// So, for example, given this function:
238 /// fn foo<'a, T>(data: &'a mut T) {
239 /// do(|| data.count += 1)
242 /// the type of the closure would be something like:
244 /// struct Closure<'a, T, U0> {
248 /// Note that the type of the upvar is not specified in the struct.
249 /// You may wonder how the impl would then be able to use the upvar,
250 /// if it doesn't know it's type? The answer is that the impl is
251 /// (conceptually) not fully generic over Closure but rather tied to
252 /// instances with the expected upvar types:
254 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
258 /// You can see that the *impl* fully specified the type of the upvar
259 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
260 /// (Here, I am assuming that `data` is mut-borrowed.)
262 /// Now, the last question you may ask is: Why include the upvar types
263 /// as extra type parameters? The reason for this design is that the
264 /// upvar types can reference lifetimes that are internal to the
265 /// creating function. In my example above, for example, the lifetime
266 /// `'b` represents the scope of the closure itself; this is some
267 /// subset of `foo`, probably just the scope of the call to the to
268 /// `do()`. If we just had the lifetime/type parameters from the
269 /// enclosing function, we couldn't name this lifetime `'b`. Note that
270 /// there can also be lifetimes in the types of the upvars themselves,
271 /// if one of them happens to be a reference to something that the
272 /// creating fn owns.
274 /// OK, you say, so why not create a more minimal set of parameters
275 /// that just includes the extra lifetime parameters? The answer is
276 /// primarily that it would be hard --- we don't know at the time when
277 /// we create the closure type what the full types of the upvars are,
278 /// nor do we know which are borrowed and which are not. In this
279 /// design, we can just supply a fresh type parameter and figure that
282 /// All right, you say, but why include the type parameters from the
283 /// original function then? The answer is that codegen may need them
284 /// when monomorphizing, and they may not appear in the upvars. A
285 /// closure could capture no variables but still make use of some
286 /// in-scope type parameter with a bound (e.g., if our example above
287 /// had an extra `U: Default`, and the closure called `U::default()`).
289 /// There is another reason. This design (implicitly) prohibits
290 /// closures from capturing themselves (except via a trait
291 /// object). This simplifies closure inference considerably, since it
292 /// means that when we infer the kind of a closure or its upvars, we
293 /// don't have to handle cycles where the decisions we make for
294 /// closure C wind up influencing the decisions we ought to make for
295 /// closure C (which would then require fixed point iteration to
296 /// handle). Plus it fixes an ICE. :P
300 /// Generators are handled similarly in `GeneratorSubsts`. The set of
301 /// type parameters is similar, but the role of CK and CS are
302 /// different. CK represents the "yield type" and CS represents the
303 /// "return type" of the generator.
304 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
305 Debug, RustcEncodable, RustcDecodable, HashStable)]
306 pub struct ClosureSubsts<'tcx> {
307 /// Lifetime and type parameters from the enclosing function,
308 /// concatenated with the types of the upvars.
310 /// These are separated out because codegen wants to pass them around
311 /// when monomorphizing.
312 pub substs: SubstsRef<'tcx>,
315 /// Struct returned by `split()`. Note that these are subslices of the
316 /// parent slice and not canonical substs themselves.
317 struct SplitClosureSubsts<'tcx> {
318 closure_kind_ty: Ty<'tcx>,
319 closure_sig_ty: Ty<'tcx>,
320 upvar_kinds: &'tcx [Kind<'tcx>],
323 impl<'tcx> ClosureSubsts<'tcx> {
324 /// Divides the closure substs into their respective
325 /// components. Single source of truth with respect to the
327 fn split(self, def_id: DefId, tcx: TyCtxt<'_>) -> SplitClosureSubsts<'tcx> {
328 let generics = tcx.generics_of(def_id);
329 let parent_len = generics.parent_count;
331 closure_kind_ty: self.substs.type_at(parent_len),
332 closure_sig_ty: self.substs.type_at(parent_len + 1),
333 upvar_kinds: &self.substs[parent_len + 2..],
342 ) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
343 let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
344 upvar_kinds.iter().map(|t| {
345 if let UnpackedKind::Type(ty) = t.unpack() {
348 bug!("upvar should be type")
353 /// Returns the closure kind for this closure; may return a type
354 /// variable during inference. To get the closure kind during
355 /// inference, use `infcx.closure_kind(def_id, substs)`.
356 pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
357 self.split(def_id, tcx).closure_kind_ty
360 /// Returns the type representing the closure signature for this
361 /// closure; may contain type variables during inference. To get
362 /// the closure signature during inference, use
363 /// `infcx.fn_sig(def_id)`.
364 pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
365 self.split(def_id, tcx).closure_sig_ty
368 /// Returns the closure kind for this closure; only usable outside
369 /// of an inference context, because in that context we know that
370 /// there are no type variables.
372 /// If you have an inference context, use `infcx.closure_kind()`.
373 pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::ClosureKind {
374 self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
377 /// Extracts the signature from the closure; only usable outside
378 /// of an inference context, because in that context we know that
379 /// there are no type variables.
381 /// If you have an inference context, use `infcx.closure_sig()`.
382 pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
383 let ty = self.closure_sig_ty(def_id, tcx);
385 ty::FnPtr(sig) => sig,
386 _ => bug!("closure_sig_ty is not a fn-ptr: {:?}", ty),
391 /// Similar to `ClosureSubsts`; see the above documentation for more.
392 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug,
393 RustcEncodable, RustcDecodable, HashStable)]
394 pub struct GeneratorSubsts<'tcx> {
395 pub substs: SubstsRef<'tcx>,
398 struct SplitGeneratorSubsts<'tcx> {
402 upvar_kinds: &'tcx [Kind<'tcx>],
405 impl<'tcx> GeneratorSubsts<'tcx> {
406 fn split(self, def_id: DefId, tcx: TyCtxt<'_>) -> SplitGeneratorSubsts<'tcx> {
407 let generics = tcx.generics_of(def_id);
408 let parent_len = generics.parent_count;
409 SplitGeneratorSubsts {
410 yield_ty: self.substs.type_at(parent_len),
411 return_ty: self.substs.type_at(parent_len + 1),
412 witness: self.substs.type_at(parent_len + 2),
413 upvar_kinds: &self.substs[parent_len + 3..],
417 /// This describes the types that can be contained in a generator.
418 /// It will be a type variable initially and unified in the last stages of typeck of a body.
419 /// It contains a tuple of all the types that could end up on a generator frame.
420 /// The state transformation MIR pass may only produce layouts which mention types
421 /// in this tuple. Upvars are not counted here.
422 pub fn witness(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
423 self.split(def_id, tcx).witness
431 ) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
432 let SplitGeneratorSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
433 upvar_kinds.iter().map(|t| {
434 if let UnpackedKind::Type(ty) = t.unpack() {
437 bug!("upvar should be type")
442 /// Returns the type representing the yield type of the generator.
443 pub fn yield_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
444 self.split(def_id, tcx).yield_ty
447 /// Returns the type representing the return type of the generator.
448 pub fn return_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> {
449 self.split(def_id, tcx).return_ty
452 /// Returns the "generator signature", which consists of its yield
453 /// and return types.
455 /// N.B., some bits of the code prefers to see this wrapped in a
456 /// binder, but it never contains bound regions. Probably this
457 /// function should be removed.
458 pub fn poly_sig(self, def_id: DefId, tcx: TyCtxt<'_>) -> PolyGenSig<'tcx> {
459 ty::Binder::dummy(self.sig(def_id, tcx))
462 /// Returns the "generator signature", which consists of its yield
463 /// and return types.
464 pub fn sig(self, def_id: DefId, tcx: TyCtxt<'_>) -> GenSig<'tcx> {
466 yield_ty: self.yield_ty(def_id, tcx),
467 return_ty: self.return_ty(def_id, tcx),
472 impl<'tcx> GeneratorSubsts<'tcx> {
473 /// Generator have not been resumed yet
474 pub const UNRESUMED: usize = 0;
475 /// Generator has returned / is completed
476 pub const RETURNED: usize = 1;
477 /// Generator has been poisoned
478 pub const POISONED: usize = 2;
480 const UNRESUMED_NAME: &'static str = "Unresumed";
481 const RETURNED_NAME: &'static str = "Returned";
482 const POISONED_NAME: &'static str = "Panicked";
484 /// The valid variant indices of this Generator.
486 pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
487 // FIXME requires optimized MIR
488 let num_variants = tcx.generator_layout(def_id).variant_fields.len();
489 (VariantIdx::new(0)..VariantIdx::new(num_variants))
492 /// The discriminant for the given variant. Panics if the variant_index is
495 pub fn discriminant_for_variant(
499 variant_index: VariantIdx,
501 // Generators don't support explicit discriminant values, so they are
502 // the same as the variant index.
503 assert!(self.variant_range(def_id, tcx).contains(&variant_index));
504 Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
507 /// The set of all discriminants for the Generator, enumerated with their
510 pub fn discriminants(
514 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
515 self.variant_range(def_id, tcx).map(move |index| {
516 (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
520 /// Calls `f` with a reference to the name of the enumerator for the given
523 pub fn variant_name(&self, v: VariantIdx) -> Cow<'static, str> {
525 Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
526 Self::RETURNED => Cow::from(Self::RETURNED_NAME),
527 Self::POISONED => Cow::from(Self::POISONED_NAME),
528 _ => Cow::from(format!("Suspend{}", v.as_usize() - 3))
532 /// The type of the state discriminant used in the generator type.
534 pub fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
538 /// This returns the types of the MIR locals which had to be stored across suspension points.
539 /// It is calculated in rustc_mir::transform::generator::StateTransform.
540 /// All the types here must be in the tuple in GeneratorInterior.
542 /// The locals are grouped by their variant number. Note that some locals may
543 /// be repeated in multiple variants.
549 ) -> impl Iterator<Item = impl Iterator<Item = Ty<'tcx>> + Captures<'tcx>> {
550 let layout = tcx.generator_layout(def_id);
551 layout.variant_fields.iter().map(move |variant| {
552 variant.iter().map(move |field| {
553 layout.field_tys[*field].subst(tcx, self.substs)
558 /// This is the types of the fields of a generator which are not stored in a
561 pub fn prefix_tys(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> impl Iterator<Item = Ty<'tcx>> {
562 self.upvar_tys(def_id, tcx)
566 #[derive(Debug, Copy, Clone)]
567 pub enum UpvarSubsts<'tcx> {
568 Closure(ClosureSubsts<'tcx>),
569 Generator(GeneratorSubsts<'tcx>),
572 impl<'tcx> UpvarSubsts<'tcx> {
578 ) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
579 let upvar_kinds = match self {
580 UpvarSubsts::Closure(substs) => substs.split(def_id, tcx).upvar_kinds,
581 UpvarSubsts::Generator(substs) => substs.split(def_id, tcx).upvar_kinds,
583 upvar_kinds.iter().map(|t| {
584 if let UnpackedKind::Type(ty) = t.unpack() {
587 bug!("upvar should be type")
593 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash,
594 RustcEncodable, RustcDecodable, HashStable)]
595 pub enum ExistentialPredicate<'tcx> {
596 /// E.g., `Iterator`.
597 Trait(ExistentialTraitRef<'tcx>),
598 /// E.g., `Iterator::Item = T`.
599 Projection(ExistentialProjection<'tcx>),
604 impl<'tcx> ExistentialPredicate<'tcx> {
605 /// Compares via an ordering that will not change if modules are reordered or other changes are
606 /// made to the tree. In particular, this ordering is preserved across incremental compilations.
607 pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering {
608 use self::ExistentialPredicate::*;
609 match (*self, *other) {
610 (Trait(_), Trait(_)) => Ordering::Equal,
611 (Projection(ref a), Projection(ref b)) =>
612 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
613 (AutoTrait(ref a), AutoTrait(ref b)) =>
614 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
615 (Trait(_), _) => Ordering::Less,
616 (Projection(_), Trait(_)) => Ordering::Greater,
617 (Projection(_), _) => Ordering::Less,
618 (AutoTrait(_), _) => Ordering::Greater,
623 impl<'tcx> Binder<ExistentialPredicate<'tcx>> {
624 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> {
625 use crate::ty::ToPredicate;
626 match *self.skip_binder() {
627 ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
628 ExistentialPredicate::Projection(p) =>
629 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
630 ExistentialPredicate::AutoTrait(did) => {
631 let trait_ref = Binder(ty::TraitRef {
633 substs: tcx.mk_substs_trait(self_ty, &[]),
635 trait_ref.to_predicate()
641 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx List<ExistentialPredicate<'tcx>> {}
643 impl<'tcx> List<ExistentialPredicate<'tcx>> {
644 /// Returns the "principal def id" of this set of existential predicates.
646 /// A Rust trait object type consists (in addition to a lifetime bound)
647 /// of a set of trait bounds, which are separated into any number
648 /// of auto-trait bounds, and at most 1 non-auto-trait bound. The
649 /// non-auto-trait bound is called the "principal" of the trait
652 /// Only the principal can have methods or type parameters (because
653 /// auto traits can have neither of them). This is important, because
654 /// it means the auto traits can be treated as an unordered set (methods
655 /// would force an order for the vtable, while relating traits with
656 /// type parameters without knowing the order to relate them in is
657 /// a rather non-trivial task).
659 /// For example, in the trait object `dyn fmt::Debug + Sync`, the
660 /// principal bound is `Some(fmt::Debug)`, while the auto-trait bounds
661 /// are the set `{Sync}`.
663 /// It is also possible to have a "trivial" trait object that
664 /// consists only of auto traits, with no principal - for example,
665 /// `dyn Send + Sync`. In that case, the set of auto-trait bounds
666 /// is `{Send, Sync}`, while there is no principal. These trait objects
667 /// have a "trivial" vtable consisting of just the size, alignment,
669 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
671 ExistentialPredicate::Trait(tr) => Some(tr),
676 pub fn principal_def_id(&self) -> Option<DefId> {
677 self.principal().map(|d| d.def_id)
681 pub fn projection_bounds<'a>(&'a self) ->
682 impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
683 self.iter().filter_map(|predicate| {
685 ExistentialPredicate::Projection(p) => Some(p),
692 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
693 self.iter().filter_map(|predicate| {
695 ExistentialPredicate::AutoTrait(d) => Some(d),
702 impl<'tcx> Binder<&'tcx List<ExistentialPredicate<'tcx>>> {
703 pub fn principal(&self) -> Option<ty::Binder<ExistentialTraitRef<'tcx>>> {
704 self.skip_binder().principal().map(Binder::bind)
707 pub fn principal_def_id(&self) -> Option<DefId> {
708 self.skip_binder().principal_def_id()
712 pub fn projection_bounds<'a>(&'a self) ->
713 impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
714 self.skip_binder().projection_bounds().map(Binder::bind)
718 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
719 self.skip_binder().auto_traits()
722 pub fn iter<'a>(&'a self)
723 -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
724 self.skip_binder().iter().cloned().map(Binder::bind)
728 /// A complete reference to a trait. These take numerous guises in syntax,
729 /// but perhaps the most recognizable form is in a where-clause:
733 /// This would be represented by a trait-reference where the `DefId` is the
734 /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0,
735 /// and `U` as parameter 1.
737 /// Trait references also appear in object types like `Foo<U>`, but in
738 /// that case the `Self` parameter is absent from the substitutions.
740 /// Note that a `TraitRef` introduces a level of region binding, to
741 /// account for higher-ranked trait bounds like `T: for<'a> Foo<&'a U>`
742 /// or higher-ranked object types.
743 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
744 pub struct TraitRef<'tcx> {
746 pub substs: SubstsRef<'tcx>,
749 impl<'tcx> TraitRef<'tcx> {
750 pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> {
751 TraitRef { def_id: def_id, substs: substs }
754 /// Returns a `TraitRef` of the form `P0: Foo<P1..Pn>` where `Pi`
755 /// are the parameters defined on trait.
756 pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> TraitRef<'tcx> {
759 substs: InternalSubsts::identity_for_item(tcx, def_id),
764 pub fn self_ty(&self) -> Ty<'tcx> {
765 self.substs.type_at(0)
768 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
769 // Select only the "input types" from a trait-reference. For
770 // now this is all the types that appear in the
771 // trait-reference, but it should eventually exclude
779 substs: SubstsRef<'tcx>,
780 ) -> ty::TraitRef<'tcx> {
781 let defs = tcx.generics_of(trait_id);
785 substs: tcx.intern_substs(&substs[..defs.params.len()])
790 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
792 impl<'tcx> PolyTraitRef<'tcx> {
793 pub fn self_ty(&self) -> Ty<'tcx> {
794 self.skip_binder().self_ty()
797 pub fn def_id(&self) -> DefId {
798 self.skip_binder().def_id
801 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
802 // Note that we preserve binding levels
803 Binder(ty::TraitPredicate { trait_ref: self.skip_binder().clone() })
807 /// An existential reference to a trait, where `Self` is erased.
808 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
810 /// exists T. T: Trait<'a, 'b, X, Y>
812 /// The substitutions don't include the erased `Self`, only trait
813 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
814 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
815 RustcEncodable, RustcDecodable, HashStable)]
816 pub struct ExistentialTraitRef<'tcx> {
818 pub substs: SubstsRef<'tcx>,
821 impl<'tcx> ExistentialTraitRef<'tcx> {
822 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
823 // Select only the "input types" from a trait-reference. For
824 // now this is all the types that appear in the
825 // trait-reference, but it should eventually exclude
830 pub fn erase_self_ty(
832 trait_ref: ty::TraitRef<'tcx>,
833 ) -> ty::ExistentialTraitRef<'tcx> {
834 // Assert there is a Self.
835 trait_ref.substs.type_at(0);
837 ty::ExistentialTraitRef {
838 def_id: trait_ref.def_id,
839 substs: tcx.intern_substs(&trait_ref.substs[1..])
843 /// Object types don't have a self type specified. Therefore, when
844 /// we convert the principal trait-ref into a normal trait-ref,
845 /// you must give *some* self type. A common choice is `mk_err()`
846 /// or some placeholder type.
847 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> {
848 // otherwise the escaping vars would be captured by the binder
849 // debug_assert!(!self_ty.has_escaping_bound_vars());
853 substs: tcx.mk_substs_trait(self_ty, self.substs)
858 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
860 impl<'tcx> PolyExistentialTraitRef<'tcx> {
861 pub fn def_id(&self) -> DefId {
862 self.skip_binder().def_id
865 /// Object types don't have a self type specified. Therefore, when
866 /// we convert the principal trait-ref into a normal trait-ref,
867 /// you must give *some* self type. A common choice is `mk_err()`
868 /// or some placeholder type.
869 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> {
870 self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
874 /// Binder is a binder for higher-ranked lifetimes or types. It is part of the
875 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
876 /// (which would be represented by the type `PolyTraitRef ==
877 /// Binder<TraitRef>`). Note that when we instantiate,
878 /// erase, or otherwise "discharge" these bound vars, we change the
879 /// type from `Binder<T>` to just `T` (see
880 /// e.g., `liberate_late_bound_regions`).
881 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
882 pub struct Binder<T>(T);
885 /// Wraps `value` in a binder, asserting that `value` does not
886 /// contain any bound vars that would be bound by the
887 /// binder. This is commonly used to 'inject' a value T into a
888 /// different binding level.
889 pub fn dummy<'tcx>(value: T) -> Binder<T>
890 where T: TypeFoldable<'tcx>
892 debug_assert!(!value.has_escaping_bound_vars());
896 /// Wraps `value` in a binder, binding higher-ranked vars (if any).
897 pub fn bind(value: T) -> Binder<T> {
901 /// Skips the binder and returns the "bound" value. This is a
902 /// risky thing to do because it's easy to get confused about
903 /// De Bruijn indices and the like. It is usually better to
904 /// discharge the binder using `no_bound_vars` or
905 /// `replace_late_bound_regions` or something like
906 /// that. `skip_binder` is only valid when you are either
907 /// extracting data that has nothing to do with bound vars, you
908 /// are doing some sort of test that does not involve bound
909 /// regions, or you are being very careful about your depth
912 /// Some examples where `skip_binder` is reasonable:
914 /// - extracting the `DefId` from a PolyTraitRef;
915 /// - comparing the self type of a PolyTraitRef to see if it is equal to
916 /// a type parameter `X`, since the type `X` does not reference any regions
917 pub fn skip_binder(&self) -> &T {
921 pub fn as_ref(&self) -> Binder<&T> {
925 pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
926 where F: FnOnce(&T) -> U
928 self.as_ref().map_bound(f)
931 pub fn map_bound<F, U>(self, f: F) -> Binder<U>
932 where F: FnOnce(T) -> U
937 /// Unwraps and returns the value within, but only if it contains
938 /// no bound vars at all. (In other words, if this binder --
939 /// and indeed any enclosing binder -- doesn't bind anything at
940 /// all.) Otherwise, returns `None`.
942 /// (One could imagine having a method that just unwraps a single
943 /// binder, but permits late-bound vars bound by enclosing
944 /// binders, but that would require adjusting the debruijn
945 /// indices, and given the shallow binding structure we often use,
946 /// would not be that useful.)
947 pub fn no_bound_vars<'tcx>(self) -> Option<T>
948 where T: TypeFoldable<'tcx>
950 if self.skip_binder().has_escaping_bound_vars() {
953 Some(self.skip_binder().clone())
957 /// Given two things that have the same binder level,
958 /// and an operation that wraps on their contents, executes the operation
959 /// and then wraps its result.
961 /// `f` should consider bound regions at depth 1 to be free, and
962 /// anything it produces with bound regions at depth 1 will be
963 /// bound in the resulting return value.
964 pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
965 where F: FnOnce(T, U) -> R
967 Binder(f(self.0, u.0))
970 /// Splits the contents into two things that share the same binder
971 /// level as the original, returning two distinct binders.
973 /// `f` should consider bound regions at depth 1 to be free, and
974 /// anything it produces with bound regions at depth 1 will be
975 /// bound in the resulting return values.
976 pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
977 where F: FnOnce(T) -> (U, V)
979 let (u, v) = f(self.0);
980 (Binder(u), Binder(v))
984 /// Represents the projection of an associated type. In explicit UFCS
985 /// form this would be written `<T as Trait<..>>::N`.
986 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord,
987 Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
988 pub struct ProjectionTy<'tcx> {
989 /// The parameters of the associated item.
990 pub substs: SubstsRef<'tcx>,
992 /// The `DefId` of the `TraitItem` for the associated type `N`.
994 /// Note that this is not the `DefId` of the `TraitRef` containing this
995 /// associated type, which is in `tcx.associated_item(item_def_id).container`.
996 pub item_def_id: DefId,
999 impl<'tcx> ProjectionTy<'tcx> {
1000 /// Construct a `ProjectionTy` by searching the trait from `trait_ref` for the
1001 /// associated item named `item_name`.
1002 pub fn from_ref_and_name(
1004 trait_ref: ty::TraitRef<'tcx>,
1006 ) -> ProjectionTy<'tcx> {
1007 let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
1008 item.kind == ty::AssocKind::Type &&
1009 tcx.hygienic_eq(item_name, item.ident, trait_ref.def_id)
1013 substs: trait_ref.substs,
1018 /// Extracts the underlying trait reference from this projection.
1019 /// For example, if this is a projection of `<T as Iterator>::Item`,
1020 /// then this function would return a `T: Iterator` trait reference.
1021 pub fn trait_ref(&self, tcx: TyCtxt<'_>) -> ty::TraitRef<'tcx> {
1022 let def_id = tcx.associated_item(self.item_def_id).container.id();
1025 substs: self.substs,
1029 pub fn self_ty(&self) -> Ty<'tcx> {
1030 self.substs.type_at(0)
1034 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
1035 pub struct GenSig<'tcx> {
1036 pub yield_ty: Ty<'tcx>,
1037 pub return_ty: Ty<'tcx>,
1040 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
1042 impl<'tcx> PolyGenSig<'tcx> {
1043 pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
1044 self.map_bound_ref(|sig| sig.yield_ty)
1046 pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
1047 self.map_bound_ref(|sig| sig.return_ty)
1051 /// Signature of a function type, which I have arbitrarily
1052 /// decided to use to refer to the input/output types.
1054 /// - `inputs`: is the list of arguments and their modes.
1055 /// - `output`: is the return type.
1056 /// - `c_variadic`: indicates whether this is a C-variadic function.
1057 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord,
1058 Hash, RustcEncodable, RustcDecodable, HashStable)]
1059 pub struct FnSig<'tcx> {
1060 pub inputs_and_output: &'tcx List<Ty<'tcx>>,
1061 pub c_variadic: bool,
1062 pub unsafety: hir::Unsafety,
1066 impl<'tcx> FnSig<'tcx> {
1067 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
1068 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
1071 pub fn output(&self) -> Ty<'tcx> {
1072 self.inputs_and_output[self.inputs_and_output.len() - 1]
1075 // Create a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible method
1076 fn fake() -> FnSig<'tcx> {
1078 inputs_and_output: List::empty(),
1080 unsafety: hir::Unsafety::Normal,
1081 abi: abi::Abi::Rust,
1086 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1088 impl<'tcx> PolyFnSig<'tcx> {
1090 pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
1091 self.map_bound_ref(|fn_sig| fn_sig.inputs())
1094 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
1095 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
1097 pub fn inputs_and_output(&self) -> ty::Binder<&'tcx List<Ty<'tcx>>> {
1098 self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
1101 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
1102 self.map_bound_ref(|fn_sig| fn_sig.output())
1104 pub fn c_variadic(&self) -> bool {
1105 self.skip_binder().c_variadic
1107 pub fn unsafety(&self) -> hir::Unsafety {
1108 self.skip_binder().unsafety
1110 pub fn abi(&self) -> abi::Abi {
1111 self.skip_binder().abi
1115 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<FnSig<'tcx>>>;
1118 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
1119 Hash, RustcEncodable, RustcDecodable, HashStable)]
1120 pub struct ParamTy {
1122 pub name: InternedString,
1125 impl<'tcx> ParamTy {
1126 pub fn new(index: u32, name: InternedString) -> ParamTy {
1127 ParamTy { index, name: name }
1130 pub fn for_self() -> ParamTy {
1131 ParamTy::new(0, kw::SelfUpper.as_interned_str())
1134 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1135 ParamTy::new(def.index, def.name)
1138 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1139 tcx.mk_ty_param(self.index, self.name)
1142 pub fn is_self(&self) -> bool {
1143 // FIXME(#50125): Ignoring `Self` with `index != 0` might lead to weird behavior elsewhere,
1144 // but this should only be possible when using `-Z continue-parse-after-error` like
1145 // `compile-fail/issue-36638.rs`.
1146 self.name.as_symbol() == kw::SelfUpper && self.index == 0
1150 #[derive(Copy, Clone, Hash, RustcEncodable, RustcDecodable,
1151 Eq, PartialEq, Ord, PartialOrd, HashStable)]
1152 pub struct ParamConst {
1154 pub name: InternedString,
1157 impl<'tcx> ParamConst {
1158 pub fn new(index: u32, name: InternedString) -> ParamConst {
1159 ParamConst { index, name }
1162 pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
1163 ParamConst::new(def.index, def.name)
1166 pub fn to_const(self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
1167 tcx.mk_const_param(self.index, self.name, ty)
1172 /// A [De Bruijn index][dbi] is a standard means of representing
1173 /// regions (and perhaps later types) in a higher-ranked setting. In
1174 /// particular, imagine a type like this:
1176 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1179 /// | +------------+ 0 | |
1181 /// +--------------------------------+ 1 |
1183 /// +------------------------------------------+ 0
1185 /// In this type, there are two binders (the outer fn and the inner
1186 /// fn). We need to be able to determine, for any given region, which
1187 /// fn type it is bound by, the inner or the outer one. There are
1188 /// various ways you can do this, but a De Bruijn index is one of the
1189 /// more convenient and has some nice properties. The basic idea is to
1190 /// count the number of binders, inside out. Some examples should help
1191 /// clarify what I mean.
1193 /// Let's start with the reference type `&'b isize` that is the first
1194 /// argument to the inner function. This region `'b` is assigned a De
1195 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
1196 /// fn). The region `'a` that appears in the second argument type (`&'a
1197 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
1198 /// second-innermost binder". (These indices are written on the arrays
1199 /// in the diagram).
1201 /// What is interesting is that De Bruijn index attached to a particular
1202 /// variable will vary depending on where it appears. For example,
1203 /// the final type `&'a char` also refers to the region `'a` declared on
1204 /// the outermost fn. But this time, this reference is not nested within
1205 /// any other binders (i.e., it is not an argument to the inner fn, but
1206 /// rather the outer one). Therefore, in this case, it is assigned a
1207 /// De Bruijn index of 0, because the innermost binder in that location
1208 /// is the outer fn.
1210 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1211 pub struct DebruijnIndex {
1212 DEBUG_FORMAT = "DebruijnIndex({})",
1213 const INNERMOST = 0,
1217 pub type Region<'tcx> = &'tcx RegionKind;
1219 /// Representation of regions.
1221 /// Unlike types, most region variants are "fictitious", not concrete,
1222 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1223 /// ones representing concrete regions.
1225 /// ## Bound Regions
1227 /// These are regions that are stored behind a binder and must be substituted
1228 /// with some concrete region before being used. There are two kind of
1229 /// bound regions: early-bound, which are bound in an item's `Generics`,
1230 /// and are substituted by a `InternalSubsts`, and late-bound, which are part of
1231 /// higher-ranked types (e.g., `for<'a> fn(&'a ())`), and are substituted by
1232 /// the likes of `liberate_late_bound_regions`. The distinction exists
1233 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1235 /// Unlike `Param`s, bound regions are not supposed to exist "in the wild"
1236 /// outside their binder, e.g., in types passed to type inference, and
1237 /// should first be substituted (by placeholder regions, free regions,
1238 /// or region variables).
1240 /// ## Placeholder and Free Regions
1242 /// One often wants to work with bound regions without knowing their precise
1243 /// identity. For example, when checking a function, the lifetime of a borrow
1244 /// can end up being assigned to some region parameter. In these cases,
1245 /// it must be ensured that bounds on the region can't be accidentally
1246 /// assumed without being checked.
1248 /// To do this, we replace the bound regions with placeholder markers,
1249 /// which don't satisfy any relation not explicitly provided.
1251 /// There are two kinds of placeholder regions in rustc: `ReFree` and
1252 /// `RePlaceholder`. When checking an item's body, `ReFree` is supposed
1253 /// to be used. These also support explicit bounds: both the internally-stored
1254 /// *scope*, which the region is assumed to outlive, as well as other
1255 /// relations stored in the `FreeRegionMap`. Note that these relations
1256 /// aren't checked when you `make_subregion` (or `eq_types`), only by
1257 /// `resolve_regions_and_report_errors`.
1259 /// When working with higher-ranked types, some region relations aren't
1260 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1261 /// `RePlaceholder` is designed for this purpose. In these contexts,
1262 /// there's also the risk that some inference variable laying around will
1263 /// get unified with your placeholder region: if you want to check whether
1264 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1265 /// with a placeholder region `'%a`, the variable `'_` would just be
1266 /// instantiated to the placeholder region `'%a`, which is wrong because
1267 /// the inference variable is supposed to satisfy the relation
1268 /// *for every value of the placeholder region*. To ensure that doesn't
1269 /// happen, you can use `leak_check`. This is more clearly explained
1270 /// by the [rustc guide].
1272 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1273 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1274 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/hrtb.html
1275 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1276 pub enum RegionKind {
1277 /// Region bound in a type or fn declaration which will be
1278 /// substituted 'early' -- that is, at the same time when type
1279 /// parameters are substituted.
1280 ReEarlyBound(EarlyBoundRegion),
1282 /// Region bound in a function scope, which will be substituted when the
1283 /// function is called.
1284 ReLateBound(DebruijnIndex, BoundRegion),
1286 /// When checking a function body, the types of all arguments and so forth
1287 /// that refer to bound region parameters are modified to refer to free
1288 /// region parameters.
1291 /// A concrete region naming some statically determined scope
1292 /// (e.g., an expression or sequence of statements) within the
1293 /// current function.
1294 ReScope(region::Scope),
1296 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1299 /// A region variable. Should not exist after typeck.
1302 /// A placeholder region - basically the higher-ranked version of ReFree.
1303 /// Should not exist after typeck.
1304 RePlaceholder(ty::PlaceholderRegion),
1306 /// Empty lifetime is for data that is never accessed.
1307 /// Bottom in the region lattice. We treat ReEmpty somewhat
1308 /// specially; at least right now, we do not generate instances of
1309 /// it during the GLB computations, but rather
1310 /// generate an error instead. This is to improve error messages.
1311 /// The only way to get an instance of ReEmpty is to have a region
1312 /// variable with no constraints.
1315 /// Erased region, used by trait selection, in MIR and during codegen.
1318 /// These are regions bound in the "defining type" for a
1319 /// closure. They are used ONLY as part of the
1320 /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1321 /// See `ClosureRegionRequirements` for more details.
1322 ReClosureBound(RegionVid),
1325 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1327 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1328 pub struct EarlyBoundRegion {
1331 pub name: InternedString,
1334 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1339 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1340 pub struct ConstVid<'tcx> {
1342 pub phantom: PhantomData<&'tcx ()>,
1345 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1350 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1351 pub struct FloatVid {
1356 pub struct RegionVid {
1357 DEBUG_FORMAT = custom,
1361 impl Atom for RegionVid {
1362 fn index(self) -> usize {
1367 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
1368 Hash, RustcEncodable, RustcDecodable, HashStable)]
1374 /// A `FreshTy` is one that is generated as a replacement for an
1375 /// unbound type variable. This is convenient for caching etc. See
1376 /// `infer::freshen` for more details.
1383 pub struct BoundVar { .. }
1386 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1387 pub struct BoundTy {
1389 pub kind: BoundTyKind,
1392 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1393 pub enum BoundTyKind {
1395 Param(InternedString),
1398 impl_stable_hash_for!(struct BoundTy { var, kind });
1399 impl_stable_hash_for!(enum self::BoundTyKind { Anon, Param(a) });
1401 impl From<BoundVar> for BoundTy {
1402 fn from(var: BoundVar) -> Self {
1405 kind: BoundTyKind::Anon,
1410 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1411 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash,
1412 Debug, RustcEncodable, RustcDecodable, HashStable)]
1413 pub struct ExistentialProjection<'tcx> {
1414 pub item_def_id: DefId,
1415 pub substs: SubstsRef<'tcx>,
1419 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1421 impl<'tcx> ExistentialProjection<'tcx> {
1422 /// Extracts the underlying existential trait reference from this projection.
1423 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1424 /// then this function would return a `exists T. T: Iterator` existential trait
1426 pub fn trait_ref(&self, tcx: TyCtxt<'_>) -> ty::ExistentialTraitRef<'tcx> {
1427 let def_id = tcx.associated_item(self.item_def_id).container.id();
1428 ty::ExistentialTraitRef{
1430 substs: self.substs,
1434 pub fn with_self_ty(
1438 ) -> ty::ProjectionPredicate<'tcx> {
1439 // otherwise the escaping regions would be captured by the binders
1440 debug_assert!(!self_ty.has_escaping_bound_vars());
1442 ty::ProjectionPredicate {
1443 projection_ty: ty::ProjectionTy {
1444 item_def_id: self.item_def_id,
1445 substs: tcx.mk_substs_trait(self_ty, self.substs),
1452 impl<'tcx> PolyExistentialProjection<'tcx> {
1453 pub fn with_self_ty(
1457 ) -> ty::PolyProjectionPredicate<'tcx> {
1458 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1461 pub fn item_def_id(&self) -> DefId {
1462 return self.skip_binder().item_def_id;
1466 impl DebruijnIndex {
1467 /// Returns the resulting index when this value is moved into
1468 /// `amount` number of new binders. So, e.g., if you had
1470 /// for<'a> fn(&'a x)
1472 /// and you wanted to change it to
1474 /// for<'a> fn(for<'b> fn(&'a x))
1476 /// you would need to shift the index for `'a` into a new binder.
1478 pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
1479 DebruijnIndex::from_u32(self.as_u32() + amount)
1482 /// Update this index in place by shifting it "in" through
1483 /// `amount` number of binders.
1484 pub fn shift_in(&mut self, amount: u32) {
1485 *self = self.shifted_in(amount);
1488 /// Returns the resulting index when this value is moved out from
1489 /// `amount` number of new binders.
1491 pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
1492 DebruijnIndex::from_u32(self.as_u32() - amount)
1495 /// Update in place by shifting out from `amount` binders.
1496 pub fn shift_out(&mut self, amount: u32) {
1497 *self = self.shifted_out(amount);
1500 /// Adjusts any De Bruijn indices so as to make `to_binder` the
1501 /// innermost binder. That is, if we have something bound at `to_binder`,
1502 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1503 /// when moving a region out from inside binders:
1506 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1507 /// // Binder: D3 D2 D1 ^^
1510 /// Here, the region `'a` would have the De Bruijn index D3,
1511 /// because it is the bound 3 binders out. However, if we wanted
1512 /// to refer to that region `'a` in the second argument (the `_`),
1513 /// those two binders would not be in scope. In that case, we
1514 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1515 /// De Bruijn index of `'a` to D1 (the innermost binder).
1517 /// If we invoke `shift_out_to_binder` and the region is in fact
1518 /// bound by one of the binders we are shifting out of, that is an
1519 /// error (and should fail an assertion failure).
1520 pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
1521 self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
1525 impl_stable_hash_for!(struct DebruijnIndex { private });
1527 /// Region utilities
1529 /// Is this region named by the user?
1530 pub fn has_name(&self) -> bool {
1532 RegionKind::ReEarlyBound(ebr) => ebr.has_name(),
1533 RegionKind::ReLateBound(_, br) => br.is_named(),
1534 RegionKind::ReFree(fr) => fr.bound_region.is_named(),
1535 RegionKind::ReScope(..) => false,
1536 RegionKind::ReStatic => true,
1537 RegionKind::ReVar(..) => false,
1538 RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(),
1539 RegionKind::ReEmpty => false,
1540 RegionKind::ReErased => false,
1541 RegionKind::ReClosureBound(..) => false,
1545 pub fn is_late_bound(&self) -> bool {
1547 ty::ReLateBound(..) => true,
1552 pub fn is_placeholder(&self) -> bool {
1554 ty::RePlaceholder(..) => true,
1559 pub fn bound_at_or_above_binder(&self, index: DebruijnIndex) -> bool {
1561 ty::ReLateBound(debruijn, _) => debruijn >= index,
1566 /// Adjusts any De Bruijn indices so as to make `to_binder` the
1567 /// innermost binder. That is, if we have something bound at `to_binder`,
1568 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1569 /// when moving a region out from inside binders:
1572 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1573 /// // Binder: D3 D2 D1 ^^
1576 /// Here, the region `'a` would have the De Bruijn index D3,
1577 /// because it is the bound 3 binders out. However, if we wanted
1578 /// to refer to that region `'a` in the second argument (the `_`),
1579 /// those two binders would not be in scope. In that case, we
1580 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1581 /// De Bruijn index of `'a` to D1 (the innermost binder).
1583 /// If we invoke `shift_out_to_binder` and the region is in fact
1584 /// bound by one of the binders we are shifting out of, that is an
1585 /// error (and should fail an assertion failure).
1586 pub fn shifted_out_to_binder(&self, to_binder: ty::DebruijnIndex) -> RegionKind {
1588 ty::ReLateBound(debruijn, r) => ty::ReLateBound(
1589 debruijn.shifted_out_to_binder(to_binder),
1596 pub fn keep_in_local_tcx(&self) -> bool {
1597 if let ty::ReVar(..) = self {
1604 pub fn type_flags(&self) -> TypeFlags {
1605 let mut flags = TypeFlags::empty();
1607 if self.keep_in_local_tcx() {
1608 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1613 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1614 flags = flags | TypeFlags::HAS_RE_INFER;
1616 ty::RePlaceholder(..) => {
1617 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1618 flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
1620 ty::ReLateBound(..) => {
1621 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1623 ty::ReEarlyBound(..) => {
1624 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1625 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1630 ty::ReScope { .. } => {
1631 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1635 ty::ReClosureBound(..) => {
1636 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1641 ty::ReStatic | ty::ReEmpty | ty::ReErased | ty::ReLateBound(..) => (),
1642 _ => flags = flags | TypeFlags::HAS_FREE_LOCAL_NAMES,
1645 debug!("type_flags({:?}) = {:?}", self, flags);
1650 /// Given an early-bound or free region, returns the `DefId` where it was bound.
1651 /// For example, consider the regions in this snippet of code:
1655 /// ^^ -- early bound, declared on an impl
1657 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1658 /// ^^ ^^ ^ anonymous, late-bound
1659 /// | early-bound, appears in where-clauses
1660 /// late-bound, appears only in fn args
1665 /// Here, `free_region_binding_scope('a)` would return the `DefId`
1666 /// of the impl, and for all the other highlighted regions, it
1667 /// would return the `DefId` of the function. In other cases (not shown), this
1668 /// function might return the `DefId` of a closure.
1669 pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_>) -> DefId {
1671 ty::ReEarlyBound(br) => {
1672 tcx.parent(br.def_id).unwrap()
1674 ty::ReFree(fr) => fr.scope,
1675 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1681 impl<'tcx> TyS<'tcx> {
1683 pub fn is_unit(&self) -> bool {
1685 Tuple(ref tys) => tys.is_empty(),
1691 pub fn is_never(&self) -> bool {
1698 /// Checks whether a type is definitely uninhabited. This is
1699 /// conservative: for some types that are uninhabited we return `false`,
1700 /// but we only return `true` for types that are definitely uninhabited.
1701 /// `ty.conservative_is_privately_uninhabited` implies that any value of type `ty`
1702 /// will be `Abi::Uninhabited`. (Note that uninhabited types may have nonzero
1703 /// size, to account for partial initialisation. See #49298 for details.)
1704 pub fn conservative_is_privately_uninhabited(&self, tcx: TyCtxt<'tcx>) -> bool {
1705 // FIXME(varkor): we can make this less conversative by substituting concrete
1709 ty::Adt(def, _) if def.is_union() => {
1710 // For now, `union`s are never considered uninhabited.
1713 ty::Adt(def, _) => {
1714 // Any ADT is uninhabited if either:
1715 // (a) It has no variants (i.e. an empty `enum`);
1716 // (b) Each of its variants (a single one in the case of a `struct`) has at least
1717 // one uninhabited field.
1718 def.variants.iter().all(|var| {
1719 var.fields.iter().any(|field| {
1720 tcx.type_of(field.did).conservative_is_privately_uninhabited(tcx)
1724 ty::Tuple(tys) => tys.iter().any(|ty| {
1725 ty.expect_ty().conservative_is_privately_uninhabited(tcx)
1727 ty::Array(ty, len) => {
1728 match len.assert_usize(tcx) {
1729 // If the array is definitely non-empty, it's uninhabited if
1730 // the type of its elements is uninhabited.
1731 Some(n) if n != 0 => ty.conservative_is_privately_uninhabited(tcx),
1736 // References to uninitialised memory is valid for any type, including
1737 // uninhabited types, in unsafe code, so we treat all references as
1746 pub fn is_primitive(&self) -> bool {
1748 Bool | Char | Int(_) | Uint(_) | Float(_) => true,
1754 pub fn is_ty_var(&self) -> bool {
1756 Infer(TyVar(_)) => true,
1762 pub fn is_ty_infer(&self) -> bool {
1770 pub fn is_phantom_data(&self) -> bool {
1771 if let Adt(def, _) = self.sty {
1772 def.is_phantom_data()
1779 pub fn is_bool(&self) -> bool { self.sty == Bool }
1782 pub fn is_param(&self, index: u32) -> bool {
1784 ty::Param(ref data) => data.index == index,
1790 pub fn is_self(&self) -> bool {
1792 Param(ref p) => p.is_self(),
1798 pub fn is_slice(&self) -> bool {
1800 RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => match ty.sty {
1801 Slice(_) | Str => true,
1809 pub fn is_simd(&self) -> bool {
1811 Adt(def, _) => def.repr.simd(),
1816 pub fn sequence_element_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1818 Array(ty, _) | Slice(ty) => ty,
1819 Str => tcx.mk_mach_uint(ast::UintTy::U8),
1820 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1824 pub fn simd_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1826 Adt(def, substs) => {
1827 def.non_enum_variant().fields[0].ty(tcx, substs)
1829 _ => bug!("simd_type called on invalid type")
1833 pub fn simd_size(&self, _cx: TyCtxt<'_>) -> usize {
1835 Adt(def, _) => def.non_enum_variant().fields.len(),
1836 _ => bug!("simd_size called on invalid type")
1841 pub fn is_region_ptr(&self) -> bool {
1849 pub fn is_mutable_pointer(&self) -> bool {
1851 RawPtr(TypeAndMut { mutbl: hir::Mutability::MutMutable, .. }) |
1852 Ref(_, _, hir::Mutability::MutMutable) => true,
1858 pub fn is_unsafe_ptr(&self) -> bool {
1860 RawPtr(_) => return true,
1865 /// Returns `true` if this type is an `Arc<T>`.
1867 pub fn is_arc(&self) -> bool {
1869 Adt(def, _) => def.is_arc(),
1874 /// Returns `true` if this type is an `Rc<T>`.
1876 pub fn is_rc(&self) -> bool {
1878 Adt(def, _) => def.is_rc(),
1884 pub fn is_box(&self) -> bool {
1886 Adt(def, _) => def.is_box(),
1891 /// panics if called on any type other than `Box<T>`
1892 pub fn boxed_ty(&self) -> Ty<'tcx> {
1894 Adt(def, substs) if def.is_box() => substs.type_at(0),
1895 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1899 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1900 /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1901 /// contents are abstract to rustc.)
1903 pub fn is_scalar(&self) -> bool {
1905 Bool | Char | Int(_) | Float(_) | Uint(_) |
1906 Infer(IntVar(_)) | Infer(FloatVar(_)) |
1907 FnDef(..) | FnPtr(_) | RawPtr(_) => true,
1912 /// Returns `true` if this type is a floating point type.
1914 pub fn is_floating_point(&self) -> bool {
1917 Infer(FloatVar(_)) => true,
1923 pub fn is_trait(&self) -> bool {
1925 Dynamic(..) => true,
1931 pub fn is_enum(&self) -> bool {
1933 Adt(adt_def, _) => {
1941 pub fn is_closure(&self) -> bool {
1943 Closure(..) => true,
1949 pub fn is_generator(&self) -> bool {
1951 Generator(..) => true,
1957 pub fn is_integral(&self) -> bool {
1959 Infer(IntVar(_)) | Int(_) | Uint(_) => true,
1965 pub fn is_fresh_ty(&self) -> bool {
1967 Infer(FreshTy(_)) => true,
1973 pub fn is_fresh(&self) -> bool {
1975 Infer(FreshTy(_)) => true,
1976 Infer(FreshIntTy(_)) => true,
1977 Infer(FreshFloatTy(_)) => true,
1983 pub fn is_char(&self) -> bool {
1991 pub fn is_numeric(&self) -> bool {
1992 self.is_integral() || self.is_floating_point()
1996 pub fn is_signed(&self) -> bool {
2004 pub fn is_pointer_sized(&self) -> bool {
2006 Int(ast::IntTy::Isize) | Uint(ast::UintTy::Usize) => true,
2012 pub fn is_machine(&self) -> bool {
2014 Int(..) | Uint(..) | Float(..) => true,
2020 pub fn has_concrete_skeleton(&self) -> bool {
2022 Param(_) | Infer(_) | Error => false,
2027 /// Returns the type and mutability of `*ty`.
2029 /// The parameter `explicit` indicates if this is an *explicit* dereference.
2030 /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
2031 pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
2033 Adt(def, _) if def.is_box() => {
2035 ty: self.boxed_ty(),
2036 mutbl: hir::MutImmutable,
2039 Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
2040 RawPtr(mt) if explicit => Some(mt),
2045 /// Returns the type of `ty[i]`.
2046 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
2048 Array(ty, _) | Slice(ty) => Some(ty),
2053 pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
2055 FnDef(def_id, substs) => {
2056 tcx.fn_sig(def_id).subst(tcx, substs)
2059 Error => { // ignore errors (#54954)
2060 ty::Binder::dummy(FnSig::fake())
2062 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
2067 pub fn is_fn(&self) -> bool {
2069 FnDef(..) | FnPtr(_) => true,
2075 pub fn is_fn_ptr(&self) -> bool {
2083 pub fn is_impl_trait(&self) -> bool {
2091 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
2093 Adt(adt, _) => Some(adt),
2098 /// If the type contains variants, returns the valid range of variant indices.
2099 /// FIXME This requires the optimized MIR in the case of generators.
2101 pub fn variant_range(&self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
2103 TyKind::Adt(adt, _) => Some(adt.variant_range()),
2104 TyKind::Generator(def_id, substs, _) => Some(substs.variant_range(def_id, tcx)),
2109 /// If the type contains variants, returns the variant for `variant_index`.
2110 /// Panics if `variant_index` is out of range.
2111 /// FIXME This requires the optimized MIR in the case of generators.
2113 pub fn discriminant_for_variant(
2116 variant_index: VariantIdx,
2117 ) -> Option<Discr<'tcx>> {
2119 TyKind::Adt(adt, _) => Some(adt.discriminant_for_variant(tcx, variant_index)),
2120 TyKind::Generator(def_id, substs, _) =>
2121 Some(substs.discriminant_for_variant(def_id, tcx, variant_index)),
2126 /// Push onto `out` the regions directly referenced from this type (but not
2127 /// types reachable from this type via `walk_tys`). This ignores late-bound
2128 /// regions binders.
2129 pub fn push_regions(&self, out: &mut SmallVec<[ty::Region<'tcx>; 4]>) {
2131 Ref(region, _, _) => {
2134 Dynamic(ref obj, region) => {
2136 if let Some(principal) = obj.principal() {
2137 out.extend(principal.skip_binder().substs.regions());
2140 Adt(_, substs) | Opaque(_, substs) => {
2141 out.extend(substs.regions())
2143 Closure(_, ClosureSubsts { ref substs }) |
2144 Generator(_, GeneratorSubsts { ref substs }, _) => {
2145 out.extend(substs.regions())
2147 Projection(ref data) | UnnormalizedProjection(ref data) => {
2148 out.extend(data.substs.regions())
2152 GeneratorWitness(..) |
2173 /// When we create a closure, we record its kind (i.e., what trait
2174 /// it implements) into its `ClosureSubsts` using a type
2175 /// parameter. This is kind of a phantom type, except that the
2176 /// most convenient thing for us to are the integral types. This
2177 /// function converts such a special type into the closure
2178 /// kind. To go the other way, use
2179 /// `tcx.closure_kind_ty(closure_kind)`.
2181 /// Note that during type checking, we use an inference variable
2182 /// to represent the closure kind, because it has not yet been
2183 /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
2184 /// is complete, that type variable will be unified.
2185 pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
2187 Int(int_ty) => match int_ty {
2188 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
2189 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
2190 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
2191 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2196 Error => Some(ty::ClosureKind::Fn),
2198 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2202 /// Fast path helper for testing if a type is `Sized`.
2204 /// Returning true means the type is known to be sized. Returning
2205 /// `false` means nothing -- could be sized, might not be.
2206 pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool {
2208 ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
2209 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
2210 ty::FnDef(..) | ty::FnPtr(_) | ty::RawPtr(..) |
2211 ty::Char | ty::Ref(..) | ty::Generator(..) |
2212 ty::GeneratorWitness(..) | ty::Array(..) | ty::Closure(..) |
2213 ty::Never | ty::Error =>
2216 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) =>
2220 tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx))
2223 ty::Adt(def, _substs) =>
2224 def.sized_constraint(tcx).is_empty(),
2226 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
2228 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
2230 ty::Infer(ty::TyVar(_)) => false,
2233 ty::Placeholder(..) |
2234 ty::Infer(ty::FreshTy(_)) |
2235 ty::Infer(ty::FreshIntTy(_)) |
2236 ty::Infer(ty::FreshFloatTy(_)) =>
2237 bug!("is_trivially_sized applied to unexpected type: {:?}", self),
2242 /// Typed constant value.
2243 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable,
2244 Eq, PartialEq, Ord, PartialOrd, HashStable)]
2245 pub struct Const<'tcx> {
2248 pub val: ConstValue<'tcx>,
2251 #[cfg(target_arch = "x86_64")]
2252 static_assert_size!(Const<'_>, 40);
2254 impl<'tcx> Const<'tcx> {
2256 pub fn from_scalar(tcx: TyCtxt<'tcx>, val: Scalar, ty: Ty<'tcx>) -> &'tcx Self {
2258 val: ConstValue::Scalar(val),
2264 pub fn from_bits(tcx: TyCtxt<'tcx>, bits: u128, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> &'tcx Self {
2265 let ty = tcx.lift_to_global(&ty).unwrap();
2266 let size = tcx.layout_of(ty).unwrap_or_else(|e| {
2267 panic!("could not compute layout for {:?}: {:?}", ty, e)
2269 Self::from_scalar(tcx, Scalar::from_uint(bits, size), ty.value)
2273 pub fn zero_sized(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
2274 Self::from_scalar(tcx, Scalar::zst(), ty)
2278 pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> &'tcx Self {
2279 Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
2283 pub fn from_usize(tcx: TyCtxt<'tcx>, n: u64) -> &'tcx Self {
2284 Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
2288 pub fn to_bits(&self, tcx: TyCtxt<'tcx>, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> Option<u128> {
2289 if self.ty != ty.value {
2292 let ty = tcx.lift_to_global(&ty).unwrap();
2293 let size = tcx.layout_of(ty).ok()?.size;
2294 self.val.try_to_bits(size)
2298 pub fn to_ptr(&self) -> Option<Pointer> {
2299 self.val.try_to_ptr()
2303 pub fn assert_bits(&self, tcx: TyCtxt<'_>, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> Option<u128> {
2304 assert_eq!(self.ty, ty.value);
2305 let ty = tcx.lift_to_global(&ty).unwrap();
2306 let size = tcx.layout_of(ty).ok()?.size;
2307 self.val.try_to_bits(size)
2311 pub fn assert_bool(&self, tcx: TyCtxt<'_>) -> Option<bool> {
2312 self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.bool)).and_then(|v| match v {
2320 pub fn assert_usize(&self, tcx: TyCtxt<'_>) -> Option<u64> {
2321 self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.usize)).map(|v| v as u64)
2325 pub fn unwrap_bits(&self, tcx: TyCtxt<'_>, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> u128 {
2326 self.assert_bits(tcx, ty).unwrap_or_else(||
2327 bug!("expected bits of {}, got {:#?}", ty.value, self))
2331 pub fn unwrap_usize(&self, tcx: TyCtxt<'_>) -> u64 {
2332 self.assert_usize(tcx).unwrap_or_else(||
2333 bug!("expected constant usize, got {:#?}", self))
2337 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}
2339 /// An inference variable for a const, for use in const generics.
2340 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd,
2341 Ord, RustcEncodable, RustcDecodable, Hash, HashStable)]
2342 pub enum InferConst<'tcx> {
2343 /// Infer the value of the const.
2344 Var(ConstVid<'tcx>),
2345 /// A fresh const variable. See `infer::freshen` for more details.
2347 /// Canonicalized const variable, used only when preparing a trait query.
2348 Canonical(DebruijnIndex, BoundVar),