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, truncate};
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, DefIdTree, TypeFlags, Ty, TyCtxt, TypeFoldable};
13 use crate::ty::{List, TyS, ParamEnvAnd, ParamEnv};
14 use crate::util::captures::Captures;
15 use crate::mir::interpret::{Scalar, Pointer};
17 use smallvec::SmallVec;
19 use std::cmp::Ordering;
20 use std::marker::PhantomData;
21 use rustc_target::spec::abi;
22 use syntax::ast::{self, Ident};
23 use syntax::symbol::{keywords, InternedString};
29 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
30 Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
31 pub struct TypeAndMut<'tcx> {
33 pub mutbl: hir::Mutability,
36 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
37 RustcEncodable, RustcDecodable, Copy, HashStable)]
38 /// A "free" region `fr` can be interpreted as "some region
39 /// at least as big as the scope `fr.scope`".
40 pub struct FreeRegion {
42 pub bound_region: BoundRegion,
45 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
46 RustcEncodable, RustcDecodable, Copy, HashStable)]
47 pub enum BoundRegion {
48 /// An anonymous region parameter for a given fn (&T)
51 /// Named region parameters for functions (a in &'a T)
53 /// The `DefId` is needed to distinguish free regions in
54 /// the event of shadowing.
55 BrNamed(DefId, InternedString),
57 /// Fresh bound identifiers created during GLB computations.
60 /// Anonymous region for the implicit env pointer parameter
66 pub fn is_named(&self) -> bool {
68 BoundRegion::BrNamed(..) => true,
73 /// When canonicalizing, we replace unbound inference variables and free
74 /// regions with anonymous late bound regions. This method asserts that
75 /// we have an anonymous late bound region, which hence may refer to
76 /// a canonical variable.
77 pub fn assert_bound_var(&self) -> BoundVar {
79 BoundRegion::BrAnon(var) => BoundVar::from_u32(var),
80 _ => bug!("bound region is not anonymous"),
85 /// N.B., if you change this, you'll probably want to change the corresponding
86 /// AST structure in `libsyntax/ast.rs` as well.
87 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
88 RustcEncodable, RustcDecodable, HashStable, Debug)]
89 pub enum TyKind<'tcx> {
90 /// The primitive boolean type. Written as `bool`.
93 /// The primitive character type; holds a Unicode scalar value
94 /// (a non-surrogate code point). Written as `char`.
97 /// A primitive signed integer type. For example, `i32`.
100 /// A primitive unsigned integer type. For example, `u32`.
103 /// A primitive floating-point type. For example, `f64`.
106 /// Structures, enumerations and unions.
108 /// InternalSubsts here, possibly against intuition, *may* contain `Param`s.
109 /// That is, even after substitution it is possible that there are type
110 /// variables. This happens when the `Adt` corresponds to an ADT
111 /// definition and not a concrete use of it.
112 Adt(&'tcx AdtDef, SubstsRef<'tcx>),
114 /// An unsized FFI type that is opaque to Rust. Written as `extern type T`.
117 /// The pointee of a string slice. Written as `str`.
120 /// An array with the given length. Written as `[T; n]`.
121 Array(Ty<'tcx>, &'tcx ty::Const<'tcx>),
123 /// The pointee of an array slice. Written as `[T]`.
126 /// A raw pointer. Written as `*mut T` or `*const T`
127 RawPtr(TypeAndMut<'tcx>),
129 /// A reference; a pointer with an associated lifetime. Written as
130 /// `&'a mut T` or `&'a T`.
131 Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability),
133 /// The anonymous type of a function declaration/definition. Each
134 /// function has a unique type, which is output (for a function
135 /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
137 /// For example the type of `bar` here:
140 /// fn foo() -> i32 { 1 }
141 /// let bar = foo; // bar: fn() -> i32 {foo}
143 FnDef(DefId, SubstsRef<'tcx>),
145 /// A pointer to a function. Written as `fn() -> i32`.
147 /// For example the type of `bar` here:
150 /// fn foo() -> i32 { 1 }
151 /// let bar: fn() -> i32 = foo;
153 FnPtr(PolyFnSig<'tcx>),
155 /// A trait, defined with `trait`.
156 Dynamic(Binder<&'tcx List<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
158 /// The anonymous type of a closure. Used to represent the type of
160 Closure(DefId, ClosureSubsts<'tcx>),
162 /// The anonymous type of a generator. Used to represent the type of
164 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
166 /// A type representin the types stored inside a generator.
167 /// This should only appear in GeneratorInteriors.
168 GeneratorWitness(Binder<&'tcx List<Ty<'tcx>>>),
170 /// The never type `!`
173 /// A tuple type. For example, `(i32, bool)`.
174 Tuple(SubstsRef<'tcx>),
176 /// The projection of an associated type. For example,
177 /// `<T as Trait<..>>::N`.
178 Projection(ProjectionTy<'tcx>),
180 /// A placeholder type used when we do not have enough information
181 /// to normalize the projection of an associated type to an
182 /// existing concrete type. Currently only used with chalk-engine.
183 UnnormalizedProjection(ProjectionTy<'tcx>),
185 /// Opaque (`impl Trait`) type found in a return type.
186 /// The `DefId` comes either from
187 /// * the `impl Trait` ast::Ty node,
188 /// * or the `existential type` declaration
189 /// The substitutions are for the generics of the function in question.
190 /// After typeck, the concrete type can be found in the `types` map.
191 Opaque(DefId, SubstsRef<'tcx>),
193 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
196 /// Bound type variable, used only when preparing a trait query.
197 Bound(ty::DebruijnIndex, BoundTy),
199 /// A placeholder type - universally quantified higher-ranked type.
200 Placeholder(ty::PlaceholderType),
202 /// A type variable used during type checking.
205 /// A placeholder for a type which could not be computed; this is
206 /// propagated to avoid useless error messages.
210 // `TyKind` is used a lot. Make sure it doesn't unintentionally get bigger.
211 #[cfg(target_arch = "x86_64")]
212 static_assert!(MEM_SIZE_OF_TY_KIND: ::std::mem::size_of::<TyKind<'_>>() == 24);
214 /// A closure can be modeled as a struct that looks like:
216 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
224 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
225 /// in scope on the function that defined the closure,
226 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
227 /// is rather hackily encoded via a scalar type. See
228 /// `TyS::to_opt_closure_kind` for details.
229 /// - CS represents the *closure signature*, representing as a `fn()`
230 /// type. For example, `fn(u32, u32) -> u32` would mean that the closure
231 /// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
233 /// - U0...Uk are type parameters representing the types of its upvars
234 /// (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
235 /// and the up-var has the type `Foo`, then `Ui = &Foo`).
237 /// So, for example, given this function:
239 /// fn foo<'a, T>(data: &'a mut T) {
240 /// do(|| data.count += 1)
243 /// the type of the closure would be something like:
245 /// struct Closure<'a, T, U0> {
249 /// Note that the type of the upvar is not specified in the struct.
250 /// You may wonder how the impl would then be able to use the upvar,
251 /// if it doesn't know it's type? The answer is that the impl is
252 /// (conceptually) not fully generic over Closure but rather tied to
253 /// instances with the expected upvar types:
255 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
259 /// You can see that the *impl* fully specified the type of the upvar
260 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
261 /// (Here, I am assuming that `data` is mut-borrowed.)
263 /// Now, the last question you may ask is: Why include the upvar types
264 /// as extra type parameters? The reason for this design is that the
265 /// upvar types can reference lifetimes that are internal to the
266 /// creating function. In my example above, for example, the lifetime
267 /// `'b` represents the scope of the closure itself; this is some
268 /// subset of `foo`, probably just the scope of the call to the to
269 /// `do()`. If we just had the lifetime/type parameters from the
270 /// enclosing function, we couldn't name this lifetime `'b`. Note that
271 /// there can also be lifetimes in the types of the upvars themselves,
272 /// if one of them happens to be a reference to something that the
273 /// creating fn owns.
275 /// OK, you say, so why not create a more minimal set of parameters
276 /// that just includes the extra lifetime parameters? The answer is
277 /// primarily that it would be hard --- we don't know at the time when
278 /// we create the closure type what the full types of the upvars are,
279 /// nor do we know which are borrowed and which are not. In this
280 /// design, we can just supply a fresh type parameter and figure that
283 /// All right, you say, but why include the type parameters from the
284 /// original function then? The answer is that codegen may need them
285 /// when monomorphizing, and they may not appear in the upvars. A
286 /// closure could capture no variables but still make use of some
287 /// in-scope type parameter with a bound (e.g., if our example above
288 /// had an extra `U: Default`, and the closure called `U::default()`).
290 /// There is another reason. This design (implicitly) prohibits
291 /// closures from capturing themselves (except via a trait
292 /// object). This simplifies closure inference considerably, since it
293 /// means that when we infer the kind of a closure or its upvars, we
294 /// don't have to handle cycles where the decisions we make for
295 /// closure C wind up influencing the decisions we ought to make for
296 /// closure C (which would then require fixed point iteration to
297 /// handle). Plus it fixes an ICE. :P
301 /// Perhaps surprisingly, `ClosureSubsts` are also used for
302 /// generators. In that case, what is written above is only half-true
303 /// -- the set of type parameters is similar, but the role of CK and
304 /// CS are different. CK represents the "yield type" and CS
305 /// represents the "return type" of the generator.
307 /// It'd be nice to split this struct into ClosureSubsts and
308 /// GeneratorSubsts, I believe. -nmatsakis
309 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
310 Debug, RustcEncodable, RustcDecodable, HashStable)]
311 pub struct ClosureSubsts<'tcx> {
312 /// Lifetime and type parameters from the enclosing function,
313 /// concatenated with the types of the upvars.
315 /// These are separated out because codegen wants to pass them around
316 /// when monomorphizing.
317 pub substs: SubstsRef<'tcx>,
320 /// Struct returned by `split()`. Note that these are subslices of the
321 /// parent slice and not canonical substs themselves.
322 struct SplitClosureSubsts<'tcx> {
323 closure_kind_ty: Ty<'tcx>,
324 closure_sig_ty: Ty<'tcx>,
325 upvar_kinds: &'tcx [Kind<'tcx>],
328 impl<'tcx> ClosureSubsts<'tcx> {
329 /// Divides the closure substs into their respective
330 /// components. Single source of truth with respect to the
332 fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitClosureSubsts<'tcx> {
333 let generics = tcx.generics_of(def_id);
334 let parent_len = generics.parent_count;
336 closure_kind_ty: self.substs.type_at(parent_len),
337 closure_sig_ty: self.substs.type_at(parent_len + 1),
338 upvar_kinds: &self.substs[parent_len + 2..],
343 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
344 impl Iterator<Item=Ty<'tcx>> + 'tcx
346 let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
347 upvar_kinds.iter().map(|t| {
348 if let UnpackedKind::Type(ty) = t.unpack() {
351 bug!("upvar should be type")
356 /// Returns the closure kind for this closure; may return a type
357 /// variable during inference. To get the closure kind during
358 /// inference, use `infcx.closure_kind(def_id, substs)`.
359 pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
360 self.split(def_id, tcx).closure_kind_ty
363 /// Returns the type representing the closure signature for this
364 /// closure; may contain type variables during inference. To get
365 /// the closure signature during inference, use
366 /// `infcx.fn_sig(def_id)`.
367 pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
368 self.split(def_id, tcx).closure_sig_ty
371 /// Returns the closure kind for this closure; only usable outside
372 /// of an inference context, because in that context we know that
373 /// there are no type variables.
375 /// If you have an inference context, use `infcx.closure_kind()`.
376 pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::ClosureKind {
377 self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
380 /// Extracts the signature from the closure; only usable outside
381 /// of an inference context, because in that context we know that
382 /// there are no type variables.
384 /// If you have an inference context, use `infcx.closure_sig()`.
385 pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
386 let ty = self.closure_sig_ty(def_id, tcx);
388 ty::FnPtr(sig) => sig,
389 _ => bug!("closure_sig_ty is not a fn-ptr: {:?}", ty),
394 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug,
395 RustcEncodable, RustcDecodable, HashStable)]
396 pub struct GeneratorSubsts<'tcx> {
397 pub substs: SubstsRef<'tcx>,
400 struct SplitGeneratorSubsts<'tcx> {
404 upvar_kinds: &'tcx [Kind<'tcx>],
407 impl<'tcx> GeneratorSubsts<'tcx> {
408 fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitGeneratorSubsts<'tcx> {
409 let generics = tcx.generics_of(def_id);
410 let parent_len = generics.parent_count;
411 SplitGeneratorSubsts {
412 yield_ty: self.substs.type_at(parent_len),
413 return_ty: self.substs.type_at(parent_len + 1),
414 witness: self.substs.type_at(parent_len + 2),
415 upvar_kinds: &self.substs[parent_len + 3..],
419 /// This describes the types that can be contained in a generator.
420 /// It will be a type variable initially and unified in the last stages of typeck of a body.
421 /// It contains a tuple of all the types that could end up on a generator frame.
422 /// The state transformation MIR pass may only produce layouts which mention types
423 /// in this tuple. Upvars are not counted here.
424 pub fn witness(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
425 self.split(def_id, tcx).witness
429 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
430 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<'a, 'gcx, 'tcx> GeneratorSubsts<'tcx> {
473 /// This returns the types of the MIR locals which had to be stored across suspension points.
474 /// It is calculated in rustc_mir::transform::generator::StateTransform.
475 /// All the types here must be in the tuple in GeneratorInterior.
479 tcx: TyCtxt<'a, 'gcx, 'tcx>,
480 ) -> impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a {
481 let state = tcx.generator_layout(def_id).fields.iter();
482 state.map(move |d| d.ty.subst(tcx, self.substs))
485 /// This is the types of the fields of a generate which
486 /// is available before the generator transformation.
487 /// It includes the upvars and the state discriminant which is u32.
488 pub fn pre_transforms_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
489 impl Iterator<Item=Ty<'tcx>> + 'a
491 self.upvar_tys(def_id, tcx).chain(iter::once(tcx.types.u32))
494 /// This is the types of all the fields stored in a generator.
495 /// It includes the upvars, state types and the state discriminant which is u32.
496 pub fn field_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
497 impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a
499 self.pre_transforms_tys(def_id, tcx).chain(self.state_tys(def_id, tcx))
503 #[derive(Debug, Copy, Clone)]
504 pub enum UpvarSubsts<'tcx> {
505 Closure(ClosureSubsts<'tcx>),
506 Generator(GeneratorSubsts<'tcx>),
509 impl<'tcx> UpvarSubsts<'tcx> {
511 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
512 impl Iterator<Item=Ty<'tcx>> + 'tcx
514 let upvar_kinds = match self {
515 UpvarSubsts::Closure(substs) => substs.split(def_id, tcx).upvar_kinds,
516 UpvarSubsts::Generator(substs) => substs.split(def_id, tcx).upvar_kinds,
518 upvar_kinds.iter().map(|t| {
519 if let UnpackedKind::Type(ty) = t.unpack() {
522 bug!("upvar should be type")
528 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash,
529 RustcEncodable, RustcDecodable, HashStable)]
530 pub enum ExistentialPredicate<'tcx> {
531 /// E.g., `Iterator`.
532 Trait(ExistentialTraitRef<'tcx>),
533 /// E.g., `Iterator::Item = T`.
534 Projection(ExistentialProjection<'tcx>),
539 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
540 /// Compares via an ordering that will not change if modules are reordered or other changes are
541 /// made to the tree. In particular, this ordering is preserved across incremental compilations.
542 pub fn stable_cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
543 use self::ExistentialPredicate::*;
544 match (*self, *other) {
545 (Trait(_), Trait(_)) => Ordering::Equal,
546 (Projection(ref a), Projection(ref b)) =>
547 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
548 (AutoTrait(ref a), AutoTrait(ref b)) =>
549 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
550 (Trait(_), _) => Ordering::Less,
551 (Projection(_), Trait(_)) => Ordering::Greater,
552 (Projection(_), _) => Ordering::Less,
553 (AutoTrait(_), _) => Ordering::Greater,
559 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
560 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
561 -> ty::Predicate<'tcx> {
562 use crate::ty::ToPredicate;
563 match *self.skip_binder() {
564 ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
565 ExistentialPredicate::Projection(p) =>
566 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
567 ExistentialPredicate::AutoTrait(did) => {
568 let trait_ref = Binder(ty::TraitRef {
570 substs: tcx.mk_substs_trait(self_ty, &[]),
572 trait_ref.to_predicate()
578 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx List<ExistentialPredicate<'tcx>> {}
580 impl<'tcx> List<ExistentialPredicate<'tcx>> {
581 /// Returns the "principal def id" of this set of existential predicates.
583 /// A Rust trait object type consists (in addition to a lifetime bound)
584 /// of a set of trait bounds, which are separated into any number
585 /// of auto-trait bounds, and at most 1 non-auto-trait bound. The
586 /// non-auto-trait bound is called the "principal" of the trait
589 /// Only the principal can have methods or type parameters (because
590 /// auto traits can have neither of them). This is important, because
591 /// it means the auto traits can be treated as an unordered set (methods
592 /// would force an order for the vtable, while relating traits with
593 /// type parameters without knowing the order to relate them in is
594 /// a rather non-trivial task).
596 /// For example, in the trait object `dyn fmt::Debug + Sync`, the
597 /// principal bound is `Some(fmt::Debug)`, while the auto-trait bounds
598 /// are the set `{Sync}`.
600 /// It is also possible to have a "trivial" trait object that
601 /// consists only of auto traits, with no principal - for example,
602 /// `dyn Send + Sync`. In that case, the set of auto-trait bounds
603 /// is `{Send, Sync}`, while there is no principal. These trait objects
604 /// have a "trivial" vtable consisting of just the size, alignment,
606 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
608 ExistentialPredicate::Trait(tr) => Some(tr),
613 pub fn principal_def_id(&self) -> Option<DefId> {
614 self.principal().map(|d| d.def_id)
618 pub fn projection_bounds<'a>(&'a self) ->
619 impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
620 self.iter().filter_map(|predicate| {
622 ExistentialPredicate::Projection(p) => Some(p),
629 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
630 self.iter().filter_map(|predicate| {
632 ExistentialPredicate::AutoTrait(d) => Some(d),
639 impl<'tcx> Binder<&'tcx List<ExistentialPredicate<'tcx>>> {
640 pub fn principal(&self) -> Option<ty::Binder<ExistentialTraitRef<'tcx>>> {
641 self.skip_binder().principal().map(Binder::bind)
644 pub fn principal_def_id(&self) -> Option<DefId> {
645 self.skip_binder().principal_def_id()
649 pub fn projection_bounds<'a>(&'a self) ->
650 impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
651 self.skip_binder().projection_bounds().map(Binder::bind)
655 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
656 self.skip_binder().auto_traits()
659 pub fn iter<'a>(&'a self)
660 -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
661 self.skip_binder().iter().cloned().map(Binder::bind)
665 /// A complete reference to a trait. These take numerous guises in syntax,
666 /// but perhaps the most recognizable form is in a where-clause:
670 /// This would be represented by a trait-reference where the `DefId` is the
671 /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0,
672 /// and `U` as parameter 1.
674 /// Trait references also appear in object types like `Foo<U>`, but in
675 /// that case the `Self` parameter is absent from the substitutions.
677 /// Note that a `TraitRef` introduces a level of region binding, to
678 /// account for higher-ranked trait bounds like `T: for<'a> Foo<&'a U>`
679 /// or higher-ranked object types.
680 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
681 pub struct TraitRef<'tcx> {
683 pub substs: SubstsRef<'tcx>,
686 impl<'tcx> TraitRef<'tcx> {
687 pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> {
688 TraitRef { def_id: def_id, substs: substs }
691 /// Returns a `TraitRef` of the form `P0: Foo<P1..Pn>` where `Pi`
692 /// are the parameters defined on trait.
693 pub fn identity<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, def_id: DefId) -> TraitRef<'tcx> {
696 substs: InternalSubsts::identity_for_item(tcx, def_id),
701 pub fn self_ty(&self) -> Ty<'tcx> {
702 self.substs.type_at(0)
705 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
706 // Select only the "input types" from a trait-reference. For
707 // now this is all the types that appear in the
708 // trait-reference, but it should eventually exclude
713 pub fn from_method(tcx: TyCtxt<'_, '_, 'tcx>,
715 substs: SubstsRef<'tcx>)
716 -> ty::TraitRef<'tcx> {
717 let defs = tcx.generics_of(trait_id);
721 substs: tcx.intern_substs(&substs[..defs.params.len()])
726 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
728 impl<'tcx> PolyTraitRef<'tcx> {
729 pub fn self_ty(&self) -> Ty<'tcx> {
730 self.skip_binder().self_ty()
733 pub fn def_id(&self) -> DefId {
734 self.skip_binder().def_id
737 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
738 // Note that we preserve binding levels
739 Binder(ty::TraitPredicate { trait_ref: self.skip_binder().clone() })
743 /// An existential reference to a trait, where `Self` is erased.
744 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
746 /// exists T. T: Trait<'a, 'b, X, Y>
748 /// The substitutions don't include the erased `Self`, only trait
749 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
750 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
751 RustcEncodable, RustcDecodable, HashStable)]
752 pub struct ExistentialTraitRef<'tcx> {
754 pub substs: SubstsRef<'tcx>,
757 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
758 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
759 // Select only the "input types" from a trait-reference. For
760 // now this is all the types that appear in the
761 // trait-reference, but it should eventually exclude
766 pub fn erase_self_ty(tcx: TyCtxt<'a, 'gcx, 'tcx>,
767 trait_ref: ty::TraitRef<'tcx>)
768 -> ty::ExistentialTraitRef<'tcx> {
769 // Assert there is a Self.
770 trait_ref.substs.type_at(0);
772 ty::ExistentialTraitRef {
773 def_id: trait_ref.def_id,
774 substs: tcx.intern_substs(&trait_ref.substs[1..])
778 /// Object types don't have a self type specified. Therefore, when
779 /// we convert the principal trait-ref into a normal trait-ref,
780 /// you must give *some* self type. A common choice is `mk_err()`
781 /// or some placeholder type.
782 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
783 -> ty::TraitRef<'tcx> {
784 // otherwise the escaping vars would be captured by the binder
785 // debug_assert!(!self_ty.has_escaping_bound_vars());
789 substs: tcx.mk_substs_trait(self_ty, self.substs)
794 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
796 impl<'tcx> PolyExistentialTraitRef<'tcx> {
797 pub fn def_id(&self) -> DefId {
798 self.skip_binder().def_id
801 /// Object types don't have a self type specified. Therefore, when
802 /// we convert the principal trait-ref into a normal trait-ref,
803 /// you must give *some* self type. A common choice is `mk_err()`
804 /// or some placeholder type.
805 pub fn with_self_ty(&self, tcx: TyCtxt<'_, '_, 'tcx>,
807 -> ty::PolyTraitRef<'tcx> {
808 self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
812 /// Binder is a binder for higher-ranked lifetimes or types. It is part of the
813 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
814 /// (which would be represented by the type `PolyTraitRef ==
815 /// Binder<TraitRef>`). Note that when we instantiate,
816 /// erase, or otherwise "discharge" these bound vars, we change the
817 /// type from `Binder<T>` to just `T` (see
818 /// e.g., `liberate_late_bound_regions`).
819 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
820 pub struct Binder<T>(T);
823 /// Wraps `value` in a binder, asserting that `value` does not
824 /// contain any bound vars that would be bound by the
825 /// binder. This is commonly used to 'inject' a value T into a
826 /// different binding level.
827 pub fn dummy<'tcx>(value: T) -> Binder<T>
828 where T: TypeFoldable<'tcx>
830 debug_assert!(!value.has_escaping_bound_vars());
834 /// Wraps `value` in a binder, binding higher-ranked vars (if any).
835 pub fn bind<'tcx>(value: T) -> Binder<T> {
839 /// Skips the binder and returns the "bound" value. This is a
840 /// risky thing to do because it's easy to get confused about
841 /// De Bruijn indices and the like. It is usually better to
842 /// discharge the binder using `no_bound_vars` or
843 /// `replace_late_bound_regions` or something like
844 /// that. `skip_binder` is only valid when you are either
845 /// extracting data that has nothing to do with bound vars, you
846 /// are doing some sort of test that does not involve bound
847 /// regions, or you are being very careful about your depth
850 /// Some examples where `skip_binder` is reasonable:
852 /// - extracting the `DefId` from a PolyTraitRef;
853 /// - comparing the self type of a PolyTraitRef to see if it is equal to
854 /// a type parameter `X`, since the type `X` does not reference any regions
855 pub fn skip_binder(&self) -> &T {
859 pub fn as_ref(&self) -> Binder<&T> {
863 pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
864 where F: FnOnce(&T) -> U
866 self.as_ref().map_bound(f)
869 pub fn map_bound<F, U>(self, f: F) -> Binder<U>
870 where F: FnOnce(T) -> U
875 /// Unwraps and returns the value within, but only if it contains
876 /// no bound vars at all. (In other words, if this binder --
877 /// and indeed any enclosing binder -- doesn't bind anything at
878 /// all.) Otherwise, returns `None`.
880 /// (One could imagine having a method that just unwraps a single
881 /// binder, but permits late-bound vars bound by enclosing
882 /// binders, but that would require adjusting the debruijn
883 /// indices, and given the shallow binding structure we often use,
884 /// would not be that useful.)
885 pub fn no_bound_vars<'tcx>(self) -> Option<T>
886 where T: TypeFoldable<'tcx>
888 if self.skip_binder().has_escaping_bound_vars() {
891 Some(self.skip_binder().clone())
895 /// Given two things that have the same binder level,
896 /// and an operation that wraps on their contents, executes the operation
897 /// and then wraps its result.
899 /// `f` should consider bound regions at depth 1 to be free, and
900 /// anything it produces with bound regions at depth 1 will be
901 /// bound in the resulting return value.
902 pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
903 where F: FnOnce(T, U) -> R
905 Binder(f(self.0, u.0))
908 /// Splits the contents into two things that share the same binder
909 /// level as the original, returning two distinct binders.
911 /// `f` should consider bound regions at depth 1 to be free, and
912 /// anything it produces with bound regions at depth 1 will be
913 /// bound in the resulting return values.
914 pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
915 where F: FnOnce(T) -> (U, V)
917 let (u, v) = f(self.0);
918 (Binder(u), Binder(v))
922 /// Represents the projection of an associated type. In explicit UFCS
923 /// form this would be written `<T as Trait<..>>::N`.
924 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord,
925 Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
926 pub struct ProjectionTy<'tcx> {
927 /// The parameters of the associated item.
928 pub substs: SubstsRef<'tcx>,
930 /// The `DefId` of the `TraitItem` for the associated type `N`.
932 /// Note that this is not the `DefId` of the `TraitRef` containing this
933 /// associated type, which is in `tcx.associated_item(item_def_id).container`.
934 pub item_def_id: DefId,
937 impl<'a, 'tcx> ProjectionTy<'tcx> {
938 /// Construct a `ProjectionTy` by searching the trait from `trait_ref` for the
939 /// associated item named `item_name`.
940 pub fn from_ref_and_name(
941 tcx: TyCtxt<'_, '_, '_>, trait_ref: ty::TraitRef<'tcx>, item_name: Ident
942 ) -> ProjectionTy<'tcx> {
943 let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
944 item.kind == ty::AssociatedKind::Type &&
945 tcx.hygienic_eq(item_name, item.ident, trait_ref.def_id)
949 substs: trait_ref.substs,
954 /// Extracts the underlying trait reference from this projection.
955 /// For example, if this is a projection of `<T as Iterator>::Item`,
956 /// then this function would return a `T: Iterator` trait reference.
957 pub fn trait_ref(&self, tcx: TyCtxt<'_, '_, '_>) -> ty::TraitRef<'tcx> {
958 let def_id = tcx.associated_item(self.item_def_id).container.id();
965 pub fn self_ty(&self) -> Ty<'tcx> {
966 self.substs.type_at(0)
970 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
971 pub struct GenSig<'tcx> {
972 pub yield_ty: Ty<'tcx>,
973 pub return_ty: Ty<'tcx>,
976 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
978 impl<'tcx> PolyGenSig<'tcx> {
979 pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
980 self.map_bound_ref(|sig| sig.yield_ty)
982 pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
983 self.map_bound_ref(|sig| sig.return_ty)
987 /// Signature of a function type, which I have arbitrarily
988 /// decided to use to refer to the input/output types.
990 /// - `inputs`: is the list of arguments and their modes.
991 /// - `output`: is the return type.
992 /// - `c_variadic`: indicates whether this is a C-variadic function.
993 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord,
994 Hash, RustcEncodable, RustcDecodable, HashStable)]
995 pub struct FnSig<'tcx> {
996 pub inputs_and_output: &'tcx List<Ty<'tcx>>,
997 pub c_variadic: bool,
998 pub unsafety: hir::Unsafety,
1002 impl<'tcx> FnSig<'tcx> {
1003 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
1004 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
1007 pub fn output(&self) -> Ty<'tcx> {
1008 self.inputs_and_output[self.inputs_and_output.len() - 1]
1011 // Create a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible method
1012 fn fake() -> FnSig<'tcx> {
1014 inputs_and_output: List::empty(),
1016 unsafety: hir::Unsafety::Normal,
1017 abi: abi::Abi::Rust,
1022 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1024 impl<'tcx> PolyFnSig<'tcx> {
1026 pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
1027 self.map_bound_ref(|fn_sig| fn_sig.inputs())
1030 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
1031 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
1033 pub fn inputs_and_output(&self) -> ty::Binder<&'tcx List<Ty<'tcx>>> {
1034 self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
1037 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
1038 self.map_bound_ref(|fn_sig| fn_sig.output())
1040 pub fn c_variadic(&self) -> bool {
1041 self.skip_binder().c_variadic
1043 pub fn unsafety(&self) -> hir::Unsafety {
1044 self.skip_binder().unsafety
1046 pub fn abi(&self) -> abi::Abi {
1047 self.skip_binder().abi
1051 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<FnSig<'tcx>>>;
1054 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
1055 Hash, RustcEncodable, RustcDecodable, HashStable)]
1056 pub struct ParamTy {
1058 pub name: InternedString,
1061 impl<'a, 'gcx, 'tcx> ParamTy {
1062 pub fn new(index: u32, name: InternedString) -> ParamTy {
1063 ParamTy { idx: index, name: name }
1066 pub fn for_self() -> ParamTy {
1067 ParamTy::new(0, keywords::SelfUpper.name().as_interned_str())
1070 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1071 ParamTy::new(def.index, def.name)
1074 pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1075 tcx.mk_ty_param(self.idx, self.name)
1078 pub fn is_self(&self) -> bool {
1079 // FIXME(#50125): Ignoring `Self` with `idx != 0` might lead to weird behavior elsewhere,
1080 // but this should only be possible when using `-Z continue-parse-after-error` like
1081 // `compile-fail/issue-36638.rs`.
1082 self.name == keywords::SelfUpper.name().as_str() && self.idx == 0
1086 #[derive(Copy, Clone, Hash, RustcEncodable, RustcDecodable,
1087 Eq, PartialEq, Ord, PartialOrd, HashStable)]
1088 pub struct ParamConst {
1090 pub name: InternedString,
1093 impl<'a, 'gcx, 'tcx> ParamConst {
1094 pub fn new(index: u32, name: InternedString) -> ParamConst {
1095 ParamConst { index, name }
1098 pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
1099 ParamConst::new(def.index, def.name)
1102 pub fn to_const(self, tcx: TyCtxt<'a, 'gcx, 'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
1103 tcx.mk_const_param(self.index, self.name, ty)
1108 /// A [De Bruijn index][dbi] is a standard means of representing
1109 /// regions (and perhaps later types) in a higher-ranked setting. In
1110 /// particular, imagine a type like this:
1112 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1115 /// | +------------+ 0 | |
1117 /// +--------------------------------+ 1 |
1119 /// +------------------------------------------+ 0
1121 /// In this type, there are two binders (the outer fn and the inner
1122 /// fn). We need to be able to determine, for any given region, which
1123 /// fn type it is bound by, the inner or the outer one. There are
1124 /// various ways you can do this, but a De Bruijn index is one of the
1125 /// more convenient and has some nice properties. The basic idea is to
1126 /// count the number of binders, inside out. Some examples should help
1127 /// clarify what I mean.
1129 /// Let's start with the reference type `&'b isize` that is the first
1130 /// argument to the inner function. This region `'b` is assigned a De
1131 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
1132 /// fn). The region `'a` that appears in the second argument type (`&'a
1133 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
1134 /// second-innermost binder". (These indices are written on the arrays
1135 /// in the diagram).
1137 /// What is interesting is that De Bruijn index attached to a particular
1138 /// variable will vary depending on where it appears. For example,
1139 /// the final type `&'a char` also refers to the region `'a` declared on
1140 /// the outermost fn. But this time, this reference is not nested within
1141 /// any other binders (i.e., it is not an argument to the inner fn, but
1142 /// rather the outer one). Therefore, in this case, it is assigned a
1143 /// De Bruijn index of 0, because the innermost binder in that location
1144 /// is the outer fn.
1146 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1147 pub struct DebruijnIndex {
1148 DEBUG_FORMAT = "DebruijnIndex({})",
1149 const INNERMOST = 0,
1153 pub type Region<'tcx> = &'tcx RegionKind;
1155 /// Representation of regions.
1157 /// Unlike types, most region variants are "fictitious", not concrete,
1158 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1159 /// ones representing concrete regions.
1161 /// ## Bound Regions
1163 /// These are regions that are stored behind a binder and must be substituted
1164 /// with some concrete region before being used. There are two kind of
1165 /// bound regions: early-bound, which are bound in an item's `Generics`,
1166 /// and are substituted by a `InternalSubsts`, and late-bound, which are part of
1167 /// higher-ranked types (e.g., `for<'a> fn(&'a ())`), and are substituted by
1168 /// the likes of `liberate_late_bound_regions`. The distinction exists
1169 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1171 /// Unlike `Param`s, bound regions are not supposed to exist "in the wild"
1172 /// outside their binder, e.g., in types passed to type inference, and
1173 /// should first be substituted (by placeholder regions, free regions,
1174 /// or region variables).
1176 /// ## Placeholder and Free Regions
1178 /// One often wants to work with bound regions without knowing their precise
1179 /// identity. For example, when checking a function, the lifetime of a borrow
1180 /// can end up being assigned to some region parameter. In these cases,
1181 /// it must be ensured that bounds on the region can't be accidentally
1182 /// assumed without being checked.
1184 /// To do this, we replace the bound regions with placeholder markers,
1185 /// which don't satisfy any relation not explicitly provided.
1187 /// There are two kinds of placeholder regions in rustc: `ReFree` and
1188 /// `RePlaceholder`. When checking an item's body, `ReFree` is supposed
1189 /// to be used. These also support explicit bounds: both the internally-stored
1190 /// *scope*, which the region is assumed to outlive, as well as other
1191 /// relations stored in the `FreeRegionMap`. Note that these relations
1192 /// aren't checked when you `make_subregion` (or `eq_types`), only by
1193 /// `resolve_regions_and_report_errors`.
1195 /// When working with higher-ranked types, some region relations aren't
1196 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1197 /// `RePlaceholder` is designed for this purpose. In these contexts,
1198 /// there's also the risk that some inference variable laying around will
1199 /// get unified with your placeholder region: if you want to check whether
1200 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1201 /// with a placeholder region `'%a`, the variable `'_` would just be
1202 /// instantiated to the placeholder region `'%a`, which is wrong because
1203 /// the inference variable is supposed to satisfy the relation
1204 /// *for every value of the placeholder region*. To ensure that doesn't
1205 /// happen, you can use `leak_check`. This is more clearly explained
1206 /// by the [rustc guide].
1208 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1209 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1210 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/hrtb.html
1211 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1212 pub enum RegionKind {
1213 /// Region bound in a type or fn declaration which will be
1214 /// substituted 'early' -- that is, at the same time when type
1215 /// parameters are substituted.
1216 ReEarlyBound(EarlyBoundRegion),
1218 /// Region bound in a function scope, which will be substituted when the
1219 /// function is called.
1220 ReLateBound(DebruijnIndex, BoundRegion),
1222 /// When checking a function body, the types of all arguments and so forth
1223 /// that refer to bound region parameters are modified to refer to free
1224 /// region parameters.
1227 /// A concrete region naming some statically determined scope
1228 /// (e.g., an expression or sequence of statements) within the
1229 /// current function.
1230 ReScope(region::Scope),
1232 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1235 /// A region variable. Should not exist after typeck.
1238 /// A placeholder region - basically the higher-ranked version of ReFree.
1239 /// Should not exist after typeck.
1240 RePlaceholder(ty::PlaceholderRegion),
1242 /// Empty lifetime is for data that is never accessed.
1243 /// Bottom in the region lattice. We treat ReEmpty somewhat
1244 /// specially; at least right now, we do not generate instances of
1245 /// it during the GLB computations, but rather
1246 /// generate an error instead. This is to improve error messages.
1247 /// The only way to get an instance of ReEmpty is to have a region
1248 /// variable with no constraints.
1251 /// Erased region, used by trait selection, in MIR and during codegen.
1254 /// These are regions bound in the "defining type" for a
1255 /// closure. They are used ONLY as part of the
1256 /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1257 /// See `ClosureRegionRequirements` for more details.
1258 ReClosureBound(RegionVid),
1261 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1263 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1264 pub struct EarlyBoundRegion {
1267 pub name: InternedString,
1270 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1275 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1276 pub struct ConstVid<'tcx> {
1278 pub phantom: PhantomData<&'tcx ()>,
1281 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1286 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1287 pub struct FloatVid {
1292 pub struct RegionVid {
1293 DEBUG_FORMAT = custom,
1297 impl Atom for RegionVid {
1298 fn index(self) -> usize {
1303 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
1304 Hash, RustcEncodable, RustcDecodable, HashStable)]
1310 /// A `FreshTy` is one that is generated as a replacement for an
1311 /// unbound type variable. This is convenient for caching etc. See
1312 /// `infer::freshen` for more details.
1319 pub struct BoundVar { .. }
1322 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1323 pub struct BoundTy {
1325 pub kind: BoundTyKind,
1328 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1329 pub enum BoundTyKind {
1331 Param(InternedString),
1334 impl_stable_hash_for!(struct BoundTy { var, kind });
1335 impl_stable_hash_for!(enum self::BoundTyKind { Anon, Param(a) });
1337 impl From<BoundVar> for BoundTy {
1338 fn from(var: BoundVar) -> Self {
1341 kind: BoundTyKind::Anon,
1346 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1347 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash,
1348 Debug, RustcEncodable, RustcDecodable, HashStable)]
1349 pub struct ExistentialProjection<'tcx> {
1350 pub item_def_id: DefId,
1351 pub substs: SubstsRef<'tcx>,
1355 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1357 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1358 /// Extracts the underlying existential trait reference from this projection.
1359 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1360 /// then this function would return a `exists T. T: Iterator` existential trait
1362 pub fn trait_ref(&self, tcx: TyCtxt<'_, '_, '_>) -> ty::ExistentialTraitRef<'tcx> {
1363 let def_id = tcx.associated_item(self.item_def_id).container.id();
1364 ty::ExistentialTraitRef{
1366 substs: self.substs,
1370 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1372 -> ty::ProjectionPredicate<'tcx>
1374 // otherwise the escaping regions would be captured by the binders
1375 debug_assert!(!self_ty.has_escaping_bound_vars());
1377 ty::ProjectionPredicate {
1378 projection_ty: ty::ProjectionTy {
1379 item_def_id: self.item_def_id,
1380 substs: tcx.mk_substs_trait(self_ty, self.substs),
1387 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
1388 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
1389 -> ty::PolyProjectionPredicate<'tcx> {
1390 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1393 pub fn item_def_id(&self) -> DefId {
1394 return self.skip_binder().item_def_id;
1398 impl DebruijnIndex {
1399 /// Returns the resulting index when this value is moved into
1400 /// `amount` number of new binders. So, e.g., if you had
1402 /// for<'a> fn(&'a x)
1404 /// and you wanted to change it to
1406 /// for<'a> fn(for<'b> fn(&'a x))
1408 /// you would need to shift the index for `'a` into a new binder.
1410 pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
1411 DebruijnIndex::from_u32(self.as_u32() + amount)
1414 /// Update this index in place by shifting it "in" through
1415 /// `amount` number of binders.
1416 pub fn shift_in(&mut self, amount: u32) {
1417 *self = self.shifted_in(amount);
1420 /// Returns the resulting index when this value is moved out from
1421 /// `amount` number of new binders.
1423 pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
1424 DebruijnIndex::from_u32(self.as_u32() - amount)
1427 /// Update in place by shifting out from `amount` binders.
1428 pub fn shift_out(&mut self, amount: u32) {
1429 *self = self.shifted_out(amount);
1432 /// Adjusts any De Bruijn indices so as to make `to_binder` the
1433 /// innermost binder. That is, if we have something bound at `to_binder`,
1434 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1435 /// when moving a region out from inside binders:
1438 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1439 /// // Binder: D3 D2 D1 ^^
1442 /// Here, the region `'a` would have the De Bruijn index D3,
1443 /// because it is the bound 3 binders out. However, if we wanted
1444 /// to refer to that region `'a` in the second argument (the `_`),
1445 /// those two binders would not be in scope. In that case, we
1446 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1447 /// De Bruijn index of `'a` to D1 (the innermost binder).
1449 /// If we invoke `shift_out_to_binder` and the region is in fact
1450 /// bound by one of the binders we are shifting out of, that is an
1451 /// error (and should fail an assertion failure).
1452 pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
1453 self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
1457 impl_stable_hash_for!(struct DebruijnIndex { private });
1459 /// Region utilities
1461 /// Is this region named by the user?
1462 pub fn has_name(&self) -> bool {
1464 RegionKind::ReEarlyBound(ebr) => ebr.has_name(),
1465 RegionKind::ReLateBound(_, br) => br.is_named(),
1466 RegionKind::ReFree(fr) => fr.bound_region.is_named(),
1467 RegionKind::ReScope(..) => false,
1468 RegionKind::ReStatic => true,
1469 RegionKind::ReVar(..) => false,
1470 RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(),
1471 RegionKind::ReEmpty => false,
1472 RegionKind::ReErased => false,
1473 RegionKind::ReClosureBound(..) => false,
1477 pub fn is_late_bound(&self) -> bool {
1479 ty::ReLateBound(..) => true,
1484 pub fn is_placeholder(&self) -> bool {
1486 ty::RePlaceholder(..) => true,
1491 pub fn bound_at_or_above_binder(&self, index: DebruijnIndex) -> bool {
1493 ty::ReLateBound(debruijn, _) => debruijn >= index,
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: ty::DebruijnIndex) -> RegionKind {
1520 ty::ReLateBound(debruijn, r) => ty::ReLateBound(
1521 debruijn.shifted_out_to_binder(to_binder),
1528 pub fn keep_in_local_tcx(&self) -> bool {
1529 if let ty::ReVar(..) = self {
1536 pub fn type_flags(&self) -> TypeFlags {
1537 let mut flags = TypeFlags::empty();
1539 if self.keep_in_local_tcx() {
1540 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1545 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1546 flags = flags | TypeFlags::HAS_RE_INFER;
1548 ty::RePlaceholder(..) => {
1549 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1550 flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
1552 ty::ReLateBound(..) => {
1553 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1555 ty::ReEarlyBound(..) => {
1556 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1557 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1562 ty::ReScope { .. } => {
1563 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1567 ty::ReClosureBound(..) => {
1568 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1573 ty::ReStatic | ty::ReEmpty | ty::ReErased | ty::ReLateBound(..) => (),
1574 _ => flags = flags | TypeFlags::HAS_FREE_LOCAL_NAMES,
1577 debug!("type_flags({:?}) = {:?}", self, flags);
1582 /// Given an early-bound or free region, returns the `DefId` where it was bound.
1583 /// For example, consider the regions in this snippet of code:
1587 /// ^^ -- early bound, declared on an impl
1589 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1590 /// ^^ ^^ ^ anonymous, late-bound
1591 /// | early-bound, appears in where-clauses
1592 /// late-bound, appears only in fn args
1597 /// Here, `free_region_binding_scope('a)` would return the `DefId`
1598 /// of the impl, and for all the other highlighted regions, it
1599 /// would return the `DefId` of the function. In other cases (not shown), this
1600 /// function might return the `DefId` of a closure.
1601 pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_, '_, '_>) -> DefId {
1603 ty::ReEarlyBound(br) => {
1604 tcx.parent(br.def_id).unwrap()
1606 ty::ReFree(fr) => fr.scope,
1607 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1613 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
1614 pub fn is_unit(&self) -> bool {
1616 Tuple(ref tys) => tys.is_empty(),
1621 pub fn is_never(&self) -> bool {
1628 /// Checks whether a type is definitely uninhabited. This is
1629 /// conservative: for some types that are uninhabited we return `false`,
1630 /// but we only return `true` for types that are definitely uninhabited.
1631 /// `ty.conservative_is_privately_uninhabited` implies that any value of type `ty`
1632 /// will be `Abi::Uninhabited`. (Note that uninhabited types may have nonzero
1633 /// size, to account for partial initialisation. See #49298 for details.)
1634 pub fn conservative_is_privately_uninhabited(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1635 // FIXME(varkor): we can make this less conversative by substituting concrete
1639 ty::Adt(def, _) if def.is_union() => {
1640 // For now, `union`s are never considered uninhabited.
1643 ty::Adt(def, _) => {
1644 // Any ADT is uninhabited if either:
1645 // (a) It has no variants (i.e. an empty `enum`);
1646 // (b) Each of its variants (a single one in the case of a `struct`) has at least
1647 // one uninhabited field.
1648 def.variants.iter().all(|var| {
1649 var.fields.iter().any(|field| {
1650 tcx.type_of(field.did).conservative_is_privately_uninhabited(tcx)
1654 ty::Tuple(tys) => tys.iter().any(|ty| {
1655 ty.expect_ty().conservative_is_privately_uninhabited(tcx)
1657 ty::Array(ty, len) => {
1658 match len.assert_usize(tcx) {
1659 // If the array is definitely non-empty, it's uninhabited if
1660 // the type of its elements is uninhabited.
1661 Some(n) if n != 0 => ty.conservative_is_privately_uninhabited(tcx),
1666 // References to uninitialised memory is valid for any type, including
1667 // uninhabited types, in unsafe code, so we treat all references as
1675 pub fn is_primitive(&self) -> bool {
1677 Bool | Char | Int(_) | Uint(_) | Float(_) => true,
1683 pub fn is_ty_var(&self) -> bool {
1685 Infer(TyVar(_)) => true,
1690 pub fn is_ty_infer(&self) -> bool {
1697 pub fn is_phantom_data(&self) -> bool {
1698 if let Adt(def, _) = self.sty {
1699 def.is_phantom_data()
1705 pub fn is_bool(&self) -> bool { self.sty == Bool }
1707 pub fn is_param(&self, index: u32) -> bool {
1709 ty::Param(ref data) => data.idx == index,
1714 pub fn is_self(&self) -> bool {
1716 Param(ref p) => p.is_self(),
1721 pub fn is_slice(&self) -> bool {
1723 RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => match ty.sty {
1724 Slice(_) | Str => true,
1732 pub fn is_simd(&self) -> bool {
1734 Adt(def, _) => def.repr.simd(),
1739 pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1741 Array(ty, _) | Slice(ty) => ty,
1742 Str => tcx.mk_mach_uint(ast::UintTy::U8),
1743 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1747 pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1749 Adt(def, substs) => {
1750 def.non_enum_variant().fields[0].ty(tcx, substs)
1752 _ => bug!("simd_type called on invalid type")
1756 pub fn simd_size(&self, _cx: TyCtxt<'_, '_, '_>) -> usize {
1758 Adt(def, _) => def.non_enum_variant().fields.len(),
1759 _ => bug!("simd_size called on invalid type")
1763 pub fn is_region_ptr(&self) -> bool {
1770 pub fn is_mutable_pointer(&self) -> bool {
1772 RawPtr(TypeAndMut { mutbl: hir::Mutability::MutMutable, .. }) |
1773 Ref(_, _, hir::Mutability::MutMutable) => true,
1778 pub fn is_unsafe_ptr(&self) -> bool {
1780 RawPtr(_) => return true,
1785 /// Returns `true` if this type is an `Arc<T>`.
1786 pub fn is_arc(&self) -> bool {
1788 Adt(def, _) => def.is_arc(),
1793 /// Returns `true` if this type is an `Rc<T>`.
1794 pub fn is_rc(&self) -> bool {
1796 Adt(def, _) => def.is_rc(),
1801 pub fn is_box(&self) -> bool {
1803 Adt(def, _) => def.is_box(),
1808 /// panics if called on any type other than `Box<T>`
1809 pub fn boxed_ty(&self) -> Ty<'tcx> {
1811 Adt(def, substs) if def.is_box() => substs.type_at(0),
1812 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1816 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1817 /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1818 /// contents are abstract to rustc.)
1819 pub fn is_scalar(&self) -> bool {
1821 Bool | Char | Int(_) | Float(_) | Uint(_) |
1822 Infer(IntVar(_)) | Infer(FloatVar(_)) |
1823 FnDef(..) | FnPtr(_) | RawPtr(_) => true,
1828 /// Returns `true` if this type is a floating point type.
1829 pub fn is_floating_point(&self) -> bool {
1832 Infer(FloatVar(_)) => true,
1837 pub fn is_trait(&self) -> bool {
1839 Dynamic(..) => true,
1844 pub fn is_enum(&self) -> bool {
1846 Adt(adt_def, _) => {
1853 pub fn is_closure(&self) -> bool {
1855 Closure(..) => true,
1860 pub fn is_generator(&self) -> bool {
1862 Generator(..) => true,
1868 pub fn is_integral(&self) -> bool {
1870 Infer(IntVar(_)) | Int(_) | Uint(_) => true,
1875 pub fn is_fresh_ty(&self) -> bool {
1877 Infer(FreshTy(_)) => true,
1882 pub fn is_fresh(&self) -> bool {
1884 Infer(FreshTy(_)) => true,
1885 Infer(FreshIntTy(_)) => true,
1886 Infer(FreshFloatTy(_)) => true,
1891 pub fn is_char(&self) -> bool {
1899 pub fn is_fp(&self) -> bool {
1901 Infer(FloatVar(_)) | Float(_) => true,
1906 pub fn is_numeric(&self) -> bool {
1907 self.is_integral() || self.is_fp()
1910 pub fn is_signed(&self) -> bool {
1917 pub fn is_pointer_sized(&self) -> bool {
1919 Int(ast::IntTy::Isize) | Uint(ast::UintTy::Usize) => true,
1924 pub fn is_machine(&self) -> bool {
1926 Int(..) | Uint(..) | Float(..) => true,
1931 pub fn has_concrete_skeleton(&self) -> bool {
1933 Param(_) | Infer(_) | Error => false,
1938 /// Returns the type and mutability of `*ty`.
1940 /// The parameter `explicit` indicates if this is an *explicit* dereference.
1941 /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
1942 pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1944 Adt(def, _) if def.is_box() => {
1946 ty: self.boxed_ty(),
1947 mutbl: hir::MutImmutable,
1950 Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
1951 RawPtr(mt) if explicit => Some(mt),
1956 /// Returns the type of `ty[i]`.
1957 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1959 Array(ty, _) | Slice(ty) => Some(ty),
1964 pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1966 FnDef(def_id, substs) => {
1967 tcx.fn_sig(def_id).subst(tcx, substs)
1970 Error => { // ignore errors (#54954)
1971 ty::Binder::dummy(FnSig::fake())
1973 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1977 pub fn is_fn(&self) -> bool {
1979 FnDef(..) | FnPtr(_) => true,
1984 pub fn is_impl_trait(&self) -> bool {
1992 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1994 Adt(adt, _) => Some(adt),
1999 /// Push onto `out` the regions directly referenced from this type (but not
2000 /// types reachable from this type via `walk_tys`). This ignores late-bound
2001 /// regions binders.
2002 pub fn push_regions(&self, out: &mut SmallVec<[ty::Region<'tcx>; 4]>) {
2004 Ref(region, _, _) => {
2007 Dynamic(ref obj, region) => {
2009 if let Some(principal) = obj.principal() {
2010 out.extend(principal.skip_binder().substs.regions());
2013 Adt(_, substs) | Opaque(_, substs) => {
2014 out.extend(substs.regions())
2016 Closure(_, ClosureSubsts { ref substs }) |
2017 Generator(_, GeneratorSubsts { ref substs }, _) => {
2018 out.extend(substs.regions())
2020 Projection(ref data) | UnnormalizedProjection(ref data) => {
2021 out.extend(data.substs.regions())
2025 GeneratorWitness(..) |
2046 /// When we create a closure, we record its kind (i.e., what trait
2047 /// it implements) into its `ClosureSubsts` using a type
2048 /// parameter. This is kind of a phantom type, except that the
2049 /// most convenient thing for us to are the integral types. This
2050 /// function converts such a special type into the closure
2051 /// kind. To go the other way, use
2052 /// `tcx.closure_kind_ty(closure_kind)`.
2054 /// Note that during type checking, we use an inference variable
2055 /// to represent the closure kind, because it has not yet been
2056 /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
2057 /// is complete, that type variable will be unified.
2058 pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
2060 Int(int_ty) => match int_ty {
2061 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
2062 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
2063 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
2064 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2069 Error => Some(ty::ClosureKind::Fn),
2071 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2075 /// Fast path helper for testing if a type is `Sized`.
2077 /// Returning true means the type is known to be sized. Returning
2078 /// `false` means nothing -- could be sized, might not be.
2079 pub fn is_trivially_sized(&self, tcx: TyCtxt<'_, '_, 'tcx>) -> bool {
2081 ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
2082 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
2083 ty::FnDef(..) | ty::FnPtr(_) | ty::RawPtr(..) |
2084 ty::Char | ty::Ref(..) | ty::Generator(..) |
2085 ty::GeneratorWitness(..) | ty::Array(..) | ty::Closure(..) |
2086 ty::Never | ty::Error =>
2089 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) =>
2093 tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx))
2096 ty::Adt(def, _substs) =>
2097 def.sized_constraint(tcx).is_empty(),
2099 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
2101 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
2103 ty::Infer(ty::TyVar(_)) => false,
2106 ty::Placeholder(..) |
2107 ty::Infer(ty::FreshTy(_)) |
2108 ty::Infer(ty::FreshIntTy(_)) |
2109 ty::Infer(ty::FreshFloatTy(_)) =>
2110 bug!("is_trivially_sized applied to unexpected type: {:?}", self),
2115 /// Typed constant value.
2116 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable,
2117 Eq, PartialEq, Ord, PartialOrd, HashStable)]
2118 pub struct Const<'tcx> {
2121 pub val: ConstValue<'tcx>,
2124 #[cfg(target_arch = "x86_64")]
2125 static_assert!(CONST_SIZE: ::std::mem::size_of::<Const<'static>>() == 48);
2127 impl<'tcx> Const<'tcx> {
2134 val: ConstValue::Scalar(val),
2141 tcx: TyCtxt<'_, '_, 'tcx>,
2143 ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2145 let ty = tcx.lift_to_global(&ty).unwrap();
2146 let size = tcx.layout_of(ty).unwrap_or_else(|e| {
2147 panic!("could not compute layout for {:?}: {:?}", ty, e)
2149 let truncated = truncate(bits, size);
2150 assert_eq!(truncated, bits, "from_bits called with untruncated value");
2151 Self::from_scalar(Scalar::Bits { bits, size: size.bytes() as u8 }, ty.value)
2155 pub fn zero_sized(ty: Ty<'tcx>) -> Self {
2156 Self::from_scalar(Scalar::Bits { bits: 0, size: 0 }, ty)
2160 pub fn from_bool(tcx: TyCtxt<'_, '_, 'tcx>, v: bool) -> Self {
2161 Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
2165 pub fn from_usize(tcx: TyCtxt<'_, '_, 'tcx>, n: u64) -> Self {
2166 Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
2172 tcx: TyCtxt<'_, '_, 'tcx>,
2173 ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2175 if self.ty != ty.value {
2178 let ty = tcx.lift_to_global(&ty).unwrap();
2179 let size = tcx.layout_of(ty).ok()?.size;
2180 self.val.try_to_bits(size)
2184 pub fn to_ptr(&self) -> Option<Pointer> {
2185 self.val.try_to_ptr()
2191 tcx: TyCtxt<'_, '_, '_>,
2192 ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2194 assert_eq!(self.ty, ty.value);
2195 let ty = tcx.lift_to_global(&ty).unwrap();
2196 let size = tcx.layout_of(ty).ok()?.size;
2197 self.val.try_to_bits(size)
2201 pub fn assert_bool(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<bool> {
2202 self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.bool)).and_then(|v| match v {
2210 pub fn assert_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<u64> {
2211 self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.usize)).map(|v| v as u64)
2217 tcx: TyCtxt<'_, '_, '_>,
2218 ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2220 self.assert_bits(tcx, ty).unwrap_or_else(||
2221 bug!("expected bits of {}, got {:#?}", ty.value, self))
2225 pub fn unwrap_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> u64 {
2226 self.assert_usize(tcx).unwrap_or_else(||
2227 bug!("expected constant usize, got {:#?}", self))
2231 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}
2233 /// An inference variable for a const, for use in const generics.
2234 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd,
2235 Ord, RustcEncodable, RustcDecodable, Hash, HashStable)]
2236 pub enum InferConst<'tcx> {
2237 /// Infer the value of the const.
2238 Var(ConstVid<'tcx>),
2239 /// A fresh const variable. See `infer::freshen` for more details.
2241 /// Canonicalized const variable, used only when preparing a trait query.
2242 Canonical(DebruijnIndex, BoundVar),