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 crate::ty::subst::{Substs, Subst, Kind, UnpackedKind};
11 use crate::ty::{self, AdtDef, TypeFlags, Ty, TyCtxt, TypeFoldable};
12 use crate::ty::{List, TyS, ParamEnvAnd, ParamEnv};
13 use crate::util::captures::Captures;
14 use crate::mir::interpret::{Scalar, Pointer};
16 use smallvec::SmallVec;
18 use std::cmp::Ordering;
19 use rustc_target::spec::abi;
20 use syntax::ast::{self, Ident};
21 use syntax::symbol::{keywords, InternedString};
27 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
28 pub struct TypeAndMut<'tcx> {
30 pub mutbl: hir::Mutability,
33 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
34 RustcEncodable, RustcDecodable, Copy)]
35 /// A "free" region `fr` can be interpreted as "some region
36 /// at least as big as the scope `fr.scope`".
37 pub struct FreeRegion {
39 pub bound_region: BoundRegion,
42 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
43 RustcEncodable, RustcDecodable, Copy)]
44 pub enum BoundRegion {
45 /// An anonymous region parameter for a given fn (&T)
48 /// Named region parameters for functions (a in &'a T)
50 /// The `DefId` is needed to distinguish free regions in
51 /// the event of shadowing.
52 BrNamed(DefId, InternedString),
54 /// Fresh bound identifiers created during GLB computations.
57 /// Anonymous region for the implicit env pointer parameter
63 pub fn is_named(&self) -> bool {
65 BoundRegion::BrNamed(..) => true,
70 /// When canonicalizing, we replace unbound inference variables and free
71 /// regions with anonymous late bound regions. This method asserts that
72 /// we have an anonymous late bound region, which hence may refer to
73 /// a canonical variable.
74 pub fn assert_bound_var(&self) -> BoundVar {
76 BoundRegion::BrAnon(var) => BoundVar::from_u32(var),
77 _ => bug!("bound region is not anonymous"),
82 /// N.B., if you change this, you'll probably want to change the corresponding
83 /// AST structure in `libsyntax/ast.rs` as well.
84 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
85 pub enum TyKind<'tcx> {
86 /// The primitive boolean type. Written as `bool`.
89 /// The primitive character type; holds a Unicode scalar value
90 /// (a non-surrogate code point). Written as `char`.
93 /// A primitive signed integer type. For example, `i32`.
96 /// A primitive unsigned integer type. For example, `u32`.
99 /// A primitive floating-point type. For example, `f64`.
102 /// Structures, enumerations and unions.
104 /// Substs here, possibly against intuition, *may* contain `Param`s.
105 /// That is, even after substitution it is possible that there are type
106 /// variables. This happens when the `Adt` corresponds to an ADT
107 /// definition and not a concrete use of it.
108 Adt(&'tcx AdtDef, &'tcx Substs<'tcx>),
110 /// An unsized FFI type that is opaque to Rust. Written as `extern type T`.
113 /// The pointee of a string slice. Written as `str`.
116 /// An array with the given length. Written as `[T; n]`.
117 Array(Ty<'tcx>, &'tcx ty::LazyConst<'tcx>),
119 /// The pointee of an array slice. Written as `[T]`.
122 /// A raw pointer. Written as `*mut T` or `*const T`
123 RawPtr(TypeAndMut<'tcx>),
125 /// A reference; a pointer with an associated lifetime. Written as
126 /// `&'a mut T` or `&'a T`.
127 Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability),
129 /// The anonymous type of a function declaration/definition. Each
130 /// function has a unique type, which is output (for a function
131 /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
133 /// For example the type of `bar` here:
136 /// fn foo() -> i32 { 1 }
137 /// let bar = foo; // bar: fn() -> i32 {foo}
139 FnDef(DefId, &'tcx Substs<'tcx>),
141 /// A pointer to a function. Written as `fn() -> i32`.
143 /// For example the type of `bar` here:
146 /// fn foo() -> i32 { 1 }
147 /// let bar: fn() -> i32 = foo;
149 FnPtr(PolyFnSig<'tcx>),
151 /// A trait, defined with `trait`.
152 Dynamic(Binder<&'tcx List<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
154 /// The anonymous type of a closure. Used to represent the type of
156 Closure(DefId, ClosureSubsts<'tcx>),
158 /// The anonymous type of a generator. Used to represent the type of
160 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
162 /// A type representin the types stored inside a generator.
163 /// This should only appear in GeneratorInteriors.
164 GeneratorWitness(Binder<&'tcx List<Ty<'tcx>>>),
166 /// The never type `!`
169 /// A tuple type. For example, `(i32, bool)`.
170 Tuple(&'tcx List<Ty<'tcx>>),
172 /// The projection of an associated type. For example,
173 /// `<T as Trait<..>>::N`.
174 Projection(ProjectionTy<'tcx>),
176 /// A placeholder type used when we do not have enough information
177 /// to normalize the projection of an associated type to an
178 /// existing concrete type. Currently only used with chalk-engine.
179 UnnormalizedProjection(ProjectionTy<'tcx>),
181 /// Opaque (`impl Trait`) type found in a return type.
182 /// The `DefId` comes either from
183 /// * the `impl Trait` ast::Ty node,
184 /// * or the `existential type` declaration
185 /// The substitutions are for the generics of the function in question.
186 /// After typeck, the concrete type can be found in the `types` map.
187 Opaque(DefId, &'tcx Substs<'tcx>),
189 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
192 /// Bound type variable, used only when preparing a trait query.
193 Bound(ty::DebruijnIndex, BoundTy),
195 /// A placeholder type - universally quantified higher-ranked type.
196 Placeholder(ty::PlaceholderType),
198 /// A type variable used during type checking.
201 /// A placeholder for a type which could not be computed; this is
202 /// propagated to avoid useless error messages.
206 // `TyKind` is used a lot. Make sure it doesn't unintentionally get bigger.
207 #[cfg(target_arch = "x86_64")]
208 static_assert!(MEM_SIZE_OF_TY_KIND: ::std::mem::size_of::<TyKind<'_>>() == 24);
210 /// A closure can be modeled as a struct that looks like:
212 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
220 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
221 /// in scope on the function that defined the closure,
222 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
223 /// is rather hackily encoded via a scalar type. See
224 /// `TyS::to_opt_closure_kind` for details.
225 /// - CS represents the *closure signature*, representing as a `fn()`
226 /// type. For example, `fn(u32, u32) -> u32` would mean that the closure
227 /// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
229 /// - U0...Uk are type parameters representing the types of its upvars
230 /// (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
231 /// and the up-var has the type `Foo`, then `Ui = &Foo`).
233 /// So, for example, given this function:
235 /// fn foo<'a, T>(data: &'a mut T) {
236 /// do(|| data.count += 1)
239 /// the type of the closure would be something like:
241 /// struct Closure<'a, T, U0> {
245 /// Note that the type of the upvar is not specified in the struct.
246 /// You may wonder how the impl would then be able to use the upvar,
247 /// if it doesn't know it's type? The answer is that the impl is
248 /// (conceptually) not fully generic over Closure but rather tied to
249 /// instances with the expected upvar types:
251 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
255 /// You can see that the *impl* fully specified the type of the upvar
256 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
257 /// (Here, I am assuming that `data` is mut-borrowed.)
259 /// Now, the last question you may ask is: Why include the upvar types
260 /// as extra type parameters? The reason for this design is that the
261 /// upvar types can reference lifetimes that are internal to the
262 /// creating function. In my example above, for example, the lifetime
263 /// `'b` represents the scope of the closure itself; this is some
264 /// subset of `foo`, probably just the scope of the call to the to
265 /// `do()`. If we just had the lifetime/type parameters from the
266 /// enclosing function, we couldn't name this lifetime `'b`. Note that
267 /// there can also be lifetimes in the types of the upvars themselves,
268 /// if one of them happens to be a reference to something that the
269 /// creating fn owns.
271 /// OK, you say, so why not create a more minimal set of parameters
272 /// that just includes the extra lifetime parameters? The answer is
273 /// primarily that it would be hard --- we don't know at the time when
274 /// we create the closure type what the full types of the upvars are,
275 /// nor do we know which are borrowed and which are not. In this
276 /// design, we can just supply a fresh type parameter and figure that
279 /// All right, you say, but why include the type parameters from the
280 /// original function then? The answer is that codegen may need them
281 /// when monomorphizing, and they may not appear in the upvars. A
282 /// closure could capture no variables but still make use of some
283 /// in-scope type parameter with a bound (e.g., if our example above
284 /// had an extra `U: Default`, and the closure called `U::default()`).
286 /// There is another reason. This design (implicitly) prohibits
287 /// closures from capturing themselves (except via a trait
288 /// object). This simplifies closure inference considerably, since it
289 /// means that when we infer the kind of a closure or its upvars, we
290 /// don't have to handle cycles where the decisions we make for
291 /// closure C wind up influencing the decisions we ought to make for
292 /// closure C (which would then require fixed point iteration to
293 /// handle). Plus it fixes an ICE. :P
297 /// Perhaps surprisingly, `ClosureSubsts` are also used for
298 /// generators. In that case, what is written above is only half-true
299 /// -- the set of type parameters is similar, but the role of CK and
300 /// CS are different. CK represents the "yield type" and CS
301 /// represents the "return type" of the generator.
303 /// It'd be nice to split this struct into ClosureSubsts and
304 /// GeneratorSubsts, I believe. -nmatsakis
305 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
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: &'tcx Substs<'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..],
338 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
339 impl Iterator<Item=Ty<'tcx>> + 'tcx
341 let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
342 upvar_kinds.iter().map(|t| {
343 if let UnpackedKind::Type(ty) = t.unpack() {
346 bug!("upvar should be type")
351 /// Returns the closure kind for this closure; may return a type
352 /// variable during inference. To get the closure kind during
353 /// inference, use `infcx.closure_kind(def_id, substs)`.
354 pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
355 self.split(def_id, tcx).closure_kind_ty
358 /// Returns the type representing the closure signature for this
359 /// closure; may contain type variables during inference. To get
360 /// the closure signature during inference, use
361 /// `infcx.fn_sig(def_id)`.
362 pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
363 self.split(def_id, tcx).closure_sig_ty
366 /// Returns the closure kind for this closure; only usable outside
367 /// of an inference context, because in that context we know that
368 /// there are no type variables.
370 /// If you have an inference context, use `infcx.closure_kind()`.
371 pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::ClosureKind {
372 self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
375 /// Extracts the signature from the closure; only usable outside
376 /// of an inference context, because in that context we know that
377 /// there are no type variables.
379 /// If you have an inference context, use `infcx.closure_sig()`.
380 pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
381 match self.closure_sig_ty(def_id, tcx).sty {
382 ty::FnPtr(sig) => sig,
383 ref t => bug!("closure_sig_ty is not a fn-ptr: {:?}", t),
388 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
389 pub struct GeneratorSubsts<'tcx> {
390 pub substs: &'tcx Substs<'tcx>,
393 struct SplitGeneratorSubsts<'tcx> {
397 upvar_kinds: &'tcx [Kind<'tcx>],
400 impl<'tcx> GeneratorSubsts<'tcx> {
401 fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitGeneratorSubsts<'tcx> {
402 let generics = tcx.generics_of(def_id);
403 let parent_len = generics.parent_count;
404 SplitGeneratorSubsts {
405 yield_ty: self.substs.type_at(parent_len),
406 return_ty: self.substs.type_at(parent_len + 1),
407 witness: self.substs.type_at(parent_len + 2),
408 upvar_kinds: &self.substs[parent_len + 3..],
412 /// This describes the types that can be contained in a generator.
413 /// It will be a type variable initially and unified in the last stages of typeck of a body.
414 /// It contains a tuple of all the types that could end up on a generator frame.
415 /// The state transformation MIR pass may only produce layouts which mention types
416 /// in this tuple. Upvars are not counted here.
417 pub fn witness(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
418 self.split(def_id, tcx).witness
422 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
423 impl Iterator<Item=Ty<'tcx>> + 'tcx
425 let SplitGeneratorSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
426 upvar_kinds.iter().map(|t| {
427 if let UnpackedKind::Type(ty) = t.unpack() {
430 bug!("upvar should be type")
435 /// Returns the type representing the yield type of the generator.
436 pub fn yield_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
437 self.split(def_id, tcx).yield_ty
440 /// Returns the type representing the return type of the generator.
441 pub fn return_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
442 self.split(def_id, tcx).return_ty
445 /// Returns the "generator signature", which consists of its yield
446 /// and return types.
448 /// N.B., some bits of the code prefers to see this wrapped in a
449 /// binder, but it never contains bound regions. Probably this
450 /// function should be removed.
451 pub fn poly_sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> PolyGenSig<'tcx> {
452 ty::Binder::dummy(self.sig(def_id, tcx))
455 /// Returns the "generator signature", which consists of its yield
456 /// and return types.
457 pub fn sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> GenSig<'tcx> {
459 yield_ty: self.yield_ty(def_id, tcx),
460 return_ty: self.return_ty(def_id, tcx),
465 impl<'a, 'gcx, 'tcx> GeneratorSubsts<'tcx> {
466 /// This returns the types of the MIR locals which had to be stored across suspension points.
467 /// It is calculated in rustc_mir::transform::generator::StateTransform.
468 /// All the types here must be in the tuple in GeneratorInterior.
472 tcx: TyCtxt<'a, 'gcx, 'tcx>,
473 ) -> impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a {
474 let state = tcx.generator_layout(def_id).fields.iter();
475 state.map(move |d| d.ty.subst(tcx, self.substs))
478 /// This is the types of the fields of a generate which
479 /// is available before the generator transformation.
480 /// It includes the upvars and the state discriminant which is u32.
481 pub fn pre_transforms_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
482 impl Iterator<Item=Ty<'tcx>> + 'a
484 self.upvar_tys(def_id, tcx).chain(iter::once(tcx.types.u32))
487 /// This is the types of all the fields stored in a generator.
488 /// It includes the upvars, state types and the state discriminant which is u32.
489 pub fn field_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
490 impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a
492 self.pre_transforms_tys(def_id, tcx).chain(self.state_tys(def_id, tcx))
496 #[derive(Debug, Copy, Clone)]
497 pub enum UpvarSubsts<'tcx> {
498 Closure(ClosureSubsts<'tcx>),
499 Generator(GeneratorSubsts<'tcx>),
502 impl<'tcx> UpvarSubsts<'tcx> {
504 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
505 impl Iterator<Item=Ty<'tcx>> + 'tcx
507 let upvar_kinds = match self {
508 UpvarSubsts::Closure(substs) => substs.split(def_id, tcx).upvar_kinds,
509 UpvarSubsts::Generator(substs) => substs.split(def_id, tcx).upvar_kinds,
511 upvar_kinds.iter().map(|t| {
512 if let UnpackedKind::Type(ty) = t.unpack() {
515 bug!("upvar should be type")
521 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, RustcEncodable, RustcDecodable)]
522 pub enum ExistentialPredicate<'tcx> {
523 /// E.g., `Iterator`.
524 Trait(ExistentialTraitRef<'tcx>),
525 /// E.g., `Iterator::Item = T`.
526 Projection(ExistentialProjection<'tcx>),
531 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
532 /// Compares via an ordering that will not change if modules are reordered or other changes are
533 /// made to the tree. In particular, this ordering is preserved across incremental compilations.
534 pub fn stable_cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
535 use self::ExistentialPredicate::*;
536 match (*self, *other) {
537 (Trait(_), Trait(_)) => Ordering::Equal,
538 (Projection(ref a), Projection(ref b)) =>
539 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
540 (AutoTrait(ref a), AutoTrait(ref b)) =>
541 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
542 (Trait(_), _) => Ordering::Less,
543 (Projection(_), Trait(_)) => Ordering::Greater,
544 (Projection(_), _) => Ordering::Less,
545 (AutoTrait(_), _) => Ordering::Greater,
551 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
552 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
553 -> ty::Predicate<'tcx> {
554 use crate::ty::ToPredicate;
555 match *self.skip_binder() {
556 ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
557 ExistentialPredicate::Projection(p) =>
558 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
559 ExistentialPredicate::AutoTrait(did) => {
560 let trait_ref = Binder(ty::TraitRef {
562 substs: tcx.mk_substs_trait(self_ty, &[]),
564 trait_ref.to_predicate()
570 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx List<ExistentialPredicate<'tcx>> {}
572 impl<'tcx> List<ExistentialPredicate<'tcx>> {
573 /// Returns the "principal def id" of this set of existential predicates.
575 /// A Rust trait object type consists (in addition to a lifetime bound)
576 /// of a set of trait bounds, which are separated into any number
577 /// of auto-trait bounds, and at most 1 non-auto-trait bound. The
578 /// non-auto-trait bound is called the "principal" of the trait
581 /// Only the principal can have methods or type parameters (because
582 /// auto traits can have neither of them). This is important, because
583 /// it means the auto traits can be treated as an unordered set (methods
584 /// would force an order for the vtable, while relating traits with
585 /// type parameters without knowing the order to relate them in is
586 /// a rather non-trivial task).
588 /// For example, in the trait object `dyn fmt::Debug + Sync`, the
589 /// principal bound is `Some(fmt::Debug)`, while the auto-trait bounds
590 /// are the set `{Sync}`.
592 /// It is also possible to have a "trivial" trait object that
593 /// consists only of auto traits, with no principal - for example,
594 /// `dyn Send + Sync`. In that case, the set of auto-trait bounds
595 /// is `{Send, Sync}`, while there is no principal. These trait objects
596 /// have a "trivial" vtable consisting of just the size, alignment,
598 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
600 ExistentialPredicate::Trait(tr) => Some(tr),
605 pub fn principal_def_id(&self) -> Option<DefId> {
606 self.principal().map(|d| d.def_id)
610 pub fn projection_bounds<'a>(&'a self) ->
611 impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
612 self.iter().filter_map(|predicate| {
614 ExistentialPredicate::Projection(p) => Some(p),
621 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
622 self.iter().filter_map(|predicate| {
624 ExistentialPredicate::AutoTrait(d) => Some(d),
631 impl<'tcx> Binder<&'tcx List<ExistentialPredicate<'tcx>>> {
632 pub fn principal(&self) -> Option<ty::Binder<ExistentialTraitRef<'tcx>>> {
633 self.skip_binder().principal().map(Binder::bind)
636 pub fn principal_def_id(&self) -> Option<DefId> {
637 self.skip_binder().principal_def_id()
641 pub fn projection_bounds<'a>(&'a self) ->
642 impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
643 self.skip_binder().projection_bounds().map(Binder::bind)
647 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
648 self.skip_binder().auto_traits()
651 pub fn iter<'a>(&'a self)
652 -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
653 self.skip_binder().iter().cloned().map(Binder::bind)
657 /// A complete reference to a trait. These take numerous guises in syntax,
658 /// but perhaps the most recognizable form is in a where-clause:
662 /// This would be represented by a trait-reference where the `DefId` is the
663 /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0,
664 /// and `U` as parameter 1.
666 /// Trait references also appear in object types like `Foo<U>`, but in
667 /// that case the `Self` parameter is absent from the substitutions.
669 /// Note that a `TraitRef` introduces a level of region binding, to
670 /// account for higher-ranked trait bounds like `T: for<'a> Foo<&'a U>`
671 /// or higher-ranked object types.
672 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
673 pub struct TraitRef<'tcx> {
675 pub substs: &'tcx Substs<'tcx>,
678 impl<'tcx> TraitRef<'tcx> {
679 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
680 TraitRef { def_id: def_id, substs: substs }
683 /// Returns a `TraitRef` of the form `P0: Foo<P1..Pn>` where `Pi`
684 /// are the parameters defined on trait.
685 pub fn identity<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, def_id: DefId) -> TraitRef<'tcx> {
688 substs: Substs::identity_for_item(tcx, def_id),
693 pub fn self_ty(&self) -> Ty<'tcx> {
694 self.substs.type_at(0)
697 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
698 // Select only the "input types" from a trait-reference. For
699 // now this is all the types that appear in the
700 // trait-reference, but it should eventually exclude
705 pub fn from_method(tcx: TyCtxt<'_, '_, 'tcx>,
707 substs: &Substs<'tcx>)
708 -> ty::TraitRef<'tcx> {
709 let defs = tcx.generics_of(trait_id);
713 substs: tcx.intern_substs(&substs[..defs.params.len()])
718 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
720 impl<'tcx> PolyTraitRef<'tcx> {
721 pub fn self_ty(&self) -> Ty<'tcx> {
722 self.skip_binder().self_ty()
725 pub fn def_id(&self) -> DefId {
726 self.skip_binder().def_id
729 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
730 // Note that we preserve binding levels
731 Binder(ty::TraitPredicate { trait_ref: self.skip_binder().clone() })
735 /// An existential reference to a trait, where `Self` is erased.
736 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
738 /// exists T. T: Trait<'a, 'b, X, Y>
740 /// The substitutions don't include the erased `Self`, only trait
741 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
742 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
743 pub struct ExistentialTraitRef<'tcx> {
745 pub substs: &'tcx Substs<'tcx>,
748 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
749 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
750 // Select only the "input types" from a trait-reference. For
751 // now this is all the types that appear in the
752 // trait-reference, but it should eventually exclude
757 pub fn erase_self_ty(tcx: TyCtxt<'a, 'gcx, 'tcx>,
758 trait_ref: ty::TraitRef<'tcx>)
759 -> ty::ExistentialTraitRef<'tcx> {
760 // Assert there is a Self.
761 trait_ref.substs.type_at(0);
763 ty::ExistentialTraitRef {
764 def_id: trait_ref.def_id,
765 substs: tcx.intern_substs(&trait_ref.substs[1..])
769 /// Object types don't have a self type specified. Therefore, when
770 /// we convert the principal trait-ref into a normal trait-ref,
771 /// you must give *some* self type. A common choice is `mk_err()`
772 /// or some placeholder type.
773 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
774 -> ty::TraitRef<'tcx> {
775 // otherwise the escaping vars would be captured by the binder
776 // debug_assert!(!self_ty.has_escaping_bound_vars());
780 substs: tcx.mk_substs_trait(self_ty, self.substs)
785 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
787 impl<'tcx> PolyExistentialTraitRef<'tcx> {
788 pub fn def_id(&self) -> DefId {
789 self.skip_binder().def_id
792 /// Object types don't have a self type specified. Therefore, when
793 /// we convert the principal trait-ref into a normal trait-ref,
794 /// you must give *some* self type. A common choice is `mk_err()`
795 /// or some placeholder type.
796 pub fn with_self_ty(&self, tcx: TyCtxt<'_, '_, 'tcx>,
798 -> ty::PolyTraitRef<'tcx> {
799 self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
803 /// Binder is a binder for higher-ranked lifetimes or types. It is part of the
804 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
805 /// (which would be represented by the type `PolyTraitRef ==
806 /// Binder<TraitRef>`). Note that when we instantiate,
807 /// erase, or otherwise "discharge" these bound vars, we change the
808 /// type from `Binder<T>` to just `T` (see
809 /// e.g., `liberate_late_bound_regions`).
810 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
811 pub struct Binder<T>(T);
814 /// Wraps `value` in a binder, asserting that `value` does not
815 /// contain any bound vars that would be bound by the
816 /// binder. This is commonly used to 'inject' a value T into a
817 /// different binding level.
818 pub fn dummy<'tcx>(value: T) -> Binder<T>
819 where T: TypeFoldable<'tcx>
821 debug_assert!(!value.has_escaping_bound_vars());
825 /// Wraps `value` in a binder, binding higher-ranked vars (if any).
826 pub fn bind<'tcx>(value: T) -> Binder<T> {
830 /// Skips the binder and returns the "bound" value. This is a
831 /// risky thing to do because it's easy to get confused about
832 /// De Bruijn indices and the like. It is usually better to
833 /// discharge the binder using `no_bound_vars` or
834 /// `replace_late_bound_regions` or something like
835 /// that. `skip_binder` is only valid when you are either
836 /// extracting data that has nothing to do with bound vars, you
837 /// are doing some sort of test that does not involve bound
838 /// regions, or you are being very careful about your depth
841 /// Some examples where `skip_binder` is reasonable:
843 /// - extracting the `DefId` from a PolyTraitRef;
844 /// - comparing the self type of a PolyTraitRef to see if it is equal to
845 /// a type parameter `X`, since the type `X` does not reference any regions
846 pub fn skip_binder(&self) -> &T {
850 pub fn as_ref(&self) -> Binder<&T> {
854 pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
855 where F: FnOnce(&T) -> U
857 self.as_ref().map_bound(f)
860 pub fn map_bound<F, U>(self, f: F) -> Binder<U>
861 where F: FnOnce(T) -> U
866 /// Unwraps and returns the value within, but only if it contains
867 /// no bound vars at all. (In other words, if this binder --
868 /// and indeed any enclosing binder -- doesn't bind anything at
869 /// all.) Otherwise, returns `None`.
871 /// (One could imagine having a method that just unwraps a single
872 /// binder, but permits late-bound vars bound by enclosing
873 /// binders, but that would require adjusting the debruijn
874 /// indices, and given the shallow binding structure we often use,
875 /// would not be that useful.)
876 pub fn no_bound_vars<'tcx>(self) -> Option<T>
877 where T: TypeFoldable<'tcx>
879 if self.skip_binder().has_escaping_bound_vars() {
882 Some(self.skip_binder().clone())
886 /// Given two things that have the same binder level,
887 /// and an operation that wraps on their contents, executes the operation
888 /// and then wraps its result.
890 /// `f` should consider bound regions at depth 1 to be free, and
891 /// anything it produces with bound regions at depth 1 will be
892 /// bound in the resulting return value.
893 pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
894 where F: FnOnce(T, U) -> R
896 Binder(f(self.0, u.0))
899 /// Splits the contents into two things that share the same binder
900 /// level as the original, returning two distinct binders.
902 /// `f` should consider bound regions at depth 1 to be free, and
903 /// anything it produces with bound regions at depth 1 will be
904 /// bound in the resulting return values.
905 pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
906 where F: FnOnce(T) -> (U, V)
908 let (u, v) = f(self.0);
909 (Binder(u), Binder(v))
913 /// Represents the projection of an associated type. In explicit UFCS
914 /// form this would be written `<T as Trait<..>>::N`.
915 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
916 pub struct ProjectionTy<'tcx> {
917 /// The parameters of the associated item.
918 pub substs: &'tcx Substs<'tcx>,
920 /// The `DefId` of the `TraitItem` for the associated type `N`.
922 /// Note that this is not the `DefId` of the `TraitRef` containing this
923 /// associated type, which is in `tcx.associated_item(item_def_id).container`.
924 pub item_def_id: DefId,
927 impl<'a, 'tcx> ProjectionTy<'tcx> {
928 /// Construct a `ProjectionTy` by searching the trait from `trait_ref` for the
929 /// associated item named `item_name`.
930 pub fn from_ref_and_name(
931 tcx: TyCtxt<'_, '_, '_>, trait_ref: ty::TraitRef<'tcx>, item_name: Ident
932 ) -> ProjectionTy<'tcx> {
933 let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
934 item.kind == ty::AssociatedKind::Type &&
935 tcx.hygienic_eq(item_name, item.ident, trait_ref.def_id)
939 substs: trait_ref.substs,
944 /// Extracts the underlying trait reference from this projection.
945 /// For example, if this is a projection of `<T as Iterator>::Item`,
946 /// then this function would return a `T: Iterator` trait reference.
947 pub fn trait_ref(&self, tcx: TyCtxt<'_, '_, '_>) -> ty::TraitRef<'tcx> {
948 let def_id = tcx.associated_item(self.item_def_id).container.id();
955 pub fn self_ty(&self) -> Ty<'tcx> {
956 self.substs.type_at(0)
960 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
961 pub struct GenSig<'tcx> {
962 pub yield_ty: Ty<'tcx>,
963 pub return_ty: Ty<'tcx>,
966 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
968 impl<'tcx> PolyGenSig<'tcx> {
969 pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
970 self.map_bound_ref(|sig| sig.yield_ty)
972 pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
973 self.map_bound_ref(|sig| sig.return_ty)
977 /// Signature of a function type, which I have arbitrarily
978 /// decided to use to refer to the input/output types.
980 /// - `inputs` is the list of arguments and their modes.
981 /// - `output` is the return type.
982 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
983 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
984 pub struct FnSig<'tcx> {
985 pub inputs_and_output: &'tcx List<Ty<'tcx>>,
987 pub unsafety: hir::Unsafety,
991 impl<'tcx> FnSig<'tcx> {
992 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
993 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
996 pub fn output(&self) -> Ty<'tcx> {
997 self.inputs_and_output[self.inputs_and_output.len() - 1]
1001 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1003 impl<'tcx> PolyFnSig<'tcx> {
1005 pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
1006 self.map_bound_ref(|fn_sig| fn_sig.inputs())
1009 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
1010 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
1012 pub fn inputs_and_output(&self) -> ty::Binder<&'tcx List<Ty<'tcx>>> {
1013 self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
1016 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
1017 self.map_bound_ref(|fn_sig| fn_sig.output())
1019 pub fn variadic(&self) -> bool {
1020 self.skip_binder().variadic
1022 pub fn unsafety(&self) -> hir::Unsafety {
1023 self.skip_binder().unsafety
1025 pub fn abi(&self) -> abi::Abi {
1026 self.skip_binder().abi
1030 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<FnSig<'tcx>>>;
1033 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1034 pub struct ParamTy {
1036 pub name: InternedString,
1039 impl<'a, 'gcx, 'tcx> ParamTy {
1040 pub fn new(index: u32, name: InternedString) -> ParamTy {
1041 ParamTy { idx: index, name: name }
1044 pub fn for_self() -> ParamTy {
1045 ParamTy::new(0, keywords::SelfUpper.name().as_interned_str())
1048 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1049 ParamTy::new(def.index, def.name)
1052 pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1053 tcx.mk_ty_param(self.idx, self.name)
1056 pub fn is_self(&self) -> bool {
1057 // FIXME(#50125): Ignoring `Self` with `idx != 0` might lead to weird behavior elsewhere,
1058 // but this should only be possible when using `-Z continue-parse-after-error` like
1059 // `compile-fail/issue-36638.rs`.
1060 self.name == keywords::SelfUpper.name().as_str() && self.idx == 0
1064 /// A [De Bruijn index][dbi] is a standard means of representing
1065 /// regions (and perhaps later types) in a higher-ranked setting. In
1066 /// particular, imagine a type like this:
1068 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1071 /// | +------------+ 0 | |
1073 /// +--------------------------------+ 1 |
1075 /// +------------------------------------------+ 0
1077 /// In this type, there are two binders (the outer fn and the inner
1078 /// fn). We need to be able to determine, for any given region, which
1079 /// fn type it is bound by, the inner or the outer one. There are
1080 /// various ways you can do this, but a De Bruijn index is one of the
1081 /// more convenient and has some nice properties. The basic idea is to
1082 /// count the number of binders, inside out. Some examples should help
1083 /// clarify what I mean.
1085 /// Let's start with the reference type `&'b isize` that is the first
1086 /// argument to the inner function. This region `'b` is assigned a De
1087 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
1088 /// fn). The region `'a` that appears in the second argument type (`&'a
1089 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
1090 /// second-innermost binder". (These indices are written on the arrays
1091 /// in the diagram).
1093 /// What is interesting is that De Bruijn index attached to a particular
1094 /// variable will vary depending on where it appears. For example,
1095 /// the final type `&'a char` also refers to the region `'a` declared on
1096 /// the outermost fn. But this time, this reference is not nested within
1097 /// any other binders (i.e., it is not an argument to the inner fn, but
1098 /// rather the outer one). Therefore, in this case, it is assigned a
1099 /// De Bruijn index of 0, because the innermost binder in that location
1100 /// is the outer fn.
1102 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1104 pub struct DebruijnIndex {
1105 DEBUG_FORMAT = "DebruijnIndex({})",
1106 const INNERMOST = 0,
1110 pub type Region<'tcx> = &'tcx RegionKind;
1112 /// Representation of regions.
1114 /// Unlike types, most region variants are "fictitious", not concrete,
1115 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1116 /// ones representing concrete regions.
1118 /// ## Bound Regions
1120 /// These are regions that are stored behind a binder and must be substituted
1121 /// with some concrete region before being used. There are two kind of
1122 /// bound regions: early-bound, which are bound in an item's `Generics`,
1123 /// and are substituted by a `Substs`, and late-bound, which are part of
1124 /// higher-ranked types (e.g., `for<'a> fn(&'a ())`), and are substituted by
1125 /// the likes of `liberate_late_bound_regions`. The distinction exists
1126 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1128 /// Unlike `Param`s, bound regions are not supposed to exist "in the wild"
1129 /// outside their binder, e.g., in types passed to type inference, and
1130 /// should first be substituted (by placeholder regions, free regions,
1131 /// or region variables).
1133 /// ## Placeholder and Free Regions
1135 /// One often wants to work with bound regions without knowing their precise
1136 /// identity. For example, when checking a function, the lifetime of a borrow
1137 /// can end up being assigned to some region parameter. In these cases,
1138 /// it must be ensured that bounds on the region can't be accidentally
1139 /// assumed without being checked.
1141 /// To do this, we replace the bound regions with placeholder markers,
1142 /// which don't satisfy any relation not explicitly provided.
1144 /// There are two kinds of placeholder regions in rustc: `ReFree` and
1145 /// `RePlaceholder`. When checking an item's body, `ReFree` is supposed
1146 /// to be used. These also support explicit bounds: both the internally-stored
1147 /// *scope*, which the region is assumed to outlive, as well as other
1148 /// relations stored in the `FreeRegionMap`. Note that these relations
1149 /// aren't checked when you `make_subregion` (or `eq_types`), only by
1150 /// `resolve_regions_and_report_errors`.
1152 /// When working with higher-ranked types, some region relations aren't
1153 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1154 /// `RePlaceholder` is designed for this purpose. In these contexts,
1155 /// there's also the risk that some inference variable laying around will
1156 /// get unified with your placeholder region: if you want to check whether
1157 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1158 /// with a placeholder region `'%a`, the variable `'_` would just be
1159 /// instantiated to the placeholder region `'%a`, which is wrong because
1160 /// the inference variable is supposed to satisfy the relation
1161 /// *for every value of the placeholder region*. To ensure that doesn't
1162 /// happen, you can use `leak_check`. This is more clearly explained
1163 /// by the [rustc guide].
1165 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1166 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1167 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/hrtb.html
1168 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1169 pub enum RegionKind {
1170 /// Region bound in a type or fn declaration which will be
1171 /// substituted 'early' -- that is, at the same time when type
1172 /// parameters are substituted.
1173 ReEarlyBound(EarlyBoundRegion),
1175 /// Region bound in a function scope, which will be substituted when the
1176 /// function is called.
1177 ReLateBound(DebruijnIndex, BoundRegion),
1179 /// When checking a function body, the types of all arguments and so forth
1180 /// that refer to bound region parameters are modified to refer to free
1181 /// region parameters.
1184 /// A concrete region naming some statically determined scope
1185 /// (e.g., an expression or sequence of statements) within the
1186 /// current function.
1187 ReScope(region::Scope),
1189 /// Static data that has an "infinite" lifetime. Top in the region lattice.
1192 /// A region variable. Should not exist after typeck.
1195 /// A placeholder region - basically the higher-ranked version of ReFree.
1196 /// Should not exist after typeck.
1197 RePlaceholder(ty::PlaceholderRegion),
1199 /// Empty lifetime is for data that is never accessed.
1200 /// Bottom in the region lattice. We treat ReEmpty somewhat
1201 /// specially; at least right now, we do not generate instances of
1202 /// it during the GLB computations, but rather
1203 /// generate an error instead. This is to improve error messages.
1204 /// The only way to get an instance of ReEmpty is to have a region
1205 /// variable with no constraints.
1208 /// Erased region, used by trait selection, in MIR and during codegen.
1211 /// These are regions bound in the "defining type" for a
1212 /// closure. They are used ONLY as part of the
1213 /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1214 /// See `ClosureRegionRequirements` for more details.
1215 ReClosureBound(RegionVid),
1218 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1220 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1221 pub struct EarlyBoundRegion {
1224 pub name: InternedString,
1227 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1232 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1237 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1238 pub struct FloatVid {
1243 pub struct RegionVid {
1244 DEBUG_FORMAT = custom,
1248 impl Atom for RegionVid {
1249 fn index(self) -> usize {
1254 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1260 /// A `FreshTy` is one that is generated as a replacement for an
1261 /// unbound type variable. This is convenient for caching etc. See
1262 /// `infer::freshen` for more details.
1269 pub struct BoundVar { .. }
1272 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1273 pub struct BoundTy {
1275 pub kind: BoundTyKind,
1278 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1279 pub enum BoundTyKind {
1281 Param(InternedString),
1284 impl_stable_hash_for!(struct BoundTy { var, kind });
1285 impl_stable_hash_for!(enum self::BoundTyKind { Anon, Param(a) });
1287 impl From<BoundVar> for BoundTy {
1288 fn from(var: BoundVar) -> Self {
1291 kind: BoundTyKind::Anon,
1296 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1297 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1298 pub struct ExistentialProjection<'tcx> {
1299 pub item_def_id: DefId,
1300 pub substs: &'tcx Substs<'tcx>,
1304 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1306 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1307 /// Extracts the underlying existential trait reference from this projection.
1308 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1309 /// then this function would return a `exists T. T: Iterator` existential trait
1311 pub fn trait_ref(&self, tcx: TyCtxt<'_, '_, '_>) -> ty::ExistentialTraitRef<'tcx> {
1312 let def_id = tcx.associated_item(self.item_def_id).container.id();
1313 ty::ExistentialTraitRef{
1315 substs: self.substs,
1319 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1321 -> ty::ProjectionPredicate<'tcx>
1323 // otherwise the escaping regions would be captured by the binders
1324 debug_assert!(!self_ty.has_escaping_bound_vars());
1326 ty::ProjectionPredicate {
1327 projection_ty: ty::ProjectionTy {
1328 item_def_id: self.item_def_id,
1329 substs: tcx.mk_substs_trait(self_ty, self.substs),
1336 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
1337 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
1338 -> ty::PolyProjectionPredicate<'tcx> {
1339 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1342 pub fn item_def_id(&self) -> DefId {
1343 return self.skip_binder().item_def_id;
1347 impl DebruijnIndex {
1348 /// Returns the resulting index when this value is moved into
1349 /// `amount` number of new binders. So, e.g., if you had
1351 /// for<'a> fn(&'a x)
1353 /// and you wanted to change it to
1355 /// for<'a> fn(for<'b> fn(&'a x))
1357 /// you would need to shift the index for `'a` into a new binder.
1359 pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
1360 DebruijnIndex::from_u32(self.as_u32() + amount)
1363 /// Update this index in place by shifting it "in" through
1364 /// `amount` number of binders.
1365 pub fn shift_in(&mut self, amount: u32) {
1366 *self = self.shifted_in(amount);
1369 /// Returns the resulting index when this value is moved out from
1370 /// `amount` number of new binders.
1372 pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
1373 DebruijnIndex::from_u32(self.as_u32() - amount)
1376 /// Update in place by shifting out from `amount` binders.
1377 pub fn shift_out(&mut self, amount: u32) {
1378 *self = self.shifted_out(amount);
1381 /// Adjusts any De Bruijn indices so as to make `to_binder` the
1382 /// innermost binder. That is, if we have something bound at `to_binder`,
1383 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1384 /// when moving a region out from inside binders:
1387 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1388 /// // Binder: D3 D2 D1 ^^
1391 /// Here, the region `'a` would have the De Bruijn index D3,
1392 /// because it is the bound 3 binders out. However, if we wanted
1393 /// to refer to that region `'a` in the second argument (the `_`),
1394 /// those two binders would not be in scope. In that case, we
1395 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1396 /// De Bruijn index of `'a` to D1 (the innermost binder).
1398 /// If we invoke `shift_out_to_binder` and the region is in fact
1399 /// bound by one of the binders we are shifting out of, that is an
1400 /// error (and should fail an assertion failure).
1401 pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
1402 self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
1406 impl_stable_hash_for!(struct DebruijnIndex { private });
1408 /// Region utilities
1410 /// Is this region named by the user?
1411 pub fn has_name(&self) -> bool {
1413 RegionKind::ReEarlyBound(ebr) => ebr.has_name(),
1414 RegionKind::ReLateBound(_, br) => br.is_named(),
1415 RegionKind::ReFree(fr) => fr.bound_region.is_named(),
1416 RegionKind::ReScope(..) => false,
1417 RegionKind::ReStatic => true,
1418 RegionKind::ReVar(..) => false,
1419 RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(),
1420 RegionKind::ReEmpty => false,
1421 RegionKind::ReErased => false,
1422 RegionKind::ReClosureBound(..) => false,
1426 pub fn is_late_bound(&self) -> bool {
1428 ty::ReLateBound(..) => true,
1433 pub fn is_placeholder(&self) -> bool {
1435 ty::RePlaceholder(..) => true,
1440 pub fn bound_at_or_above_binder(&self, index: DebruijnIndex) -> bool {
1442 ty::ReLateBound(debruijn, _) => debruijn >= index,
1447 /// Adjusts any De Bruijn indices so as to make `to_binder` the
1448 /// innermost binder. That is, if we have something bound at `to_binder`,
1449 /// it will now be bound at INNERMOST. This is an appropriate thing to do
1450 /// when moving a region out from inside binders:
1453 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
1454 /// // Binder: D3 D2 D1 ^^
1457 /// Here, the region `'a` would have the De Bruijn index D3,
1458 /// because it is the bound 3 binders out. However, if we wanted
1459 /// to refer to that region `'a` in the second argument (the `_`),
1460 /// those two binders would not be in scope. In that case, we
1461 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1462 /// De Bruijn index of `'a` to D1 (the innermost binder).
1464 /// If we invoke `shift_out_to_binder` and the region is in fact
1465 /// bound by one of the binders we are shifting out of, that is an
1466 /// error (and should fail an assertion failure).
1467 pub fn shifted_out_to_binder(&self, to_binder: ty::DebruijnIndex) -> RegionKind {
1469 ty::ReLateBound(debruijn, r) => ty::ReLateBound(
1470 debruijn.shifted_out_to_binder(to_binder),
1477 pub fn keep_in_local_tcx(&self) -> bool {
1478 if let ty::ReVar(..) = self {
1485 pub fn type_flags(&self) -> TypeFlags {
1486 let mut flags = TypeFlags::empty();
1488 if self.keep_in_local_tcx() {
1489 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1494 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1495 flags = flags | TypeFlags::HAS_RE_INFER;
1497 ty::RePlaceholder(..) => {
1498 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1499 flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
1501 ty::ReLateBound(..) => {
1502 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1504 ty::ReEarlyBound(..) => {
1505 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1506 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1511 ty::ReScope { .. } => {
1512 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1516 ty::ReClosureBound(..) => {
1517 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1522 ty::ReStatic | ty::ReEmpty | ty::ReErased | ty::ReLateBound(..) => (),
1523 _ => flags = flags | TypeFlags::HAS_FREE_LOCAL_NAMES,
1526 debug!("type_flags({:?}) = {:?}", self, flags);
1531 /// Given an early-bound or free region, returns the `DefId` where it was bound.
1532 /// For example, consider the regions in this snippet of code:
1536 /// ^^ -- early bound, declared on an impl
1538 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1539 /// ^^ ^^ ^ anonymous, late-bound
1540 /// | early-bound, appears in where-clauses
1541 /// late-bound, appears only in fn args
1546 /// Here, `free_region_binding_scope('a)` would return the `DefId`
1547 /// of the impl, and for all the other highlighted regions, it
1548 /// would return the `DefId` of the function. In other cases (not shown), this
1549 /// function might return the `DefId` of a closure.
1550 pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_, '_, '_>) -> DefId {
1552 ty::ReEarlyBound(br) => {
1553 tcx.parent_def_id(br.def_id).unwrap()
1555 ty::ReFree(fr) => fr.scope,
1556 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1562 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
1563 pub fn is_unit(&self) -> bool {
1565 Tuple(ref tys) => tys.is_empty(),
1570 pub fn is_never(&self) -> bool {
1577 /// Checks whether a type is definitely uninhabited. This is
1578 /// conservative: for some types that are uninhabited we return `false`,
1579 /// but we only return `true` for types that are definitely uninhabited.
1580 /// `ty.conservative_is_privately_uninhabited` implies that any value of type `ty`
1581 /// will be `Abi::Uninhabited`. (Note that uninhabited types may have nonzero
1582 /// size, to account for partial initialisation. See #49298 for details.)
1583 pub fn conservative_is_privately_uninhabited(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1584 // FIXME(varkor): we can make this less conversative by substituting concrete
1588 ty::Adt(def, _) if def.is_union() => {
1589 // For now, `union`s are never considered uninhabited.
1592 ty::Adt(def, _) => {
1593 // Any ADT is uninhabited if either:
1594 // (a) It has no variants (i.e. an empty `enum`);
1595 // (b) Each of its variants (a single one in the case of a `struct`) has at least
1596 // one uninhabited field.
1597 def.variants.iter().all(|var| {
1598 var.fields.iter().any(|field| {
1599 tcx.type_of(field.did).conservative_is_privately_uninhabited(tcx)
1603 ty::Tuple(tys) => tys.iter().any(|ty| ty.conservative_is_privately_uninhabited(tcx)),
1604 ty::Array(ty, len) => {
1605 match len.assert_usize(tcx) {
1606 // If the array is definitely non-empty, it's uninhabited if
1607 // the type of its elements is uninhabited.
1608 Some(n) if n != 0 => ty.conservative_is_privately_uninhabited(tcx),
1613 // References to uninitialised memory is valid for any type, including
1614 // uninhabited types, in unsafe code, so we treat all references as
1622 pub fn is_primitive(&self) -> bool {
1624 Bool | Char | Int(_) | Uint(_) | Float(_) => true,
1630 pub fn is_ty_var(&self) -> bool {
1632 Infer(TyVar(_)) => true,
1637 pub fn is_ty_infer(&self) -> bool {
1644 pub fn is_phantom_data(&self) -> bool {
1645 if let Adt(def, _) = self.sty {
1646 def.is_phantom_data()
1652 pub fn is_bool(&self) -> bool { self.sty == Bool }
1654 pub fn is_param(&self, index: u32) -> bool {
1656 ty::Param(ref data) => data.idx == index,
1661 pub fn is_self(&self) -> bool {
1663 Param(ref p) => p.is_self(),
1668 pub fn is_slice(&self) -> bool {
1670 RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => match ty.sty {
1671 Slice(_) | Str => true,
1679 pub fn is_simd(&self) -> bool {
1681 Adt(def, _) => def.repr.simd(),
1686 pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1688 Array(ty, _) | Slice(ty) => ty,
1689 Str => tcx.mk_mach_uint(ast::UintTy::U8),
1690 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1694 pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1696 Adt(def, substs) => {
1697 def.non_enum_variant().fields[0].ty(tcx, substs)
1699 _ => bug!("simd_type called on invalid type")
1703 pub fn simd_size(&self, _cx: TyCtxt<'_, '_, '_>) -> usize {
1705 Adt(def, _) => def.non_enum_variant().fields.len(),
1706 _ => bug!("simd_size called on invalid type")
1710 pub fn is_region_ptr(&self) -> bool {
1717 pub fn is_mutable_pointer(&self) -> bool {
1719 RawPtr(TypeAndMut { mutbl: hir::Mutability::MutMutable, .. }) |
1720 Ref(_, _, hir::Mutability::MutMutable) => true,
1725 pub fn is_unsafe_ptr(&self) -> bool {
1727 RawPtr(_) => return true,
1732 /// Returns `true` if this type is an `Arc<T>`.
1733 pub fn is_arc(&self) -> bool {
1735 Adt(def, _) => def.is_arc(),
1740 /// Returns `true` if this type is an `Rc<T>`.
1741 pub fn is_rc(&self) -> bool {
1743 Adt(def, _) => def.is_rc(),
1748 pub fn is_box(&self) -> bool {
1750 Adt(def, _) => def.is_box(),
1755 /// panics if called on any type other than `Box<T>`
1756 pub fn boxed_ty(&self) -> Ty<'tcx> {
1758 Adt(def, substs) if def.is_box() => substs.type_at(0),
1759 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1763 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1764 /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1765 /// contents are abstract to rustc.)
1766 pub fn is_scalar(&self) -> bool {
1768 Bool | Char | Int(_) | Float(_) | Uint(_) |
1769 Infer(IntVar(_)) | Infer(FloatVar(_)) |
1770 FnDef(..) | FnPtr(_) | RawPtr(_) => true,
1775 /// Returns `true` if this type is a floating point type.
1776 pub fn is_floating_point(&self) -> bool {
1779 Infer(FloatVar(_)) => true,
1784 pub fn is_trait(&self) -> bool {
1786 Dynamic(..) => true,
1791 pub fn is_enum(&self) -> bool {
1793 Adt(adt_def, _) => {
1800 pub fn is_closure(&self) -> bool {
1802 Closure(..) => true,
1807 pub fn is_generator(&self) -> bool {
1809 Generator(..) => true,
1815 pub fn is_integral(&self) -> bool {
1817 Infer(IntVar(_)) | Int(_) | Uint(_) => true,
1822 pub fn is_fresh_ty(&self) -> bool {
1824 Infer(FreshTy(_)) => true,
1829 pub fn is_fresh(&self) -> bool {
1831 Infer(FreshTy(_)) => true,
1832 Infer(FreshIntTy(_)) => true,
1833 Infer(FreshFloatTy(_)) => true,
1838 pub fn is_char(&self) -> bool {
1846 pub fn is_fp(&self) -> bool {
1848 Infer(FloatVar(_)) | Float(_) => true,
1853 pub fn is_numeric(&self) -> bool {
1854 self.is_integral() || self.is_fp()
1857 pub fn is_signed(&self) -> bool {
1864 pub fn is_pointer_sized(&self) -> bool {
1866 Int(ast::IntTy::Isize) | Uint(ast::UintTy::Usize) => true,
1871 pub fn is_machine(&self) -> bool {
1873 Int(ast::IntTy::Isize) | Uint(ast::UintTy::Usize) => false,
1874 Int(..) | Uint(..) | Float(..) => true,
1879 pub fn has_concrete_skeleton(&self) -> bool {
1881 Param(_) | Infer(_) | Error => false,
1886 /// Returns the type and mutability of `*ty`.
1888 /// The parameter `explicit` indicates if this is an *explicit* dereference.
1889 /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
1890 pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1892 Adt(def, _) if def.is_box() => {
1894 ty: self.boxed_ty(),
1895 mutbl: hir::MutImmutable,
1898 Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
1899 RawPtr(mt) if explicit => Some(mt),
1904 /// Returns the type of `ty[i]`.
1905 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1907 Array(ty, _) | Slice(ty) => Some(ty),
1912 pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1914 FnDef(def_id, substs) => {
1915 tcx.fn_sig(def_id).subst(tcx, substs)
1918 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1922 pub fn is_fn(&self) -> bool {
1924 FnDef(..) | FnPtr(_) => true,
1929 pub fn is_impl_trait(&self) -> bool {
1937 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1939 Adt(adt, _) => Some(adt),
1944 /// Push onto `out` the regions directly referenced from this type (but not
1945 /// types reachable from this type via `walk_tys`). This ignores late-bound
1946 /// regions binders.
1947 pub fn push_regions(&self, out: &mut SmallVec<[ty::Region<'tcx>; 4]>) {
1949 Ref(region, _, _) => {
1952 Dynamic(ref obj, region) => {
1954 if let Some(principal) = obj.principal() {
1955 out.extend(principal.skip_binder().substs.regions());
1958 Adt(_, substs) | Opaque(_, substs) => {
1959 out.extend(substs.regions())
1961 Closure(_, ClosureSubsts { ref substs }) |
1962 Generator(_, GeneratorSubsts { ref substs }, _) => {
1963 out.extend(substs.regions())
1965 Projection(ref data) | UnnormalizedProjection(ref data) => {
1966 out.extend(data.substs.regions())
1970 GeneratorWitness(..) |
1991 /// When we create a closure, we record its kind (i.e., what trait
1992 /// it implements) into its `ClosureSubsts` using a type
1993 /// parameter. This is kind of a phantom type, except that the
1994 /// most convenient thing for us to are the integral types. This
1995 /// function converts such a special type into the closure
1996 /// kind. To go the other way, use
1997 /// `tcx.closure_kind_ty(closure_kind)`.
1999 /// Note that during type checking, we use an inference variable
2000 /// to represent the closure kind, because it has not yet been
2001 /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
2002 /// is complete, that type variable will be unified.
2003 pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
2005 Int(int_ty) => match int_ty {
2006 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
2007 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
2008 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
2009 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2014 Error => Some(ty::ClosureKind::Fn),
2016 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2020 /// Fast path helper for testing if a type is `Sized`.
2022 /// Returning true means the type is known to be sized. Returning
2023 /// `false` means nothing -- could be sized, might not be.
2024 pub fn is_trivially_sized(&self, tcx: TyCtxt<'_, '_, 'tcx>) -> bool {
2026 ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
2027 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
2028 ty::FnDef(..) | ty::FnPtr(_) | ty::RawPtr(..) |
2029 ty::Char | ty::Ref(..) | ty::Generator(..) |
2030 ty::GeneratorWitness(..) | ty::Array(..) | ty::Closure(..) |
2031 ty::Never | ty::Error =>
2034 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) =>
2038 tys.iter().all(|ty| ty.is_trivially_sized(tcx)),
2040 ty::Adt(def, _substs) =>
2041 def.sized_constraint(tcx).is_empty(),
2043 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
2045 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
2047 ty::Infer(ty::TyVar(_)) => false,
2050 ty::Placeholder(..) |
2051 ty::Infer(ty::FreshTy(_)) |
2052 ty::Infer(ty::FreshIntTy(_)) |
2053 ty::Infer(ty::FreshFloatTy(_)) =>
2054 bug!("is_trivially_sized applied to unexpected type: {:?}", self),
2059 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Eq, PartialEq, Ord, PartialOrd)]
2060 /// Used in the HIR by using `Unevaluated` everywhere and later normalizing to `Evaluated` if the
2061 /// code is monomorphic enough for that.
2062 pub enum LazyConst<'tcx> {
2063 Unevaluated(DefId, &'tcx Substs<'tcx>),
2064 Evaluated(Const<'tcx>),
2067 #[cfg(target_arch = "x86_64")]
2068 static_assert!(LAZY_CONST_SIZE: ::std::mem::size_of::<LazyConst<'static>>() == 56);
2070 impl<'tcx> LazyConst<'tcx> {
2071 pub fn map_evaluated<R>(self, f: impl FnOnce(Const<'tcx>) -> Option<R>) -> Option<R> {
2073 LazyConst::Evaluated(c) => f(c),
2074 LazyConst::Unevaluated(..) => None,
2078 pub fn assert_usize(self, tcx: TyCtxt<'_, '_, '_>) -> Option<u64> {
2079 self.map_evaluated(|c| c.assert_usize(tcx))
2083 pub fn unwrap_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> u64 {
2084 self.assert_usize(tcx).expect("expected `LazyConst` to contain a usize")
2088 /// Typed constant value.
2089 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Eq, PartialEq, Ord, PartialOrd)]
2090 pub struct Const<'tcx> {
2093 pub val: ConstValue<'tcx>,
2096 #[cfg(target_arch = "x86_64")]
2097 static_assert!(CONST_SIZE: ::std::mem::size_of::<Const<'static>>() == 48);
2099 impl<'tcx> Const<'tcx> {
2106 val: ConstValue::Scalar(val),
2113 tcx: TyCtxt<'_, '_, 'tcx>,
2115 ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2117 let ty = tcx.lift_to_global(&ty).unwrap();
2118 let size = tcx.layout_of(ty).unwrap_or_else(|e| {
2119 panic!("could not compute layout for {:?}: {:?}", ty, e)
2121 let truncated = truncate(bits, size);
2122 assert_eq!(truncated, bits, "from_bits called with untruncated value");
2123 Self::from_scalar(Scalar::Bits { bits, size: size.bytes() as u8 }, ty.value)
2127 pub fn zero_sized(ty: Ty<'tcx>) -> Self {
2128 Self::from_scalar(Scalar::Bits { bits: 0, size: 0 }, ty)
2132 pub fn from_bool(tcx: TyCtxt<'_, '_, 'tcx>, v: bool) -> Self {
2133 Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
2137 pub fn from_usize(tcx: TyCtxt<'_, '_, 'tcx>, n: u64) -> Self {
2138 Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
2144 tcx: TyCtxt<'_, '_, 'tcx>,
2145 ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2147 if self.ty != ty.value {
2150 let ty = tcx.lift_to_global(&ty).unwrap();
2151 let size = tcx.layout_of(ty).ok()?.size;
2152 self.val.try_to_bits(size)
2156 pub fn to_ptr(&self) -> Option<Pointer> {
2157 self.val.try_to_ptr()
2163 tcx: TyCtxt<'_, '_, '_>,
2164 ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2166 assert_eq!(self.ty, ty.value);
2167 let ty = tcx.lift_to_global(&ty).unwrap();
2168 let size = tcx.layout_of(ty).ok()?.size;
2169 self.val.try_to_bits(size)
2173 pub fn assert_bool(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<bool> {
2174 self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.bool)).and_then(|v| match v {
2182 pub fn assert_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<u64> {
2183 self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.usize)).map(|v| v as u64)
2189 tcx: TyCtxt<'_, '_, '_>,
2190 ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2192 self.assert_bits(tcx, ty).unwrap_or_else(||
2193 bug!("expected bits of {}, got {:#?}", ty.value, self))
2197 pub fn unwrap_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> u64 {
2198 self.assert_usize(tcx).unwrap_or_else(||
2199 bug!("expected constant usize, got {:#?}", self))
2203 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx LazyConst<'tcx> {}