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, Subst};
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;
27 use util::nodemap::FxHashMap;
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 {
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
72 pub fn is_named(&self) -> bool {
74 BoundRegion::BrNamed(..) => true,
80 /// NB: If you change this, you'll probably want to change the corresponding
81 /// AST structure in libsyntax/ast.rs as well.
82 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
83 pub enum TypeVariants<'tcx> {
84 /// The primitive boolean type. Written as `bool`.
87 /// The primitive character type; holds a Unicode scalar value
88 /// (a non-surrogate code point). Written as `char`.
91 /// A primitive signed integer type. For example, `i32`.
94 /// A primitive unsigned integer type. For example, `u32`.
97 /// A primitive floating-point type. For example, `f64`.
98 TyFloat(ast::FloatTy),
100 /// Structures, enumerations and unions.
102 /// Substs here, possibly against intuition, *may* contain `TyParam`s.
103 /// That is, even after substitution it is possible that there are type
104 /// variables. This happens when the `TyAdt` corresponds to an ADT
105 /// definition and not a concrete use of it.
106 TyAdt(&'tcx AdtDef, &'tcx Substs<'tcx>),
108 /// The pointee of a string slice. Written as `str`.
111 /// An array with the given length. Written as `[T; n]`.
112 TyArray(Ty<'tcx>, usize),
114 /// The pointee of an array slice. Written as `[T]`.
117 /// A raw pointer. Written as `*mut T` or `*const T`
118 TyRawPtr(TypeAndMut<'tcx>),
120 /// A reference; a pointer with an associated lifetime. Written as
121 /// `&'a mut T` or `&'a T`.
122 TyRef(Region<'tcx>, TypeAndMut<'tcx>),
124 /// The anonymous type of a function declaration/definition. Each
125 /// function has a unique type.
126 TyFnDef(DefId, &'tcx Substs<'tcx>),
128 /// A pointer to a function. Written as `fn() -> i32`.
129 TyFnPtr(PolyFnSig<'tcx>),
131 /// A trait, defined with `trait`.
132 TyDynamic(Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
134 /// The anonymous type of a closure. Used to represent the type of
136 TyClosure(DefId, ClosureSubsts<'tcx>),
138 /// The never type `!`
141 /// A tuple type. For example, `(i32, bool)`.
142 /// The bool indicates whether this is a unit tuple and was created by
143 /// defaulting a diverging type variable with feature(never_type) disabled.
144 /// It's only purpose is for raising future-compatibility warnings for when
145 /// diverging type variables start defaulting to ! instead of ().
146 TyTuple(&'tcx Slice<Ty<'tcx>>, bool),
148 /// The projection of an associated type. For example,
149 /// `<T as Trait<..>>::N`.
150 TyProjection(ProjectionTy<'tcx>),
152 /// Anonymized (`impl Trait`) type found in a return type.
153 /// The DefId comes from the `impl Trait` ast::Ty node, and the
154 /// substitutions are for the generics of the function in question.
155 /// After typeck, the concrete type can be found in the `types` map.
156 TyAnon(DefId, &'tcx Substs<'tcx>),
158 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
161 /// A type variable used during type-checking.
164 /// A placeholder for a type which could not be computed; this is
165 /// propagated to avoid useless error messages.
169 /// A closure can be modeled as a struct that looks like:
171 /// struct Closure<'l0...'li, T0...Tj, U0...Uk> {
177 /// where 'l0...'li and T0...Tj are the lifetime and type parameters
178 /// in scope on the function that defined the closure, and U0...Uk are
179 /// type parameters representing the types of its upvars (borrowed, if
182 /// So, for example, given this function:
184 /// fn foo<'a, T>(data: &'a mut T) {
185 /// do(|| data.count += 1)
188 /// the type of the closure would be something like:
190 /// struct Closure<'a, T, U0> {
194 /// Note that the type of the upvar is not specified in the struct.
195 /// You may wonder how the impl would then be able to use the upvar,
196 /// if it doesn't know it's type? The answer is that the impl is
197 /// (conceptually) not fully generic over Closure but rather tied to
198 /// instances with the expected upvar types:
200 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
204 /// You can see that the *impl* fully specified the type of the upvar
205 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
206 /// (Here, I am assuming that `data` is mut-borrowed.)
208 /// Now, the last question you may ask is: Why include the upvar types
209 /// as extra type parameters? The reason for this design is that the
210 /// upvar types can reference lifetimes that are internal to the
211 /// creating function. In my example above, for example, the lifetime
212 /// `'b` represents the extent of the closure itself; this is some
213 /// subset of `foo`, probably just the extent of the call to the to
214 /// `do()`. If we just had the lifetime/type parameters from the
215 /// enclosing function, we couldn't name this lifetime `'b`. Note that
216 /// there can also be lifetimes in the types of the upvars themselves,
217 /// if one of them happens to be a reference to something that the
218 /// creating fn owns.
220 /// OK, you say, so why not create a more minimal set of parameters
221 /// that just includes the extra lifetime parameters? The answer is
222 /// primarily that it would be hard --- we don't know at the time when
223 /// we create the closure type what the full types of the upvars are,
224 /// nor do we know which are borrowed and which are not. In this
225 /// design, we can just supply a fresh type parameter and figure that
228 /// All right, you say, but why include the type parameters from the
229 /// original function then? The answer is that trans may need them
230 /// when monomorphizing, and they may not appear in the upvars. A
231 /// closure could capture no variables but still make use of some
232 /// in-scope type parameter with a bound (e.g., if our example above
233 /// had an extra `U: Default`, and the closure called `U::default()`).
235 /// There is another reason. This design (implicitly) prohibits
236 /// closures from capturing themselves (except via a trait
237 /// object). This simplifies closure inference considerably, since it
238 /// means that when we infer the kind of a closure or its upvars, we
239 /// don't have to handle cycles where the decisions we make for
240 /// closure C wind up influencing the decisions we ought to make for
241 /// closure C (which would then require fixed point iteration to
242 /// handle). Plus it fixes an ICE. :P
243 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
244 pub struct ClosureSubsts<'tcx> {
245 /// Lifetime and type parameters from the enclosing function,
246 /// concatenated with the types of the upvars.
248 /// These are separated out because trans wants to pass them around
249 /// when monomorphizing.
250 pub substs: &'tcx Substs<'tcx>,
253 impl<'a, 'gcx, 'acx, 'tcx> ClosureSubsts<'tcx> {
255 pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'acx>) ->
256 impl Iterator<Item=Ty<'tcx>> + 'tcx
258 let generics = tcx.generics_of(def_id);
259 self.substs[self.substs.len()-generics.own_count()..].iter().map(
260 |t| t.as_type().expect("unexpected region in upvars"))
264 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
265 pub enum ExistentialPredicate<'tcx> {
267 Trait(ExistentialTraitRef<'tcx>),
268 /// e.g. Iterator::Item = T
269 Projection(ExistentialProjection<'tcx>),
274 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
275 pub fn cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
276 use self::ExistentialPredicate::*;
277 match (*self, *other) {
278 (Trait(_), Trait(_)) => Ordering::Equal,
279 (Projection(ref a), Projection(ref b)) =>
280 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
281 (AutoTrait(ref a), AutoTrait(ref b)) =>
282 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
283 (Trait(_), _) => Ordering::Less,
284 (Projection(_), Trait(_)) => Ordering::Greater,
285 (Projection(_), _) => Ordering::Less,
286 (AutoTrait(_), _) => Ordering::Greater,
292 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
293 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
294 -> ty::Predicate<'tcx> {
296 match *self.skip_binder() {
297 ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
298 ExistentialPredicate::Projection(p) =>
299 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
300 ExistentialPredicate::AutoTrait(did) => {
301 let trait_ref = Binder(ty::TraitRef {
303 substs: tcx.mk_substs_trait(self_ty, &[]),
305 trait_ref.to_predicate()
311 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<ExistentialPredicate<'tcx>> {}
313 impl<'tcx> Slice<ExistentialPredicate<'tcx>> {
314 pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
316 Some(&ExistentialPredicate::Trait(tr)) => Some(tr),
322 pub fn projection_bounds<'a>(&'a self) ->
323 impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
324 self.iter().filter_map(|predicate| {
326 ExistentialPredicate::Projection(p) => Some(p),
333 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
334 self.iter().filter_map(|predicate| {
336 ExistentialPredicate::AutoTrait(d) => Some(d),
343 impl<'tcx> Binder<&'tcx Slice<ExistentialPredicate<'tcx>>> {
344 pub fn principal(&self) -> Option<PolyExistentialTraitRef<'tcx>> {
345 self.skip_binder().principal().map(Binder)
349 pub fn projection_bounds<'a>(&'a self) ->
350 impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
351 self.skip_binder().projection_bounds().map(Binder)
355 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
356 self.skip_binder().auto_traits()
359 pub fn iter<'a>(&'a self)
360 -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
361 self.skip_binder().iter().cloned().map(Binder)
365 /// A complete reference to a trait. These take numerous guises in syntax,
366 /// but perhaps the most recognizable form is in a where clause:
370 /// This would be represented by a trait-reference where the def-id is the
371 /// def-id for the trait `Foo` and the substs define `T` as parameter 0,
372 /// and `U` as parameter 1.
374 /// Trait references also appear in object types like `Foo<U>`, but in
375 /// that case the `Self` parameter is absent from the substitutions.
377 /// Note that a `TraitRef` introduces a level of region binding, to
378 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
379 /// U>` or higher-ranked object types.
380 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
381 pub struct TraitRef<'tcx> {
383 pub substs: &'tcx Substs<'tcx>,
386 impl<'tcx> TraitRef<'tcx> {
387 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
388 TraitRef { def_id: def_id, substs: substs }
391 pub fn self_ty(&self) -> Ty<'tcx> {
392 self.substs.type_at(0)
395 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
396 // Select only the "input types" from a trait-reference. For
397 // now this is all the types that appear in the
398 // trait-reference, but it should eventually exclude
404 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
406 impl<'tcx> PolyTraitRef<'tcx> {
407 pub fn self_ty(&self) -> Ty<'tcx> {
411 pub fn def_id(&self) -> DefId {
415 pub fn substs(&self) -> &'tcx Substs<'tcx> {
416 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
420 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
421 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
425 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
426 // Note that we preserve binding levels
427 Binder(ty::TraitPredicate { trait_ref: self.0.clone() })
431 /// An existential reference to a trait, where `Self` is erased.
432 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
434 /// exists T. T: Trait<'a, 'b, X, Y>
436 /// The substitutions don't include the erased `Self`, only trait
437 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
438 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
439 pub struct ExistentialTraitRef<'tcx> {
441 pub substs: &'tcx Substs<'tcx>,
444 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
445 pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
446 // Select only the "input types" from a trait-reference. For
447 // now this is all the types that appear in the
448 // trait-reference, but it should eventually exclude
453 /// Object types don't have a self-type specified. Therefore, when
454 /// we convert the principal trait-ref into a normal trait-ref,
455 /// you must give *some* self-type. A common choice is `mk_err()`
456 /// or some skolemized type.
457 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
458 -> ty::TraitRef<'tcx> {
459 // otherwise the escaping regions would be captured by the binder
460 assert!(!self_ty.has_escaping_regions());
464 substs: tcx.mk_substs(
465 iter::once(Kind::from(self_ty)).chain(self.substs.iter().cloned()))
470 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
472 impl<'tcx> PolyExistentialTraitRef<'tcx> {
473 pub fn def_id(&self) -> DefId {
477 pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
478 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
483 /// Binder is a binder for higher-ranked lifetimes. It is part of the
484 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
485 /// (which would be represented by the type `PolyTraitRef ==
486 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
487 /// erase, or otherwise "discharge" these bound regions, we change the
488 /// type from `Binder<T>` to just `T` (see
489 /// e.g. `liberate_late_bound_regions`).
490 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
491 pub struct Binder<T>(pub T);
494 /// Skips the binder and returns the "bound" value. This is a
495 /// risky thing to do because it's easy to get confused about
496 /// debruijn indices and the like. It is usually better to
497 /// discharge the binder using `no_late_bound_regions` or
498 /// `replace_late_bound_regions` or something like
499 /// that. `skip_binder` is only valid when you are either
500 /// extracting data that has nothing to do with bound regions, you
501 /// are doing some sort of test that does not involve bound
502 /// regions, or you are being very careful about your depth
505 /// Some examples where `skip_binder` is reasonable:
506 /// - extracting the def-id from a PolyTraitRef;
507 /// - comparing the self type of a PolyTraitRef to see if it is equal to
508 /// a type parameter `X`, since the type `X` does not reference any regions
509 pub fn skip_binder(&self) -> &T {
513 pub fn as_ref(&self) -> Binder<&T> {
517 pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
518 where F: FnOnce(&T) -> U
520 self.as_ref().map_bound(f)
523 pub fn map_bound<F, U>(self, f: F) -> Binder<U>
524 where F: FnOnce(T) -> U
526 ty::Binder(f(self.0))
530 impl fmt::Debug for TypeFlags {
531 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
532 write!(f, "{:x}", self.bits)
536 /// Represents the projection of an associated type. In explicit UFCS
537 /// form this would be written `<T as Trait<..>>::N`.
538 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
539 pub struct ProjectionTy<'tcx> {
540 /// The parameters of the associated item.
541 pub substs: &'tcx Substs<'tcx>,
543 /// The DefId of the TraitItem for the associated type N.
545 /// Note that this is not the DefId of the TraitRef containing this
546 /// associated type, which is in tcx.associated_item(item_def_id).container.
547 pub item_def_id: DefId,
550 impl<'a, 'tcx> ProjectionTy<'tcx> {
551 /// Construct a ProjectionTy by searching the trait from trait_ref for the
552 /// associated item named item_name.
553 pub fn from_ref_and_name(
554 tcx: TyCtxt, trait_ref: ty::TraitRef<'tcx>, item_name: Name
555 ) -> ProjectionTy<'tcx> {
556 let item_def_id = tcx.associated_items(trait_ref.def_id).find(
557 |item| item.name == item_name && item.kind == ty::AssociatedKind::Type
561 substs: trait_ref.substs,
566 /// Extracts the underlying trait reference from this projection.
567 /// For example, if this is a projection of `<T as Iterator>::Item`,
568 /// then this function would return a `T: Iterator` trait reference.
569 pub fn trait_ref(&self, tcx: TyCtxt) -> ty::TraitRef<'tcx> {
570 let def_id = tcx.associated_item(self.item_def_id).container.id();
577 pub fn self_ty(&self) -> Ty<'tcx> {
578 self.substs.type_at(0)
583 /// Signature of a function type, which I have arbitrarily
584 /// decided to use to refer to the input/output types.
586 /// - `inputs` is the list of arguments and their modes.
587 /// - `output` is the return type.
588 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
589 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
590 pub struct FnSig<'tcx> {
591 pub inputs_and_output: &'tcx Slice<Ty<'tcx>>,
593 pub unsafety: hir::Unsafety,
597 impl<'tcx> FnSig<'tcx> {
598 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
599 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
602 pub fn output(&self) -> Ty<'tcx> {
603 self.inputs_and_output[self.inputs_and_output.len() - 1]
607 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
609 impl<'tcx> PolyFnSig<'tcx> {
610 pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
611 Binder(self.skip_binder().inputs())
613 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
614 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
616 pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
617 self.map_bound_ref(|fn_sig| fn_sig.output().clone())
619 pub fn variadic(&self) -> bool {
620 self.skip_binder().variadic
622 pub fn unsafety(&self) -> hir::Unsafety {
623 self.skip_binder().unsafety
625 pub fn abi(&self) -> abi::Abi {
626 self.skip_binder().abi
630 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
636 impl<'a, 'gcx, 'tcx> ParamTy {
637 pub fn new(index: u32, name: Name) -> ParamTy {
638 ParamTy { idx: index, name: name }
641 pub fn for_self() -> ParamTy {
642 ParamTy::new(0, keywords::SelfType.name())
645 pub fn for_def(def: &ty::TypeParameterDef) -> ParamTy {
646 ParamTy::new(def.index, def.name)
649 pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
650 tcx.mk_param(self.idx, self.name)
653 pub fn is_self(&self) -> bool {
654 if self.name == keywords::SelfType.name() {
655 assert_eq!(self.idx, 0);
663 /// A [De Bruijn index][dbi] is a standard means of representing
664 /// regions (and perhaps later types) in a higher-ranked setting. In
665 /// particular, imagine a type like this:
667 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
670 /// | +------------+ 1 | |
672 /// +--------------------------------+ 2 |
674 /// +------------------------------------------+ 1
676 /// In this type, there are two binders (the outer fn and the inner
677 /// fn). We need to be able to determine, for any given region, which
678 /// fn type it is bound by, the inner or the outer one. There are
679 /// various ways you can do this, but a De Bruijn index is one of the
680 /// more convenient and has some nice properties. The basic idea is to
681 /// count the number of binders, inside out. Some examples should help
682 /// clarify what I mean.
684 /// Let's start with the reference type `&'b isize` that is the first
685 /// argument to the inner function. This region `'b` is assigned a De
686 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
687 /// fn). The region `'a` that appears in the second argument type (`&'a
688 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
689 /// second-innermost binder". (These indices are written on the arrays
692 /// What is interesting is that De Bruijn index attached to a particular
693 /// variable will vary depending on where it appears. For example,
694 /// the final type `&'a char` also refers to the region `'a` declared on
695 /// the outermost fn. But this time, this reference is not nested within
696 /// any other binders (i.e., it is not an argument to the inner fn, but
697 /// rather the outer one). Therefore, in this case, it is assigned a
698 /// De Bruijn index of 1, because the innermost binder in that location
701 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
702 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
703 pub struct DebruijnIndex {
704 /// We maintain the invariant that this is never 0. So 1 indicates
705 /// the innermost binder. To ensure this, create with `DebruijnIndex::new`.
709 pub type Region<'tcx> = &'tcx RegionKind;
711 /// Representation of regions.
713 /// Unlike types, most region variants are "fictitious", not concrete,
714 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
715 /// ones representing concrete regions.
719 /// These are regions that are stored behind a binder and must be substituted
720 /// with some concrete region before being used. There are 2 kind of
721 /// bound regions: early-bound, which are bound in an item's Generics,
722 /// and are substituted by a Substs, and late-bound, which are part of
723 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
724 /// the likes of `liberate_late_bound_regions`. The distinction exists
725 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
727 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
728 /// outside their binder, e.g. in types passed to type inference, and
729 /// should first be substituted (by skolemized regions, free regions,
730 /// or region variables).
732 /// ## Skolemized and Free Regions
734 /// One often wants to work with bound regions without knowing their precise
735 /// identity. For example, when checking a function, the lifetime of a borrow
736 /// can end up being assigned to some region parameter. In these cases,
737 /// it must be ensured that bounds on the region can't be accidentally
738 /// assumed without being checked.
740 /// The process of doing that is called "skolemization". The bound regions
741 /// are replaced by skolemized markers, which don't satisfy any relation
742 /// not explicitly provided.
744 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
745 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
746 /// to be used. These also support explicit bounds: both the internally-stored
747 /// *scope*, which the region is assumed to outlive, as well as other
748 /// relations stored in the `FreeRegionMap`. Note that these relations
749 /// aren't checked when you `make_subregion` (or `eq_types`), only by
750 /// `resolve_regions_and_report_errors`.
752 /// When working with higher-ranked types, some region relations aren't
753 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
754 /// `ReSkolemized` is designed for this purpose. In these contexts,
755 /// there's also the risk that some inference variable laying around will
756 /// get unified with your skolemized region: if you want to check whether
757 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
758 /// with a skolemized region `'%a`, the variable `'_` would just be
759 /// instantiated to the skolemized region `'%a`, which is wrong because
760 /// the inference variable is supposed to satisfy the relation
761 /// *for every value of the skolemized region*. To ensure that doesn't
762 /// happen, you can use `leak_check`. This is more clearly explained
763 /// by infer/higher_ranked/README.md.
765 /// [1] http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
766 /// [2] http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
767 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable)]
768 pub enum RegionKind {
769 // Region bound in a type or fn declaration which will be
770 // substituted 'early' -- that is, at the same time when type
771 // parameters are substituted.
772 ReEarlyBound(EarlyBoundRegion),
774 // Region bound in a function scope, which will be substituted when the
775 // function is called.
776 ReLateBound(DebruijnIndex, BoundRegion),
778 /// When checking a function body, the types of all arguments and so forth
779 /// that refer to bound region parameters are modified to refer to free
780 /// region parameters.
783 /// A concrete region naming some statically determined extent
784 /// (e.g. an expression or sequence of statements) within the
785 /// current function.
786 ReScope(region::CodeExtent),
788 /// Static data that has an "infinite" lifetime. Top in the region lattice.
791 /// A region variable. Should not exist after typeck.
794 /// A skolemized region - basically the higher-ranked version of ReFree.
795 /// Should not exist after typeck.
796 ReSkolemized(SkolemizedRegionVid, BoundRegion),
798 /// Empty lifetime is for data that is never accessed.
799 /// Bottom in the region lattice. We treat ReEmpty somewhat
800 /// specially; at least right now, we do not generate instances of
801 /// it during the GLB computations, but rather
802 /// generate an error instead. This is to improve error messages.
803 /// The only way to get an instance of ReEmpty is to have a region
804 /// variable with no constraints.
807 /// Erased region, used by trait selection, in MIR and during trans.
811 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
813 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
814 pub struct EarlyBoundRegion {
820 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
825 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
830 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
831 pub struct FloatVid {
835 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
836 pub struct RegionVid {
840 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
841 pub struct SkolemizedRegionVid {
845 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
851 /// A `FreshTy` is one that is generated as a replacement for an
852 /// unbound type variable. This is convenient for caching etc. See
853 /// `infer::freshen` for more details.
859 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
860 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
861 pub struct ExistentialProjection<'tcx> {
862 pub item_def_id: DefId,
863 pub substs: &'tcx Substs<'tcx>,
867 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
869 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
870 /// Extracts the underlying existential trait reference from this projection.
871 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
872 /// then this function would return a `exists T. T: Iterator` existential trait
874 pub fn trait_ref(&self, tcx: TyCtxt) -> ty::ExistentialTraitRef<'tcx> {
875 let def_id = tcx.associated_item(self.item_def_id).container.id();
876 ty::ExistentialTraitRef{
882 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
884 -> ty::ProjectionPredicate<'tcx>
886 // otherwise the escaping regions would be captured by the binders
887 assert!(!self_ty.has_escaping_regions());
889 ty::ProjectionPredicate {
890 projection_ty: ty::ProjectionTy {
891 item_def_id: self.item_def_id,
892 substs: tcx.mk_substs(
893 iter::once(Kind::from(self_ty)).chain(self.substs.iter().cloned())),
900 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
901 pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
902 -> ty::PolyProjectionPredicate<'tcx> {
903 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
908 pub fn new(depth: u32) -> DebruijnIndex {
910 DebruijnIndex { depth: depth }
913 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
914 DebruijnIndex { depth: self.depth + amount }
920 pub fn is_late_bound(&self) -> bool {
922 ty::ReLateBound(..) => true,
927 pub fn needs_infer(&self) -> bool {
929 ty::ReVar(..) | ty::ReSkolemized(..) => true,
934 pub fn escapes_depth(&self, depth: u32) -> bool {
936 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
941 /// Returns the depth of `self` from the (1-based) binding level `depth`
942 pub fn from_depth(&self, depth: u32) -> RegionKind {
944 ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
945 depth: debruijn.depth - (depth - 1)
951 pub fn type_flags(&self) -> TypeFlags {
952 let mut flags = TypeFlags::empty();
956 flags = flags | TypeFlags::HAS_RE_INFER;
957 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
959 ty::ReSkolemized(..) => {
960 flags = flags | TypeFlags::HAS_RE_INFER;
961 flags = flags | TypeFlags::HAS_RE_SKOL;
962 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
964 ty::ReLateBound(..) => { }
965 ty::ReEarlyBound(..) => { flags = flags | TypeFlags::HAS_RE_EARLY_BOUND; }
966 ty::ReStatic | ty::ReErased => { }
967 _ => { flags = flags | TypeFlags::HAS_FREE_REGIONS; }
971 ty::ReStatic | ty::ReEmpty | ty::ReErased => (),
972 _ => flags = flags | TypeFlags::HAS_LOCAL_NAMES,
975 debug!("type_flags({:?}) = {:?}", self, flags);
980 // This method returns whether the given Region is Named
981 pub fn is_named_region(&self) -> bool {
983 ty::ReFree(ref free_region) => {
984 match free_region.bound_region {
985 ty::BrNamed(..) => true,
995 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
996 pub fn as_opt_param_ty(&self) -> Option<ty::ParamTy> {
998 ty::TyParam(ref d) => Some(d.clone()),
1003 pub fn is_nil(&self) -> bool {
1005 TyTuple(ref tys, _) => tys.is_empty(),
1010 pub fn is_never(&self) -> bool {
1017 /// Test whether this is a `()` which was produced by defaulting a
1018 /// diverging type variable with feature(never_type) disabled.
1019 pub fn is_defaulted_unit(&self) -> bool {
1021 TyTuple(_, true) => true,
1026 /// Checks whether a type is visibly uninhabited from a particular module.
1032 /// pub struct SecretlyUninhabited {
1039 /// pub struct AlsoSecretlyUninhabited {
1047 /// x: a::b::SecretlyUninhabited,
1048 /// y: c::AlsoSecretlyUninhabited,
1051 /// In this code, the type `Foo` will only be visibly uninhabited inside the
1052 /// modules b, c and d. This effects pattern-matching on `Foo` or types that
1057 /// let foo_result: Result<T, Foo> = ... ;
1058 /// let Ok(t) = foo_result;
1060 /// This code should only compile in modules where the uninhabitedness of Foo is
1062 pub fn is_uninhabited_from(&self, module: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1063 let mut visited = FxHashMap::default();
1064 let forest = self.uninhabited_from(&mut visited, tcx);
1066 // To check whether this type is uninhabited at all (not just from the
1067 // given node) you could check whether the forest is empty.
1069 // forest.is_empty()
1071 forest.contains(tcx, module)
1074 pub fn is_primitive(&self) -> bool {
1076 TyBool | TyChar | TyInt(_) | TyUint(_) | TyFloat(_) => true,
1081 pub fn is_ty_var(&self) -> bool {
1083 TyInfer(TyVar(_)) => true,
1088 pub fn is_phantom_data(&self) -> bool {
1089 if let TyAdt(def, _) = self.sty {
1090 def.is_phantom_data()
1096 pub fn is_bool(&self) -> bool { self.sty == TyBool }
1098 pub fn is_param(&self, index: u32) -> bool {
1100 ty::TyParam(ref data) => data.idx == index,
1105 pub fn is_self(&self) -> bool {
1107 TyParam(ref p) => p.is_self(),
1112 pub fn is_slice(&self) -> bool {
1114 TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
1115 TySlice(_) | TyStr => true,
1122 pub fn is_structural(&self) -> bool {
1124 TyAdt(..) | TyTuple(..) | TyArray(..) | TyClosure(..) => true,
1125 _ => self.is_slice() | self.is_trait(),
1130 pub fn is_simd(&self) -> bool {
1132 TyAdt(def, _) => def.repr.simd(),
1137 pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1139 TyArray(ty, _) | TySlice(ty) => ty,
1140 TyStr => tcx.mk_mach_uint(ast::UintTy::U8),
1141 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1145 pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1147 TyAdt(def, substs) => {
1148 def.struct_variant().fields[0].ty(tcx, substs)
1150 _ => bug!("simd_type called on invalid type")
1154 pub fn simd_size(&self, _cx: TyCtxt) -> usize {
1156 TyAdt(def, _) => def.struct_variant().fields.len(),
1157 _ => bug!("simd_size called on invalid type")
1161 pub fn is_region_ptr(&self) -> bool {
1168 pub fn is_mutable_pointer(&self) -> bool {
1170 TyRawPtr(tnm) | TyRef(_, tnm) => if let hir::Mutability::MutMutable = tnm.mutbl {
1179 pub fn is_unsafe_ptr(&self) -> bool {
1181 TyRawPtr(_) => return true,
1186 pub fn is_box(&self) -> bool {
1188 TyAdt(def, _) => def.is_box(),
1193 /// panics if called on any type other than `Box<T>`
1194 pub fn boxed_ty(&self) -> Ty<'tcx> {
1196 TyAdt(def, substs) if def.is_box() => substs.type_at(0),
1197 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1201 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1202 /// (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1203 /// contents are abstract to rustc.)
1204 pub fn is_scalar(&self) -> bool {
1206 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
1207 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
1208 TyFnDef(..) | TyFnPtr(_) | TyRawPtr(_) => true,
1213 /// Returns true if this type is a floating point type and false otherwise.
1214 pub fn is_floating_point(&self) -> bool {
1217 TyInfer(FloatVar(_)) => true,
1222 pub fn is_trait(&self) -> bool {
1224 TyDynamic(..) => true,
1229 pub fn is_closure(&self) -> bool {
1231 TyClosure(..) => true,
1236 pub fn is_integral(&self) -> bool {
1238 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
1243 pub fn is_fresh(&self) -> bool {
1245 TyInfer(FreshTy(_)) => true,
1246 TyInfer(FreshIntTy(_)) => true,
1247 TyInfer(FreshFloatTy(_)) => true,
1252 pub fn is_uint(&self) -> bool {
1254 TyInfer(IntVar(_)) | TyUint(ast::UintTy::Us) => true,
1259 pub fn is_char(&self) -> bool {
1266 pub fn is_fp(&self) -> bool {
1268 TyInfer(FloatVar(_)) | TyFloat(_) => true,
1273 pub fn is_numeric(&self) -> bool {
1274 self.is_integral() || self.is_fp()
1277 pub fn is_signed(&self) -> bool {
1284 pub fn is_machine(&self) -> bool {
1286 TyInt(ast::IntTy::Is) | TyUint(ast::UintTy::Us) => false,
1287 TyInt(..) | TyUint(..) | TyFloat(..) => true,
1292 pub fn has_concrete_skeleton(&self) -> bool {
1294 TyParam(_) | TyInfer(_) | TyError => false,
1299 /// Returns the type and mutability of *ty.
1301 /// The parameter `explicit` indicates if this is an *explicit* dereference.
1302 /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1303 pub fn builtin_deref(&self, explicit: bool, pref: ty::LvaluePreference)
1304 -> Option<TypeAndMut<'tcx>>
1307 TyAdt(def, _) if def.is_box() => {
1309 ty: self.boxed_ty(),
1310 mutbl: if pref == ty::PreferMutLvalue {
1317 TyRef(_, mt) => Some(mt),
1318 TyRawPtr(mt) if explicit => Some(mt),
1323 /// Returns the type of ty[i]
1324 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1326 TyArray(ty, _) | TySlice(ty) => Some(ty),
1331 pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1333 TyFnDef(def_id, substs) => {
1334 tcx.fn_sig(def_id).subst(tcx, substs)
1337 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1341 pub fn is_fn(&self) -> bool {
1343 TyFnDef(..) | TyFnPtr(_) => true,
1348 pub fn ty_to_def_id(&self) -> Option<DefId> {
1350 TyDynamic(ref tt, ..) => tt.principal().map(|p| p.def_id()),
1351 TyAdt(def, _) => Some(def.did),
1352 TyClosure(id, _) => Some(id),
1357 pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1359 TyAdt(adt, _) => Some(adt),
1364 /// Returns the regions directly referenced from this type (but
1365 /// not types reachable from this type via `walk_tys`). This
1366 /// ignores late-bound regions binders.
1367 pub fn regions(&self) -> Vec<ty::Region<'tcx>> {
1369 TyRef(region, _) => {
1372 TyDynamic(ref obj, region) => {
1373 let mut v = vec![region];
1374 if let Some(p) = obj.principal() {
1375 v.extend(p.skip_binder().substs.regions());
1379 TyAdt(_, substs) | TyAnon(_, substs) => {
1380 substs.regions().collect()
1382 TyClosure(_, ref substs) => {
1383 substs.substs.regions().collect()
1385 TyProjection(ref data) => {
1386 data.substs.regions().collect()