1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This module contains TypeVariants and its major components
13 use hir::def_id::DefId;
16 use ty::subst::Substs;
17 use ty::{self, AdtDef, TypeFlags, Ty, TyCtxt, TypeFoldable};
23 use std::cmp::Ordering;
25 use syntax::ast::{self, Name};
26 use syntax::symbol::{keywords, InternedString};
27 use util::nodemap::FxHashSet;
34 use self::TypeVariants::*;
36 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
37 pub struct TypeAndMut<'tcx> {
39 pub mutbl: hir::Mutability,
42 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
43 RustcEncodable, RustcDecodable, Copy)]
44 /// A "free" region `fr` can be interpreted as "some region
45 /// at least as big as the scope `fr.scope`".
46 pub struct FreeRegion {
47 pub scope: region::CodeExtent,
48 pub bound_region: BoundRegion
51 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
52 RustcEncodable, RustcDecodable, Copy)]
53 pub enum BoundRegion {
54 /// An anonymous region parameter for a given fn (&T)
57 /// Named region parameters for functions (a in &'a T)
59 /// The def-id is needed to distinguish free regions in
60 /// the event of shadowing.
61 BrNamed(DefId, Name, Issue32330),
63 /// Fresh bound identifiers created during GLB computations.
66 // Anonymous region for the implicit env pointer parameter
71 /// True if this late-bound region is unconstrained, and hence will
72 /// become early-bound once #32330 is fixed.
73 #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash,
74 RustcEncodable, RustcDecodable)]
78 /// this region will change from late-bound to early-bound once
81 /// fn where is region declared
84 /// name of region; duplicates the info in BrNamed but convenient
85 /// to have it here, and this code is only temporary
86 region_name: ast::Name,
90 // NB: If you change this, you'll probably want to change the corresponding
91 // AST structure in libsyntax/ast.rs as well.
92 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
93 pub enum TypeVariants<'tcx> {
94 /// The primitive boolean type. Written as `bool`.
97 /// The primitive character type; holds a Unicode scalar value
98 /// (a non-surrogate code point). Written as `char`.
101 /// A primitive signed integer type. For example, `i32`.
104 /// A primitive unsigned integer type. For example, `u32`.
107 /// A primitive floating-point type. For example, `f64`.
108 TyFloat(ast::FloatTy),
110 /// Structures, enumerations and unions.
112 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
113 /// That is, even after substitution it is possible that there are type
114 /// variables. This happens when the `TyAdt` corresponds to an ADT
115 /// definition and not a concrete use of it.
116 TyAdt(&'tcx AdtDef, &'tcx Substs<'tcx>),
118 /// The pointee of a string slice. Written as `str`.
121 /// An array with the given length. Written as `[T; n]`.
122 TyArray(Ty<'tcx>, usize),
124 /// The pointee of an array slice. Written as `[T]`.
127 /// A raw pointer. Written as `*mut T` or `*const T`
128 TyRawPtr(TypeAndMut<'tcx>),
130 /// A reference; a pointer with an associated lifetime. Written as
131 /// `&'a mut T` or `&'a T`.
132 TyRef(&'tcx Region, TypeAndMut<'tcx>),
134 /// The anonymous type of a function declaration/definition. Each
135 /// function has a unique type.
136 TyFnDef(DefId, &'tcx Substs<'tcx>, &'tcx BareFnTy<'tcx>),
138 /// A pointer to a function. Written as `fn() -> i32`.
139 /// FIXME: This is currently also used to represent the callee of a method;
140 /// see ty::MethodCallee etc.
141 TyFnPtr(&'tcx BareFnTy<'tcx>),
143 /// A trait, defined with `trait`.
144 TyDynamic(Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>, &'tcx ty::Region),
146 /// The anonymous type of a closure. Used to represent the type of
148 TyClosure(DefId, ClosureSubsts<'tcx>),
150 /// The never type `!`
153 /// A tuple type. For example, `(i32, bool)`.
154 /// The bool indicates whether this is a unit tuple and was created by
155 /// defaulting a diverging type variable with feature(never_type) disabled.
156 /// It's only purpose is for raising future-compatibility warnings for when
157 /// diverging type variables start defaulting to ! instead of ().
158 TyTuple(&'tcx Slice<Ty<'tcx>>, bool),
160 /// The projection of an associated type. For example,
161 /// `<T as Trait<..>>::N`.
162 TyProjection(ProjectionTy<'tcx>),
164 /// Anonymized (`impl Trait`) type found in a return type.
165 /// The DefId comes from the `impl Trait` ast::Ty node, and the
166 /// substitutions are for the generics of the function in question.
167 /// After typeck, the concrete type can be found in the `types` map.
168 TyAnon(DefId, &'tcx Substs<'tcx>),
170 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
173 /// A type variable used during type-checking.
176 /// A placeholder for a type which could not be computed; this is
177 /// propagated to avoid useless error messages.
181 /// A closure can be modeled as a struct that looks like:
183 /// struct Closure<'l0...'li, T0...Tj, U0...Uk> {
189 /// where 'l0...'li and T0...Tj are the lifetime and type parameters
190 /// in scope on the function that defined the closure, and U0...Uk are
191 /// type parameters representing the types of its upvars (borrowed, if
194 /// So, for example, given this function:
196 /// fn foo<'a, T>(data: &'a mut T) {
197 /// do(|| data.count += 1)
200 /// the type of the closure would be something like:
202 /// struct Closure<'a, T, U0> {
206 /// Note that the type of the upvar is not specified in the struct.
207 /// You may wonder how the impl would then be able to use the upvar,
208 /// if it doesn't know it's type? The answer is that the impl is
209 /// (conceptually) not fully generic over Closure but rather tied to
210 /// instances with the expected upvar types:
212 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
216 /// You can see that the *impl* fully specified the type of the upvar
217 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
218 /// (Here, I am assuming that `data` is mut-borrowed.)
220 /// Now, the last question you may ask is: Why include the upvar types
221 /// as extra type parameters? The reason for this design is that the
222 /// upvar types can reference lifetimes that are internal to the
223 /// creating function. In my example above, for example, the lifetime
224 /// `'b` represents the extent of the closure itself; this is some
225 /// subset of `foo`, probably just the extent of the call to the to
226 /// `do()`. If we just had the lifetime/type parameters from the
227 /// enclosing function, we couldn't name this lifetime `'b`. Note that
228 /// there can also be lifetimes in the types of the upvars themselves,
229 /// if one of them happens to be a reference to something that the
230 /// creating fn owns.
232 /// OK, you say, so why not create a more minimal set of parameters
233 /// that just includes the extra lifetime parameters? The answer is
234 /// primarily that it would be hard --- we don't know at the time when
235 /// we create the closure type what the full types of the upvars are,
236 /// nor do we know which are borrowed and which are not. In this
237 /// design, we can just supply a fresh type parameter and figure that
240 /// All right, you say, but why include the type parameters from the
241 /// original function then? The answer is that trans may need them
242 /// when monomorphizing, and they may not appear in the upvars. A
243 /// closure could capture no variables but still make use of some
244 /// in-scope type parameter with a bound (e.g., if our example above
245 /// had an extra `U: Default`, and the closure called `U::default()`).
247 /// There is another reason. This design (implicitly) prohibits
248 /// closures from capturing themselves (except via a trait
249 /// object). This simplifies closure inference considerably, since it
250 /// means that when we infer the kind of a closure or its upvars, we
251 /// don't have to handle cycles where the decisions we make for
252 /// closure C wind up influencing the decisions we ought to make for
253 /// closure C (which would then require fixed point iteration to
254 /// handle). Plus it fixes an ICE. :P
255 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
256 pub struct ClosureSubsts<'tcx> {
257 /// Lifetime and type parameters from the enclosing function,
258 /// concatenated with the types of the upvars.
260 /// These are separated out because trans wants to pass them around
261 /// when monomorphizing.
262 pub substs: &'tcx Substs<'tcx>,
265 impl<'a, 'gcx, 'acx, 'tcx> ClosureSubsts<'tcx> {
267 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'acx>) ->
268 impl Iterator<Item=Ty<'tcx>> + 'tcx
270 let generics = tcx.item_generics(def_id);
271 self.substs[self.substs.len()-generics.own_count()..].iter().map(
272 |t| t.as_type().expect("unexpected region in upvars"))
276 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
277 pub enum ExistentialPredicate<'tcx> {
279 Trait(ExistentialTraitRef<'tcx>),
280 // e.g. Iterator::Item = T
281 Projection(ExistentialProjection<'tcx>),
286 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
287 pub fn cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
288 use self::ExistentialPredicate::*;
289 match (*self, *other) {
290 (Trait(_), Trait(_)) => Ordering::Equal,
291 (Projection(ref a), Projection(ref b)) => a.sort_key(tcx).cmp(&b.sort_key(tcx)),
292 (AutoTrait(ref a), AutoTrait(ref b)) =>
293 tcx.lookup_trait_def(*a).def_path_hash.cmp(&tcx.lookup_trait_def(*b).def_path_hash),
294 (Trait(_), _) => Ordering::Less,
295 (Projection(_), Trait(_)) => Ordering::Greater,
296 (Projection(_), _) => Ordering::Less,
297 (AutoTrait(_), _) => Ordering::Greater,
303 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
304 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
305 -> ty::Predicate<'tcx> {
307 match *self.skip_binder() {
308 ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
309 ExistentialPredicate::Projection(p) =>
310 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
311 ExistentialPredicate::AutoTrait(did) => {
312 let trait_ref = Binder(ty::TraitRef {
314 substs: tcx.mk_substs_trait(self_ty, &[]),
316 trait_ref.to_predicate()
322 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<ExistentialPredicate<'tcx>> {}
324 impl<'tcx> Slice<ExistentialPredicate<'tcx>> {
325 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
327 Some(&ExistentialPredicate::Trait(tr)) => Some(tr),
333 pub fn projection_bounds<'a>(&'a self) ->
334 impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
335 self.iter().filter_map(|predicate| {
337 ExistentialPredicate::Projection(p) => Some(p),
344 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
345 self.iter().filter_map(|predicate| {
347 ExistentialPredicate::AutoTrait(d) => Some(d),
354 impl<'tcx> Binder<&'tcx Slice<ExistentialPredicate<'tcx>>> {
355 pub fn principal(&self) -> Option<PolyExistentialTraitRef<'tcx>> {
356 self.skip_binder().principal().map(Binder)
360 pub fn projection_bounds<'a>(&'a self) ->
361 impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
362 self.skip_binder().projection_bounds().map(Binder)
366 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
367 self.skip_binder().auto_traits()
370 pub fn iter<'a>(&'a self)
371 -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
372 self.skip_binder().iter().cloned().map(Binder)
376 /// A complete reference to a trait. These take numerous guises in syntax,
377 /// but perhaps the most recognizable form is in a where clause:
381 /// This would be represented by a trait-reference where the def-id is the
382 /// def-id for the trait `Foo` and the substs define `T` as parameter 0,
383 /// and `U` as parameter 1.
385 /// Trait references also appear in object types like `Foo<U>`, but in
386 /// that case the `Self` parameter is absent from the substitutions.
388 /// Note that a `TraitRef` introduces a level of region binding, to
389 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
390 /// U>` or higher-ranked object types.
391 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
392 pub struct TraitRef<'tcx> {
394 pub substs: &'tcx Substs<'tcx>,
397 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
399 impl<'tcx> PolyTraitRef<'tcx> {
400 pub fn self_ty(&self) -> Ty<'tcx> {
404 pub fn def_id(&self) -> DefId {
408 pub fn substs(&self) -> &'tcx Substs<'tcx> {
409 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
413 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
414 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
418 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
419 // Note that we preserve binding levels
420 Binder(ty::TraitPredicate { trait_ref: self.0.clone() })
424 /// An existential reference to a trait, where `Self` is erased.
425 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
427 /// exists T. T: Trait<'a, 'b, X, Y>
429 /// The substitutions don't include the erased `Self`, only trait
430 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
431 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
432 pub struct ExistentialTraitRef<'tcx> {
434 pub substs: &'tcx Substs<'tcx>,
437 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
438 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
439 // Select only the "input types" from a trait-reference. For
440 // now this is all the types that appear in the
441 // trait-reference, but it should eventually exclude
446 /// Object types don't have a self-type specified. Therefore, when
447 /// we convert the principal trait-ref into a normal trait-ref,
448 /// you must give *some* self-type. A common choice is `mk_err()`
449 /// or some skolemized type.
450 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
451 -> ty::TraitRef<'tcx> {
452 // otherwise the escaping regions would be captured by the binder
453 assert!(!self_ty.has_escaping_regions());
457 substs: tcx.mk_substs(
458 iter::once(Kind::from(self_ty)).chain(self.substs.iter().cloned()))
463 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
465 impl<'tcx> PolyExistentialTraitRef<'tcx> {
466 pub fn def_id(&self) -> DefId {
470 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
471 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
476 /// Binder is a binder for higher-ranked lifetimes. It is part of the
477 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
478 /// (which would be represented by the type `PolyTraitRef ==
479 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
480 /// erase, or otherwise "discharge" these bound regions, we change the
481 /// type from `Binder<T>` to just `T` (see
482 /// e.g. `liberate_late_bound_regions`).
483 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
484 pub struct Binder<T>(pub T);
487 /// Skips the binder and returns the "bound" value. This is a
488 /// risky thing to do because it's easy to get confused about
489 /// debruijn indices and the like. It is usually better to
490 /// discharge the binder using `no_late_bound_regions` or
491 /// `replace_late_bound_regions` or something like
492 /// that. `skip_binder` is only valid when you are either
493 /// extracting data that has nothing to do with bound regions, you
494 /// are doing some sort of test that does not involve bound
495 /// regions, or you are being very careful about your depth
498 /// Some examples where `skip_binder` is reasonable:
499 /// - extracting the def-id from a PolyTraitRef;
500 /// - comparing the self type of a PolyTraitRef to see if it is equal to
501 /// a type parameter `X`, since the type `X` does not reference any regions
502 pub fn skip_binder(&self) -> &T {
506 pub fn as_ref(&self) -> Binder<&T> {
510 pub fn map_bound_ref<F,U>(&self, f: F) -> Binder<U>
511 where F: FnOnce(&T) -> U
513 self.as_ref().map_bound(f)
516 pub fn map_bound<F,U>(self, f: F) -> Binder<U>
517 where F: FnOnce(T) -> U
519 ty::Binder(f(self.0))
523 impl fmt::Debug for TypeFlags {
524 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
525 write!(f, "{:x}", self.bits)
529 /// Represents the projection of an associated type. In explicit UFCS
530 /// form this would be written `<T as Trait<..>>::N`.
531 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
532 pub struct ProjectionTy<'tcx> {
533 /// The trait reference `T as Trait<..>`.
534 pub trait_ref: ty::TraitRef<'tcx>,
536 /// The name `N` of the associated type.
540 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
541 pub struct BareFnTy<'tcx> {
542 pub unsafety: hir::Unsafety,
544 /// Signature (inputs and output) of this function type.
545 pub sig: PolyFnSig<'tcx>,
548 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx BareFnTy<'tcx> {}
550 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
551 pub struct ClosureTy<'tcx> {
552 pub unsafety: hir::Unsafety,
554 pub sig: PolyFnSig<'tcx>,
557 /// Signature of a function type, which I have arbitrarily
558 /// decided to use to refer to the input/output types.
560 /// - `inputs` is the list of arguments and their modes.
561 /// - `output` is the return type.
562 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
563 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
564 pub struct FnSig<'tcx> {
565 pub inputs_and_output: &'tcx Slice<Ty<'tcx>>,
569 impl<'tcx> FnSig<'tcx> {
570 pub fn inputs(&self) -> &[Ty<'tcx>] {
571 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
574 pub fn output(&self) -> Ty<'tcx> {
575 self.inputs_and_output[self.inputs_and_output.len() - 1]
579 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
581 impl<'tcx> PolyFnSig<'tcx> {
582 pub fn inputs(&self) -> Binder<&[Ty<'tcx>]> {
583 Binder(self.skip_binder().inputs())
585 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
586 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
588 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
589 self.map_bound_ref(|fn_sig| fn_sig.output().clone())
591 pub fn variadic(&self) -> bool {
592 self.skip_binder().variadic
596 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
602 impl<'a, 'gcx, 'tcx> ParamTy {
603 pub fn new(index: u32, name: Name) -> ParamTy {
604 ParamTy { idx: index, name: name }
607 pub fn for_self() -> ParamTy {
608 ParamTy::new(0, keywords::SelfType.name())
611 pub fn for_def(def: &ty::TypeParameterDef) -> ParamTy {
612 ParamTy::new(def.index, def.name)
615 pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
616 tcx.mk_param(self.idx, self.name)
619 pub fn is_self(&self) -> bool {
620 if self.name == keywords::SelfType.name() {
621 assert_eq!(self.idx, 0);
629 /// A [De Bruijn index][dbi] is a standard means of representing
630 /// regions (and perhaps later types) in a higher-ranked setting. In
631 /// particular, imagine a type like this:
633 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
636 /// | +------------+ 1 | |
638 /// +--------------------------------+ 2 |
640 /// +------------------------------------------+ 1
642 /// In this type, there are two binders (the outer fn and the inner
643 /// fn). We need to be able to determine, for any given region, which
644 /// fn type it is bound by, the inner or the outer one. There are
645 /// various ways you can do this, but a De Bruijn index is one of the
646 /// more convenient and has some nice properties. The basic idea is to
647 /// count the number of binders, inside out. Some examples should help
648 /// clarify what I mean.
650 /// Let's start with the reference type `&'b isize` that is the first
651 /// argument to the inner function. This region `'b` is assigned a De
652 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
653 /// fn). The region `'a` that appears in the second argument type (`&'a
654 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
655 /// second-innermost binder". (These indices are written on the arrays
658 /// What is interesting is that De Bruijn index attached to a particular
659 /// variable will vary depending on where it appears. For example,
660 /// the final type `&'a char` also refers to the region `'a` declared on
661 /// the outermost fn. But this time, this reference is not nested within
662 /// any other binders (i.e., it is not an argument to the inner fn, but
663 /// rather the outer one). Therefore, in this case, it is assigned a
664 /// De Bruijn index of 1, because the innermost binder in that location
667 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
668 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
669 pub struct DebruijnIndex {
670 // We maintain the invariant that this is never 0. So 1 indicates
671 // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
675 /// Representation of regions.
677 /// Unlike types, most region variants are "fictitious", not concrete,
678 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
679 /// ones representing concrete regions.
683 /// These are regions that are stored behind a binder and must be substituted
684 /// with some concrete region before being used. There are 2 kind of
685 /// bound regions: early-bound, which are bound in an item's Generics,
686 /// and are substituted by a Substs, and late-bound, which are part of
687 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
688 /// the likes of `liberate_late_bound_regions`. The distinction exists
689 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
691 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
692 /// outside their binder, e.g. in types passed to type inference, and
693 /// should first be substituted (by skolemized regions, free regions,
694 /// or region variables).
696 /// ## Skolemized and Free Regions
698 /// One often wants to work with bound regions without knowing their precise
699 /// identity. For example, when checking a function, the lifetime of a borrow
700 /// can end up being assigned to some region parameter. In these cases,
701 /// it must be ensured that bounds on the region can't be accidentally
702 /// assumed without being checked.
704 /// The process of doing that is called "skolemization". The bound regions
705 /// are replaced by skolemized markers, which don't satisfy any relation
706 /// not explicity provided.
708 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
709 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
710 /// to be used. These also support explicit bounds: both the internally-stored
711 /// *scope*, which the region is assumed to outlive, as well as other
712 /// relations stored in the `FreeRegionMap`. Note that these relations
713 /// aren't checked when you `make_subregion` (or `eq_types`), only by
714 /// `resolve_regions_and_report_errors`.
716 /// When working with higher-ranked types, some region relations aren't
717 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
718 /// `ReSkolemized` is designed for this purpose. In these contexts,
719 /// there's also the risk that some inference variable laying around will
720 /// get unified with your skolemized region: if you want to check whether
721 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
722 /// with a skolemized region `'%a`, the variable `'_` would just be
723 /// instantiated to the skolemized region `'%a`, which is wrong because
724 /// the inference variable is supposed to satisfy the relation
725 /// *for every value of the skolemized region*. To ensure that doesn't
726 /// happen, you can use `leak_check`. This is more clearly explained
727 /// by infer/higher_ranked/README.md.
729 /// [1] http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
730 /// [2] http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
731 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable)]
733 // Region bound in a type or fn declaration which will be
734 // substituted 'early' -- that is, at the same time when type
735 // parameters are substituted.
736 ReEarlyBound(EarlyBoundRegion),
738 // Region bound in a function scope, which will be substituted when the
739 // function is called.
740 ReLateBound(DebruijnIndex, BoundRegion),
742 /// When checking a function body, the types of all arguments and so forth
743 /// that refer to bound region parameters are modified to refer to free
744 /// region parameters.
747 /// A concrete region naming some statically determined extent
748 /// (e.g. an expression or sequence of statements) within the
749 /// current function.
750 ReScope(region::CodeExtent),
752 /// Static data that has an "infinite" lifetime. Top in the region lattice.
755 /// A region variable. Should not exist after typeck.
758 /// A skolemized region - basically the higher-ranked version of ReFree.
759 /// Should not exist after typeck.
760 ReSkolemized(SkolemizedRegionVid, BoundRegion),
762 /// Empty lifetime is for data that is never accessed.
763 /// Bottom in the region lattice. We treat ReEmpty somewhat
764 /// specially; at least right now, we do not generate instances of
765 /// it during the GLB computations, but rather
766 /// generate an error instead. This is to improve error messages.
767 /// The only way to get an instance of ReEmpty is to have a region
768 /// variable with no constraints.
771 /// Erased region, used by trait selection, in MIR and during trans.
775 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Region {}
777 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
778 pub struct EarlyBoundRegion {
783 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
788 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
793 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
794 pub struct FloatVid {
798 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
799 pub struct RegionVid {
803 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
804 pub struct SkolemizedRegionVid {
808 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
814 /// A `FreshTy` is one that is generated as a replacement for an
815 /// unbound type variable. This is convenient for caching etc. See
816 /// `infer::freshen` for more details.
822 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
823 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
824 pub struct ExistentialProjection<'tcx> {
825 pub trait_ref: ExistentialTraitRef<'tcx>,
830 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
832 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
833 pub fn item_name(&self) -> Name {
834 self.item_name // safe to skip the binder to access a name
837 pub fn sort_key(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> (u64, InternedString) {
838 // We want something here that is stable across crate boundaries.
839 // The DefId isn't but the `deterministic_hash` of the corresponding
841 let trait_def = tcx.lookup_trait_def(self.trait_ref.def_id);
842 let def_path_hash = trait_def.def_path_hash;
844 // An `ast::Name` is also not stable (it's just an index into an
845 // interning table), so map to the corresponding `InternedString`.
846 let item_name = self.item_name.as_str();
847 (def_path_hash, item_name)
850 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
852 -> ty::ProjectionPredicate<'tcx>
854 // otherwise the escaping regions would be captured by the binders
855 assert!(!self_ty.has_escaping_regions());
857 ty::ProjectionPredicate {
858 projection_ty: ty::ProjectionTy {
859 trait_ref: self.trait_ref.with_self_ty(tcx, self_ty),
860 item_name: self.item_name
867 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
868 pub fn item_name(&self) -> Name {
869 self.skip_binder().item_name()
872 pub fn sort_key(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> (u64, InternedString) {
873 self.skip_binder().sort_key(tcx)
876 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
877 -> ty::PolyProjectionPredicate<'tcx> {
878 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
883 pub fn new(depth: u32) -> DebruijnIndex {
885 DebruijnIndex { depth: depth }
888 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
889 DebruijnIndex { depth: self.depth + amount }
895 pub fn is_bound(&self) -> bool {
897 ty::ReEarlyBound(..) => true,
898 ty::ReLateBound(..) => true,
903 pub fn needs_infer(&self) -> bool {
905 ty::ReVar(..) | ty::ReSkolemized(..) => true,
910 pub fn escapes_depth(&self, depth: u32) -> bool {
912 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
917 /// Returns the depth of `self` from the (1-based) binding level `depth`
918 pub fn from_depth(&self, depth: u32) -> Region {
920 ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
921 depth: debruijn.depth - (depth - 1)
927 pub fn type_flags(&self) -> TypeFlags {
928 let mut flags = TypeFlags::empty();
932 flags = flags | TypeFlags::HAS_RE_INFER;
933 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
935 ty::ReSkolemized(..) => {
936 flags = flags | TypeFlags::HAS_RE_INFER;
937 flags = flags | TypeFlags::HAS_RE_SKOL;
938 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
940 ty::ReLateBound(..) => { }
941 ty::ReEarlyBound(..) => { flags = flags | TypeFlags::HAS_RE_EARLY_BOUND; }
942 ty::ReStatic | ty::ReErased => { }
943 _ => { flags = flags | TypeFlags::HAS_FREE_REGIONS; }
947 ty::ReStatic | ty::ReEmpty | ty::ReErased => (),
948 _ => flags = flags | TypeFlags::HAS_LOCAL_NAMES,
951 debug!("type_flags({:?}) = {:?}", self, flags);
958 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
959 pub fn as_opt_param_ty(&self) -> Option<ty::ParamTy> {
961 ty::TyParam(ref d) => Some(d.clone()),
966 pub fn is_nil(&self) -> bool {
968 TyTuple(ref tys, _) => tys.is_empty(),
973 pub fn is_never(&self) -> bool {
980 // Test whether this is a `()` which was produced by defaulting a
981 // diverging type variable with feature(never_type) disabled.
982 pub fn is_defaulted_unit(&self) -> bool {
984 TyTuple(_, true) => true,
989 /// Checks whether a type is visibly uninhabited from a particular module.
995 /// pub struct SecretlyUninhabited {
1002 /// pub struct AlsoSecretlyUninhabited {
1010 /// x: a::b::SecretlyUninhabited,
1011 /// y: c::AlsoSecretlyUninhabited,
1014 /// In this code, the type `Foo` will only be visibly uninhabited inside the
1015 /// modules b, c and d. This effects pattern-matching on `Foo` or types that
1020 /// let foo_result: Result<T, Foo> = ... ;
1021 /// let Ok(t) = foo_result;
1023 /// This code should only compile in modules where the uninhabitedness of Foo is
1025 pub fn is_uninhabited_from(&self, module: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1026 let mut visited = FxHashSet::default();
1027 let forest = self.uninhabited_from(&mut visited, tcx);
1029 // To check whether this type is uninhabited at all (not just from the
1030 // given node) you could check whether the forest is empty.
1032 // forest.is_empty()
1034 forest.contains(tcx, module)
1037 pub fn is_primitive(&self) -> bool {
1039 TyBool | TyChar | TyInt(_) | TyUint(_) | TyFloat(_) => true,
1044 pub fn is_ty_var(&self) -> bool {
1046 TyInfer(TyVar(_)) => true,
1051 pub fn is_phantom_data(&self) -> bool {
1052 if let TyAdt(def, _) = self.sty {
1053 def.is_phantom_data()
1059 pub fn is_bool(&self) -> bool { self.sty == TyBool }
1061 pub fn is_param(&self, index: u32) -> bool {
1063 ty::TyParam(ref data) => data.idx == index,
1068 pub fn is_self(&self) -> bool {
1070 TyParam(ref p) => p.is_self(),
1075 pub fn is_slice(&self) -> bool {
1077 TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
1078 TySlice(_) | TyStr => true,
1085 pub fn is_structural(&self) -> bool {
1087 TyAdt(..) | TyTuple(..) | TyArray(..) | TyClosure(..) => true,
1088 _ => self.is_slice() | self.is_trait()
1093 pub fn is_simd(&self) -> bool {
1095 TyAdt(def, _) => def.is_simd(),
1100 pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1102 TyArray(ty, _) | TySlice(ty) => ty,
1103 TyStr => tcx.mk_mach_uint(ast::UintTy::U8),
1104 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1108 pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1110 TyAdt(def, substs) => {
1111 def.struct_variant().fields[0].ty(tcx, substs)
1113 _ => bug!("simd_type called on invalid type")
1117 pub fn simd_size(&self, _cx: TyCtxt) -> usize {
1119 TyAdt(def, _) => def.struct_variant().fields.len(),
1120 _ => bug!("simd_size called on invalid type")
1124 pub fn is_region_ptr(&self) -> bool {
1131 pub fn is_mutable_pointer(&self) -> bool {
1133 TyRawPtr(tnm) | TyRef(_, tnm) => if let hir::Mutability::MutMutable = tnm.mutbl {
1142 pub fn is_unsafe_ptr(&self) -> bool {
1144 TyRawPtr(_) => return true,
1149 pub fn is_box(&self) -> bool {
1151 TyAdt(def, _) => def.is_box(),
1156 pub fn boxed_ty(&self) -> Ty<'tcx> {
1158 TyAdt(def, substs) if def.is_box() => substs.type_at(0),
1159 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1164 A scalar type is one that denotes an atomic datum, with no sub-components.
1165 (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1166 contents are abstract to rustc.)
1168 pub fn is_scalar(&self) -> bool {
1170 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
1171 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
1172 TyFnDef(..) | TyFnPtr(_) | TyRawPtr(_) => true,
1177 /// Returns true if this type is a floating point type and false otherwise.
1178 pub fn is_floating_point(&self) -> bool {
1181 TyInfer(FloatVar(_)) => true,
1186 pub fn is_trait(&self) -> bool {
1188 TyDynamic(..) => true,
1193 pub fn is_integral(&self) -> bool {
1195 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
1200 pub fn is_fresh(&self) -> bool {
1202 TyInfer(FreshTy(_)) => true,
1203 TyInfer(FreshIntTy(_)) => true,
1204 TyInfer(FreshFloatTy(_)) => true,
1209 pub fn is_uint(&self) -> bool {
1211 TyInfer(IntVar(_)) | TyUint(ast::UintTy::Us) => true,
1216 pub fn is_char(&self) -> bool {
1223 pub fn is_fp(&self) -> bool {
1225 TyInfer(FloatVar(_)) | TyFloat(_) => true,
1230 pub fn is_numeric(&self) -> bool {
1231 self.is_integral() || self.is_fp()
1234 pub fn is_signed(&self) -> bool {
1241 pub fn is_machine(&self) -> bool {
1243 TyInt(ast::IntTy::Is) | TyUint(ast::UintTy::Us) => false,
1244 TyInt(..) | TyUint(..) | TyFloat(..) => true,
1249 pub fn has_concrete_skeleton(&self) -> bool {
1251 TyParam(_) | TyInfer(_) | TyError => false,
1256 // Returns the type and mutability of *ty.
1258 // The parameter `explicit` indicates if this is an *explicit* dereference.
1259 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1260 pub fn builtin_deref(&self, explicit: bool, pref: ty::LvaluePreference)
1261 -> Option<TypeAndMut<'tcx>>
1264 TyAdt(def, _) if def.is_box() => {
1266 ty: self.boxed_ty(),
1267 mutbl: if pref == ty::PreferMutLvalue {
1274 TyRef(_, mt) => Some(mt),
1275 TyRawPtr(mt) if explicit => Some(mt),
1280 // Returns the type of ty[i]
1281 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1283 TyArray(ty, _) | TySlice(ty) => Some(ty),
1288 pub fn fn_sig(&self) -> &'tcx PolyFnSig<'tcx> {
1290 TyFnDef(.., ref f) | TyFnPtr(ref f) => &f.sig,
1291 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1295 /// Returns the ABI of the given function.
1296 pub fn fn_abi(&self) -> abi::Abi {
1298 TyFnDef(.., ref f) | TyFnPtr(ref f) => f.abi,
1299 _ => bug!("Ty::fn_abi() called on non-fn type"),
1303 // Type accessors for substructures of types
1304 pub fn fn_args(&self) -> ty::Binder<&[Ty<'tcx>]> {
1305 self.fn_sig().inputs()
1308 pub fn fn_ret(&self) -> Binder<Ty<'tcx>> {
1309 self.fn_sig().output()
1312 pub fn is_fn(&self) -> bool {
1314 TyFnDef(..) | TyFnPtr(_) => true,
1319 pub fn ty_to_def_id(&self) -> Option<DefId> {
1321 TyDynamic(ref tt, ..) => tt.principal().map(|p| p.def_id()),
1322 TyAdt(def, _) => Some(def.did),
1323 TyClosure(id, _) => Some(id),
1328 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1330 TyAdt(adt, _) => Some(adt),
1335 /// Returns the regions directly referenced from this type (but
1336 /// not types reachable from this type via `walk_tys`). This
1337 /// ignores late-bound regions binders.
1338 pub fn regions(&self) -> Vec<&'tcx ty::Region> {
1340 TyRef(region, _) => {
1343 TyDynamic(ref obj, region) => {
1344 let mut v = vec![region];
1345 if let Some(p) = obj.principal() {
1346 v.extend(p.skip_binder().substs.regions());
1350 TyAdt(_, substs) | TyAnon(_, substs) => {
1351 substs.regions().collect()
1353 TyClosure(_, ref substs) => {
1354 substs.substs.regions().collect()
1356 TyProjection(ref data) => {
1357 data.trait_ref.substs.regions().collect()