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.
63 /// Fresh bound identifiers created during GLB computations.
66 // Anonymous region for the implicit env pointer parameter
71 /// When a region changed from late-bound to early-bound when #32330
72 /// was fixed, its `RegionParameterDef` will have one of these
73 /// structures that we can use to give nicer errors.
74 #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash,
75 RustcEncodable, RustcDecodable)]
76 pub struct Issue32330 {
77 /// fn where is region declared
80 /// name of region; duplicates the info in BrNamed but convenient
81 /// to have it here, and this code is only temporary
82 pub region_name: ast::Name,
85 // NB: If you change this, you'll probably want to change the corresponding
86 // AST structure in libsyntax/ast.rs as well.
87 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
88 pub enum TypeVariants<'tcx> {
89 /// The primitive boolean type. Written as `bool`.
92 /// The primitive character type; holds a Unicode scalar value
93 /// (a non-surrogate code point). Written as `char`.
96 /// A primitive signed integer type. For example, `i32`.
99 /// A primitive unsigned integer type. For example, `u32`.
102 /// A primitive floating-point type. For example, `f64`.
103 TyFloat(ast::FloatTy),
105 /// Structures, enumerations and unions.
107 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
108 /// That is, even after substitution it is possible that there are type
109 /// variables. This happens when the `TyAdt` corresponds to an ADT
110 /// definition and not a concrete use of it.
111 TyAdt(&'tcx AdtDef, &'tcx Substs<'tcx>),
113 /// The pointee of a string slice. Written as `str`.
116 /// An array with the given length. Written as `[T; n]`.
117 TyArray(Ty<'tcx>, usize),
119 /// The pointee of an array slice. Written as `[T]`.
122 /// A raw pointer. Written as `*mut T` or `*const T`
123 TyRawPtr(TypeAndMut<'tcx>),
125 /// A reference; a pointer with an associated lifetime. Written as
126 /// `&'a mut T` or `&'a T`.
127 TyRef(&'tcx Region, TypeAndMut<'tcx>),
129 /// The anonymous type of a function declaration/definition. Each
130 /// function has a unique type.
131 TyFnDef(DefId, &'tcx Substs<'tcx>, &'tcx BareFnTy<'tcx>),
133 /// A pointer to a function. Written as `fn() -> i32`.
134 /// FIXME: This is currently also used to represent the callee of a method;
135 /// see ty::MethodCallee etc.
136 TyFnPtr(&'tcx BareFnTy<'tcx>),
138 /// A trait, defined with `trait`.
139 TyDynamic(Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>, &'tcx ty::Region),
141 /// The anonymous type of a closure. Used to represent the type of
143 TyClosure(DefId, ClosureSubsts<'tcx>),
145 /// The never type `!`
148 /// A tuple type. For example, `(i32, bool)`.
149 /// The bool indicates whether this is a unit tuple and was created by
150 /// defaulting a diverging type variable with feature(never_type) disabled.
151 /// It's only purpose is for raising future-compatibility warnings for when
152 /// diverging type variables start defaulting to ! instead of ().
153 TyTuple(&'tcx Slice<Ty<'tcx>>, bool),
155 /// The projection of an associated type. For example,
156 /// `<T as Trait<..>>::N`.
157 TyProjection(ProjectionTy<'tcx>),
159 /// Anonymized (`impl Trait`) type found in a return type.
160 /// The DefId comes from the `impl Trait` ast::Ty node, and the
161 /// substitutions are for the generics of the function in question.
162 /// After typeck, the concrete type can be found in the `types` map.
163 TyAnon(DefId, &'tcx Substs<'tcx>),
165 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
168 /// A type variable used during type-checking.
171 /// A placeholder for a type which could not be computed; this is
172 /// propagated to avoid useless error messages.
176 /// A closure can be modeled as a struct that looks like:
178 /// struct Closure<'l0...'li, T0...Tj, U0...Uk> {
184 /// where 'l0...'li and T0...Tj are the lifetime and type parameters
185 /// in scope on the function that defined the closure, and U0...Uk are
186 /// type parameters representing the types of its upvars (borrowed, if
189 /// So, for example, given this function:
191 /// fn foo<'a, T>(data: &'a mut T) {
192 /// do(|| data.count += 1)
195 /// the type of the closure would be something like:
197 /// struct Closure<'a, T, U0> {
201 /// Note that the type of the upvar is not specified in the struct.
202 /// You may wonder how the impl would then be able to use the upvar,
203 /// if it doesn't know it's type? The answer is that the impl is
204 /// (conceptually) not fully generic over Closure but rather tied to
205 /// instances with the expected upvar types:
207 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
211 /// You can see that the *impl* fully specified the type of the upvar
212 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
213 /// (Here, I am assuming that `data` is mut-borrowed.)
215 /// Now, the last question you may ask is: Why include the upvar types
216 /// as extra type parameters? The reason for this design is that the
217 /// upvar types can reference lifetimes that are internal to the
218 /// creating function. In my example above, for example, the lifetime
219 /// `'b` represents the extent of the closure itself; this is some
220 /// subset of `foo`, probably just the extent of the call to the to
221 /// `do()`. If we just had the lifetime/type parameters from the
222 /// enclosing function, we couldn't name this lifetime `'b`. Note that
223 /// there can also be lifetimes in the types of the upvars themselves,
224 /// if one of them happens to be a reference to something that the
225 /// creating fn owns.
227 /// OK, you say, so why not create a more minimal set of parameters
228 /// that just includes the extra lifetime parameters? The answer is
229 /// primarily that it would be hard --- we don't know at the time when
230 /// we create the closure type what the full types of the upvars are,
231 /// nor do we know which are borrowed and which are not. In this
232 /// design, we can just supply a fresh type parameter and figure that
235 /// All right, you say, but why include the type parameters from the
236 /// original function then? The answer is that trans may need them
237 /// when monomorphizing, and they may not appear in the upvars. A
238 /// closure could capture no variables but still make use of some
239 /// in-scope type parameter with a bound (e.g., if our example above
240 /// had an extra `U: Default`, and the closure called `U::default()`).
242 /// There is another reason. This design (implicitly) prohibits
243 /// closures from capturing themselves (except via a trait
244 /// object). This simplifies closure inference considerably, since it
245 /// means that when we infer the kind of a closure or its upvars, we
246 /// don't have to handle cycles where the decisions we make for
247 /// closure C wind up influencing the decisions we ought to make for
248 /// closure C (which would then require fixed point iteration to
249 /// handle). Plus it fixes an ICE. :P
250 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
251 pub struct ClosureSubsts<'tcx> {
252 /// Lifetime and type parameters from the enclosing function,
253 /// concatenated with the types of the upvars.
255 /// These are separated out because trans wants to pass them around
256 /// when monomorphizing.
257 pub substs: &'tcx Substs<'tcx>,
260 impl<'a, 'gcx, 'acx, 'tcx> ClosureSubsts<'tcx> {
262 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'acx>) ->
263 impl Iterator<Item=Ty<'tcx>> + 'tcx
265 let generics = tcx.item_generics(def_id);
266 self.substs[self.substs.len()-generics.own_count()..].iter().map(
267 |t| t.as_type().expect("unexpected region in upvars"))
271 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
272 pub enum ExistentialPredicate<'tcx> {
274 Trait(ExistentialTraitRef<'tcx>),
275 // e.g. Iterator::Item = T
276 Projection(ExistentialProjection<'tcx>),
281 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
282 pub fn cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
283 use self::ExistentialPredicate::*;
284 match (*self, *other) {
285 (Trait(_), Trait(_)) => Ordering::Equal,
286 (Projection(ref a), Projection(ref b)) => a.sort_key(tcx).cmp(&b.sort_key(tcx)),
287 (AutoTrait(ref a), AutoTrait(ref b)) =>
288 tcx.lookup_trait_def(*a).def_path_hash.cmp(&tcx.lookup_trait_def(*b).def_path_hash),
289 (Trait(_), _) => Ordering::Less,
290 (Projection(_), Trait(_)) => Ordering::Greater,
291 (Projection(_), _) => Ordering::Less,
292 (AutoTrait(_), _) => Ordering::Greater,
298 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
299 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
300 -> ty::Predicate<'tcx> {
302 match *self.skip_binder() {
303 ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
304 ExistentialPredicate::Projection(p) =>
305 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
306 ExistentialPredicate::AutoTrait(did) => {
307 let trait_ref = Binder(ty::TraitRef {
309 substs: tcx.mk_substs_trait(self_ty, &[]),
311 trait_ref.to_predicate()
317 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<ExistentialPredicate<'tcx>> {}
319 impl<'tcx> Slice<ExistentialPredicate<'tcx>> {
320 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
322 Some(&ExistentialPredicate::Trait(tr)) => Some(tr),
328 pub fn projection_bounds<'a>(&'a self) ->
329 impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
330 self.iter().filter_map(|predicate| {
332 ExistentialPredicate::Projection(p) => Some(p),
339 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
340 self.iter().filter_map(|predicate| {
342 ExistentialPredicate::AutoTrait(d) => Some(d),
349 impl<'tcx> Binder<&'tcx Slice<ExistentialPredicate<'tcx>>> {
350 pub fn principal(&self) -> Option<PolyExistentialTraitRef<'tcx>> {
351 self.skip_binder().principal().map(Binder)
355 pub fn projection_bounds<'a>(&'a self) ->
356 impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
357 self.skip_binder().projection_bounds().map(Binder)
361 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
362 self.skip_binder().auto_traits()
365 pub fn iter<'a>(&'a self)
366 -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
367 self.skip_binder().iter().cloned().map(Binder)
371 /// A complete reference to a trait. These take numerous guises in syntax,
372 /// but perhaps the most recognizable form is in a where clause:
376 /// This would be represented by a trait-reference where the def-id is the
377 /// def-id for the trait `Foo` and the substs define `T` as parameter 0,
378 /// and `U` as parameter 1.
380 /// Trait references also appear in object types like `Foo<U>`, but in
381 /// that case the `Self` parameter is absent from the substitutions.
383 /// Note that a `TraitRef` introduces a level of region binding, to
384 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
385 /// U>` or higher-ranked object types.
386 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
387 pub struct TraitRef<'tcx> {
389 pub substs: &'tcx Substs<'tcx>,
392 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
394 impl<'tcx> PolyTraitRef<'tcx> {
395 pub fn self_ty(&self) -> Ty<'tcx> {
399 pub fn def_id(&self) -> DefId {
403 pub fn substs(&self) -> &'tcx Substs<'tcx> {
404 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
408 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
409 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
413 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
414 // Note that we preserve binding levels
415 Binder(ty::TraitPredicate { trait_ref: self.0.clone() })
419 /// An existential reference to a trait, where `Self` is erased.
420 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
422 /// exists T. T: Trait<'a, 'b, X, Y>
424 /// The substitutions don't include the erased `Self`, only trait
425 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
426 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
427 pub struct ExistentialTraitRef<'tcx> {
429 pub substs: &'tcx Substs<'tcx>,
432 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
433 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
434 // Select only the "input types" from a trait-reference. For
435 // now this is all the types that appear in the
436 // trait-reference, but it should eventually exclude
441 /// Object types don't have a self-type specified. Therefore, when
442 /// we convert the principal trait-ref into a normal trait-ref,
443 /// you must give *some* self-type. A common choice is `mk_err()`
444 /// or some skolemized type.
445 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
446 -> ty::TraitRef<'tcx> {
447 // otherwise the escaping regions would be captured by the binder
448 assert!(!self_ty.has_escaping_regions());
452 substs: tcx.mk_substs(
453 iter::once(Kind::from(self_ty)).chain(self.substs.iter().cloned()))
458 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
460 impl<'tcx> PolyExistentialTraitRef<'tcx> {
461 pub fn def_id(&self) -> DefId {
465 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
466 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
471 /// Binder is a binder for higher-ranked lifetimes. It is part of the
472 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
473 /// (which would be represented by the type `PolyTraitRef ==
474 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
475 /// erase, or otherwise "discharge" these bound regions, we change the
476 /// type from `Binder<T>` to just `T` (see
477 /// e.g. `liberate_late_bound_regions`).
478 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
479 pub struct Binder<T>(pub T);
482 /// Skips the binder and returns the "bound" value. This is a
483 /// risky thing to do because it's easy to get confused about
484 /// debruijn indices and the like. It is usually better to
485 /// discharge the binder using `no_late_bound_regions` or
486 /// `replace_late_bound_regions` or something like
487 /// that. `skip_binder` is only valid when you are either
488 /// extracting data that has nothing to do with bound regions, you
489 /// are doing some sort of test that does not involve bound
490 /// regions, or you are being very careful about your depth
493 /// Some examples where `skip_binder` is reasonable:
494 /// - extracting the def-id from a PolyTraitRef;
495 /// - comparing the self type of a PolyTraitRef to see if it is equal to
496 /// a type parameter `X`, since the type `X` does not reference any regions
497 pub fn skip_binder(&self) -> &T {
501 pub fn as_ref(&self) -> Binder<&T> {
505 pub fn map_bound_ref<F,U>(&self, f: F) -> Binder<U>
506 where F: FnOnce(&T) -> U
508 self.as_ref().map_bound(f)
511 pub fn map_bound<F,U>(self, f: F) -> Binder<U>
512 where F: FnOnce(T) -> U
514 ty::Binder(f(self.0))
518 impl fmt::Debug for TypeFlags {
519 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
520 write!(f, "{:x}", self.bits)
524 /// Represents the projection of an associated type. In explicit UFCS
525 /// form this would be written `<T as Trait<..>>::N`.
526 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
527 pub struct ProjectionTy<'tcx> {
528 /// The trait reference `T as Trait<..>`.
529 pub trait_ref: ty::TraitRef<'tcx>,
531 /// The name `N` of the associated type.
535 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
536 pub struct BareFnTy<'tcx> {
537 pub unsafety: hir::Unsafety,
539 /// Signature (inputs and output) of this function type.
540 pub sig: PolyFnSig<'tcx>,
543 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx BareFnTy<'tcx> {}
545 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
546 pub struct ClosureTy<'tcx> {
547 pub unsafety: hir::Unsafety,
549 pub sig: PolyFnSig<'tcx>,
552 /// Signature of a function type, which I have arbitrarily
553 /// decided to use to refer to the input/output types.
555 /// - `inputs` is the list of arguments and their modes.
556 /// - `output` is the return type.
557 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
558 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
559 pub struct FnSig<'tcx> {
560 pub inputs_and_output: &'tcx Slice<Ty<'tcx>>,
564 impl<'tcx> FnSig<'tcx> {
565 pub fn inputs(&self) -> &[Ty<'tcx>] {
566 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
569 pub fn output(&self) -> Ty<'tcx> {
570 self.inputs_and_output[self.inputs_and_output.len() - 1]
574 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
576 impl<'tcx> PolyFnSig<'tcx> {
577 pub fn inputs(&self) -> Binder<&[Ty<'tcx>]> {
578 Binder(self.skip_binder().inputs())
580 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
581 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
583 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
584 self.map_bound_ref(|fn_sig| fn_sig.output().clone())
586 pub fn variadic(&self) -> bool {
587 self.skip_binder().variadic
591 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
597 impl<'a, 'gcx, 'tcx> ParamTy {
598 pub fn new(index: u32, name: Name) -> ParamTy {
599 ParamTy { idx: index, name: name }
602 pub fn for_self() -> ParamTy {
603 ParamTy::new(0, keywords::SelfType.name())
606 pub fn for_def(def: &ty::TypeParameterDef) -> ParamTy {
607 ParamTy::new(def.index, def.name)
610 pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
611 tcx.mk_param(self.idx, self.name)
614 pub fn is_self(&self) -> bool {
615 if self.name == keywords::SelfType.name() {
616 assert_eq!(self.idx, 0);
624 /// A [De Bruijn index][dbi] is a standard means of representing
625 /// regions (and perhaps later types) in a higher-ranked setting. In
626 /// particular, imagine a type like this:
628 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
631 /// | +------------+ 1 | |
633 /// +--------------------------------+ 2 |
635 /// +------------------------------------------+ 1
637 /// In this type, there are two binders (the outer fn and the inner
638 /// fn). We need to be able to determine, for any given region, which
639 /// fn type it is bound by, the inner or the outer one. There are
640 /// various ways you can do this, but a De Bruijn index is one of the
641 /// more convenient and has some nice properties. The basic idea is to
642 /// count the number of binders, inside out. Some examples should help
643 /// clarify what I mean.
645 /// Let's start with the reference type `&'b isize` that is the first
646 /// argument to the inner function. This region `'b` is assigned a De
647 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
648 /// fn). The region `'a` that appears in the second argument type (`&'a
649 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
650 /// second-innermost binder". (These indices are written on the arrays
653 /// What is interesting is that De Bruijn index attached to a particular
654 /// variable will vary depending on where it appears. For example,
655 /// the final type `&'a char` also refers to the region `'a` declared on
656 /// the outermost fn. But this time, this reference is not nested within
657 /// any other binders (i.e., it is not an argument to the inner fn, but
658 /// rather the outer one). Therefore, in this case, it is assigned a
659 /// De Bruijn index of 1, because the innermost binder in that location
662 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
663 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
664 pub struct DebruijnIndex {
665 // We maintain the invariant that this is never 0. So 1 indicates
666 // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
670 /// Representation of regions.
672 /// Unlike types, most region variants are "fictitious", not concrete,
673 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
674 /// ones representing concrete regions.
678 /// These are regions that are stored behind a binder and must be substituted
679 /// with some concrete region before being used. There are 2 kind of
680 /// bound regions: early-bound, which are bound in an item's Generics,
681 /// and are substituted by a Substs, and late-bound, which are part of
682 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
683 /// the likes of `liberate_late_bound_regions`. The distinction exists
684 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
686 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
687 /// outside their binder, e.g. in types passed to type inference, and
688 /// should first be substituted (by skolemized regions, free regions,
689 /// or region variables).
691 /// ## Skolemized and Free Regions
693 /// One often wants to work with bound regions without knowing their precise
694 /// identity. For example, when checking a function, the lifetime of a borrow
695 /// can end up being assigned to some region parameter. In these cases,
696 /// it must be ensured that bounds on the region can't be accidentally
697 /// assumed without being checked.
699 /// The process of doing that is called "skolemization". The bound regions
700 /// are replaced by skolemized markers, which don't satisfy any relation
701 /// not explicity provided.
703 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
704 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
705 /// to be used. These also support explicit bounds: both the internally-stored
706 /// *scope*, which the region is assumed to outlive, as well as other
707 /// relations stored in the `FreeRegionMap`. Note that these relations
708 /// aren't checked when you `make_subregion` (or `eq_types`), only by
709 /// `resolve_regions_and_report_errors`.
711 /// When working with higher-ranked types, some region relations aren't
712 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
713 /// `ReSkolemized` is designed for this purpose. In these contexts,
714 /// there's also the risk that some inference variable laying around will
715 /// get unified with your skolemized region: if you want to check whether
716 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
717 /// with a skolemized region `'%a`, the variable `'_` would just be
718 /// instantiated to the skolemized region `'%a`, which is wrong because
719 /// the inference variable is supposed to satisfy the relation
720 /// *for every value of the skolemized region*. To ensure that doesn't
721 /// happen, you can use `leak_check`. This is more clearly explained
722 /// by infer/higher_ranked/README.md.
724 /// [1] http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
725 /// [2] http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
726 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable)]
728 // Region bound in a type or fn declaration which will be
729 // substituted 'early' -- that is, at the same time when type
730 // parameters are substituted.
731 ReEarlyBound(EarlyBoundRegion),
733 // Region bound in a function scope, which will be substituted when the
734 // function is called.
735 ReLateBound(DebruijnIndex, BoundRegion),
737 /// When checking a function body, the types of all arguments and so forth
738 /// that refer to bound region parameters are modified to refer to free
739 /// region parameters.
742 /// A concrete region naming some statically determined extent
743 /// (e.g. an expression or sequence of statements) within the
744 /// current function.
745 ReScope(region::CodeExtent),
747 /// Static data that has an "infinite" lifetime. Top in the region lattice.
750 /// A region variable. Should not exist after typeck.
753 /// A skolemized region - basically the higher-ranked version of ReFree.
754 /// Should not exist after typeck.
755 ReSkolemized(SkolemizedRegionVid, BoundRegion),
757 /// Empty lifetime is for data that is never accessed.
758 /// Bottom in the region lattice. We treat ReEmpty somewhat
759 /// specially; at least right now, we do not generate instances of
760 /// it during the GLB computations, but rather
761 /// generate an error instead. This is to improve error messages.
762 /// The only way to get an instance of ReEmpty is to have a region
763 /// variable with no constraints.
766 /// Erased region, used by trait selection, in MIR and during trans.
770 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Region {}
772 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
773 pub struct EarlyBoundRegion {
778 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
783 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
788 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
789 pub struct FloatVid {
793 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
794 pub struct RegionVid {
798 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
799 pub struct SkolemizedRegionVid {
803 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
809 /// A `FreshTy` is one that is generated as a replacement for an
810 /// unbound type variable. This is convenient for caching etc. See
811 /// `infer::freshen` for more details.
817 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
818 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
819 pub struct ExistentialProjection<'tcx> {
820 pub trait_ref: ExistentialTraitRef<'tcx>,
825 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
827 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
828 pub fn item_name(&self) -> Name {
829 self.item_name // safe to skip the binder to access a name
832 pub fn sort_key(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> (u64, InternedString) {
833 // We want something here that is stable across crate boundaries.
834 // The DefId isn't but the `deterministic_hash` of the corresponding
836 let trait_def = tcx.lookup_trait_def(self.trait_ref.def_id);
837 let def_path_hash = trait_def.def_path_hash;
839 // An `ast::Name` is also not stable (it's just an index into an
840 // interning table), so map to the corresponding `InternedString`.
841 let item_name = self.item_name.as_str();
842 (def_path_hash, item_name)
845 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
847 -> ty::ProjectionPredicate<'tcx>
849 // otherwise the escaping regions would be captured by the binders
850 assert!(!self_ty.has_escaping_regions());
852 ty::ProjectionPredicate {
853 projection_ty: ty::ProjectionTy {
854 trait_ref: self.trait_ref.with_self_ty(tcx, self_ty),
855 item_name: self.item_name
862 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
863 pub fn item_name(&self) -> Name {
864 self.skip_binder().item_name()
867 pub fn sort_key(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> (u64, InternedString) {
868 self.skip_binder().sort_key(tcx)
871 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
872 -> ty::PolyProjectionPredicate<'tcx> {
873 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
878 pub fn new(depth: u32) -> DebruijnIndex {
880 DebruijnIndex { depth: depth }
883 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
884 DebruijnIndex { depth: self.depth + amount }
890 pub fn is_bound(&self) -> bool {
892 ty::ReEarlyBound(..) => true,
893 ty::ReLateBound(..) => true,
898 pub fn needs_infer(&self) -> bool {
900 ty::ReVar(..) | ty::ReSkolemized(..) => true,
905 pub fn escapes_depth(&self, depth: u32) -> bool {
907 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
912 /// Returns the depth of `self` from the (1-based) binding level `depth`
913 pub fn from_depth(&self, depth: u32) -> Region {
915 ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
916 depth: debruijn.depth - (depth - 1)
922 pub fn type_flags(&self) -> TypeFlags {
923 let mut flags = TypeFlags::empty();
927 flags = flags | TypeFlags::HAS_RE_INFER;
928 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
930 ty::ReSkolemized(..) => {
931 flags = flags | TypeFlags::HAS_RE_INFER;
932 flags = flags | TypeFlags::HAS_RE_SKOL;
933 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
935 ty::ReLateBound(..) => { }
936 ty::ReEarlyBound(..) => { flags = flags | TypeFlags::HAS_RE_EARLY_BOUND; }
937 ty::ReStatic | ty::ReErased => { }
938 _ => { flags = flags | TypeFlags::HAS_FREE_REGIONS; }
942 ty::ReStatic | ty::ReEmpty | ty::ReErased => (),
943 _ => flags = flags | TypeFlags::HAS_LOCAL_NAMES,
946 debug!("type_flags({:?}) = {:?}", self, flags);
953 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
954 pub fn as_opt_param_ty(&self) -> Option<ty::ParamTy> {
956 ty::TyParam(ref d) => Some(d.clone()),
961 pub fn is_nil(&self) -> bool {
963 TyTuple(ref tys, _) => tys.is_empty(),
968 pub fn is_never(&self) -> bool {
975 // Test whether this is a `()` which was produced by defaulting a
976 // diverging type variable with feature(never_type) disabled.
977 pub fn is_defaulted_unit(&self) -> bool {
979 TyTuple(_, true) => true,
984 /// Checks whether a type is visibly uninhabited from a particular module.
990 /// pub struct SecretlyUninhabited {
997 /// pub struct AlsoSecretlyUninhabited {
1005 /// x: a::b::SecretlyUninhabited,
1006 /// y: c::AlsoSecretlyUninhabited,
1009 /// In this code, the type `Foo` will only be visibly uninhabited inside the
1010 /// modules b, c and d. This effects pattern-matching on `Foo` or types that
1015 /// let foo_result: Result<T, Foo> = ... ;
1016 /// let Ok(t) = foo_result;
1018 /// This code should only compile in modules where the uninhabitedness of Foo is
1020 pub fn is_uninhabited_from(&self, module: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1021 let mut visited = FxHashSet::default();
1022 let forest = self.uninhabited_from(&mut visited, tcx);
1024 // To check whether this type is uninhabited at all (not just from the
1025 // given node) you could check whether the forest is empty.
1027 // forest.is_empty()
1029 forest.contains(tcx, module)
1032 pub fn is_primitive(&self) -> bool {
1034 TyBool | TyChar | TyInt(_) | TyUint(_) | TyFloat(_) => true,
1039 pub fn is_ty_var(&self) -> bool {
1041 TyInfer(TyVar(_)) => true,
1046 pub fn is_phantom_data(&self) -> bool {
1047 if let TyAdt(def, _) = self.sty {
1048 def.is_phantom_data()
1054 pub fn is_bool(&self) -> bool { self.sty == TyBool }
1056 pub fn is_param(&self, index: u32) -> bool {
1058 ty::TyParam(ref data) => data.idx == index,
1063 pub fn is_self(&self) -> bool {
1065 TyParam(ref p) => p.is_self(),
1070 pub fn is_slice(&self) -> bool {
1072 TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
1073 TySlice(_) | TyStr => true,
1080 pub fn is_structural(&self) -> bool {
1082 TyAdt(..) | TyTuple(..) | TyArray(..) | TyClosure(..) => true,
1083 _ => self.is_slice() | self.is_trait()
1088 pub fn is_simd(&self) -> bool {
1090 TyAdt(def, _) => def.is_simd(),
1095 pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1097 TyArray(ty, _) | TySlice(ty) => ty,
1098 TyStr => tcx.mk_mach_uint(ast::UintTy::U8),
1099 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1103 pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1105 TyAdt(def, substs) => {
1106 def.struct_variant().fields[0].ty(tcx, substs)
1108 _ => bug!("simd_type called on invalid type")
1112 pub fn simd_size(&self, _cx: TyCtxt) -> usize {
1114 TyAdt(def, _) => def.struct_variant().fields.len(),
1115 _ => bug!("simd_size called on invalid type")
1119 pub fn is_region_ptr(&self) -> bool {
1126 pub fn is_mutable_pointer(&self) -> bool {
1128 TyRawPtr(tnm) | TyRef(_, tnm) => if let hir::Mutability::MutMutable = tnm.mutbl {
1137 pub fn is_unsafe_ptr(&self) -> bool {
1139 TyRawPtr(_) => return true,
1144 pub fn is_box(&self) -> bool {
1146 TyAdt(def, _) => def.is_box(),
1151 pub fn boxed_ty(&self) -> Ty<'tcx> {
1153 TyAdt(def, substs) if def.is_box() => substs.type_at(0),
1154 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1159 A scalar type is one that denotes an atomic datum, with no sub-components.
1160 (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1161 contents are abstract to rustc.)
1163 pub fn is_scalar(&self) -> bool {
1165 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
1166 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
1167 TyFnDef(..) | TyFnPtr(_) | TyRawPtr(_) => true,
1172 /// Returns true if this type is a floating point type and false otherwise.
1173 pub fn is_floating_point(&self) -> bool {
1176 TyInfer(FloatVar(_)) => true,
1181 pub fn is_trait(&self) -> bool {
1183 TyDynamic(..) => true,
1188 pub fn is_integral(&self) -> bool {
1190 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
1195 pub fn is_fresh(&self) -> bool {
1197 TyInfer(FreshTy(_)) => true,
1198 TyInfer(FreshIntTy(_)) => true,
1199 TyInfer(FreshFloatTy(_)) => true,
1204 pub fn is_uint(&self) -> bool {
1206 TyInfer(IntVar(_)) | TyUint(ast::UintTy::Us) => true,
1211 pub fn is_char(&self) -> bool {
1218 pub fn is_fp(&self) -> bool {
1220 TyInfer(FloatVar(_)) | TyFloat(_) => true,
1225 pub fn is_numeric(&self) -> bool {
1226 self.is_integral() || self.is_fp()
1229 pub fn is_signed(&self) -> bool {
1236 pub fn is_machine(&self) -> bool {
1238 TyInt(ast::IntTy::Is) | TyUint(ast::UintTy::Us) => false,
1239 TyInt(..) | TyUint(..) | TyFloat(..) => true,
1244 pub fn has_concrete_skeleton(&self) -> bool {
1246 TyParam(_) | TyInfer(_) | TyError => false,
1251 // Returns the type and mutability of *ty.
1253 // The parameter `explicit` indicates if this is an *explicit* dereference.
1254 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1255 pub fn builtin_deref(&self, explicit: bool, pref: ty::LvaluePreference)
1256 -> Option<TypeAndMut<'tcx>>
1259 TyAdt(def, _) if def.is_box() => {
1261 ty: self.boxed_ty(),
1262 mutbl: if pref == ty::PreferMutLvalue {
1269 TyRef(_, mt) => Some(mt),
1270 TyRawPtr(mt) if explicit => Some(mt),
1275 // Returns the type of ty[i]
1276 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1278 TyArray(ty, _) | TySlice(ty) => Some(ty),
1283 pub fn fn_sig(&self) -> &'tcx PolyFnSig<'tcx> {
1285 TyFnDef(.., ref f) | TyFnPtr(ref f) => &f.sig,
1286 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1290 /// Returns the ABI of the given function.
1291 pub fn fn_abi(&self) -> abi::Abi {
1293 TyFnDef(.., ref f) | TyFnPtr(ref f) => f.abi,
1294 _ => bug!("Ty::fn_abi() called on non-fn type"),
1298 // Type accessors for substructures of types
1299 pub fn fn_args(&self) -> ty::Binder<&[Ty<'tcx>]> {
1300 self.fn_sig().inputs()
1303 pub fn fn_ret(&self) -> Binder<Ty<'tcx>> {
1304 self.fn_sig().output()
1307 pub fn is_fn(&self) -> bool {
1309 TyFnDef(..) | TyFnPtr(_) => true,
1314 pub fn ty_to_def_id(&self) -> Option<DefId> {
1316 TyDynamic(ref tt, ..) => tt.principal().map(|p| p.def_id()),
1317 TyAdt(def, _) => Some(def.did),
1318 TyClosure(id, _) => Some(id),
1323 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1325 TyAdt(adt, _) => Some(adt),
1330 /// Returns the regions directly referenced from this type (but
1331 /// not types reachable from this type via `walk_tys`). This
1332 /// ignores late-bound regions binders.
1333 pub fn regions(&self) -> Vec<&'tcx ty::Region> {
1335 TyRef(region, _) => {
1338 TyDynamic(ref obj, region) => {
1339 let mut v = vec![region];
1340 if let Some(p) = obj.principal() {
1341 v.extend(p.skip_binder().substs.regions());
1345 TyAdt(_, substs) | TyAnon(_, substs) => {
1346 substs.regions().collect()
1348 TyClosure(_, ref substs) => {
1349 substs.substs.regions().collect()
1351 TyProjection(ref data) => {
1352 data.trait_ref.substs.regions().collect()