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
14 use hir::def_id::DefId;
16 use ty::subst::{self, Substs};
17 use ty::{self, AdtDef, ToPredicate, TypeFlags, Ty, TyCtxt, TyS, TypeFoldable};
18 use util::common::ErrorReported;
20 use collections::enum_set::{self, EnumSet, CLike};
25 use syntax::ast::{self, Name};
26 use syntax::parse::token::keywords;
28 use serialize::{Decodable, Decoder, Encodable, Encoder};
32 use self::FnOutput::*;
34 use self::TypeVariants::*;
36 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
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)]
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 /// An enumerated type, defined with `enum`.
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 `TyEnum` corresponds to an enum
115 /// definition and not a concrete use of it. This is true for `TyStruct`
117 TyEnum(AdtDef<'tcx>, &'tcx Substs<'tcx>),
119 /// A structure type, defined with `struct`.
121 /// See warning about substitutions for enumerated types.
122 TyStruct(AdtDef<'tcx>, &'tcx Substs<'tcx>),
124 /// `Box<T>`; this is nominally a struct in the documentation, but is
125 /// special-cased internally. For example, it is possible to implicitly
126 /// move the contents of a box out of that box, and methods of any type
127 /// can have type `Box<Self>`.
130 /// The pointee of a string slice. Written as `str`.
133 /// An array with the given length. Written as `[T; n]`.
134 TyArray(Ty<'tcx>, usize),
136 /// The pointee of an array slice. Written as `[T]`.
139 /// A raw pointer. Written as `*mut T` or `*const T`
140 TyRawPtr(TypeAndMut<'tcx>),
142 /// A reference; a pointer with an associated lifetime. Written as
143 /// `&a mut T` or `&'a T`.
144 TyRef(&'tcx Region, TypeAndMut<'tcx>),
146 /// The anonymous type of a function declaration/definition. Each
147 /// function has a unique type.
148 TyFnDef(DefId, &'tcx Substs<'tcx>, &'tcx BareFnTy<'tcx>),
150 /// A pointer to a function. Written as `fn() -> i32`.
151 /// FIXME: This is currently also used to represent the callee of a method;
152 /// see ty::MethodCallee etc.
153 TyFnPtr(&'tcx BareFnTy<'tcx>),
155 /// A trait, defined with `trait`.
156 TyTrait(Box<TraitTy<'tcx>>),
158 /// The anonymous type of a closure. Used to represent the type of
160 TyClosure(DefId, ClosureSubsts<'tcx>),
162 /// A tuple type. For example, `(i32, bool)`.
163 TyTuple(&'tcx [Ty<'tcx>]),
165 /// The projection of an associated type. For example,
166 /// `<T as Trait<..>>::N`.
167 TyProjection(ProjectionTy<'tcx>),
169 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
172 /// A type variable used during type-checking.
175 /// A placeholder for a type which could not be computed; this is
176 /// propagated to avoid useless error messages.
180 /// A closure can be modeled as a struct that looks like:
182 /// struct Closure<'l0...'li, T0...Tj, U0...Uk> {
188 /// where 'l0...'li and T0...Tj are the lifetime and type parameters
189 /// in scope on the function that defined the closure, and U0...Uk are
190 /// type parameters representing the types of its upvars (borrowed, if
193 /// So, for example, given this function:
195 /// fn foo<'a, T>(data: &'a mut T) {
196 /// do(|| data.count += 1)
199 /// the type of the closure would be something like:
201 /// struct Closure<'a, T, U0> {
205 /// Note that the type of the upvar is not specified in the struct.
206 /// You may wonder how the impl would then be able to use the upvar,
207 /// if it doesn't know it's type? The answer is that the impl is
208 /// (conceptually) not fully generic over Closure but rather tied to
209 /// instances with the expected upvar types:
211 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
215 /// You can see that the *impl* fully specified the type of the upvar
216 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
217 /// (Here, I am assuming that `data` is mut-borrowed.)
219 /// Now, the last question you may ask is: Why include the upvar types
220 /// as extra type parameters? The reason for this design is that the
221 /// upvar types can reference lifetimes that are internal to the
222 /// creating function. In my example above, for example, the lifetime
223 /// `'b` represents the extent of the closure itself; this is some
224 /// subset of `foo`, probably just the extent of the call to the to
225 /// `do()`. If we just had the lifetime/type parameters from the
226 /// enclosing function, we couldn't name this lifetime `'b`. Note that
227 /// there can also be lifetimes in the types of the upvars themselves,
228 /// if one of them happens to be a reference to something that the
229 /// creating fn owns.
231 /// OK, you say, so why not create a more minimal set of parameters
232 /// that just includes the extra lifetime parameters? The answer is
233 /// primarily that it would be hard --- we don't know at the time when
234 /// we create the closure type what the full types of the upvars are,
235 /// nor do we know which are borrowed and which are not. In this
236 /// design, we can just supply a fresh type parameter and figure that
239 /// All right, you say, but why include the type parameters from the
240 /// original function then? The answer is that trans may need them
241 /// when monomorphizing, and they may not appear in the upvars. A
242 /// closure could capture no variables but still make use of some
243 /// in-scope type parameter with a bound (e.g., if our example above
244 /// had an extra `U: Default`, and the closure called `U::default()`).
246 /// There is another reason. This design (implicitly) prohibits
247 /// closures from capturing themselves (except via a trait
248 /// object). This simplifies closure inference considerably, since it
249 /// means that when we infer the kind of a closure or its upvars, we
250 /// don't have to handle cycles where the decisions we make for
251 /// closure C wind up influencing the decisions we ought to make for
252 /// closure C (which would then require fixed point iteration to
253 /// handle). Plus it fixes an ICE. :P
254 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
255 pub struct ClosureSubsts<'tcx> {
256 /// Lifetime and type parameters from the enclosing function.
257 /// These are separated out because trans wants to pass them around
258 /// when monomorphizing.
259 pub func_substs: &'tcx Substs<'tcx>,
261 /// The types of the upvars. The list parallels the freevars and
262 /// `upvar_borrows` lists. These are kept distinct so that we can
263 /// easily index into them.
264 pub upvar_tys: &'tcx [Ty<'tcx>]
267 impl<'tcx> Encodable for ClosureSubsts<'tcx> {
268 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
269 (self.func_substs, self.upvar_tys).encode(s)
273 impl<'tcx> Decodable for ClosureSubsts<'tcx> {
274 fn decode<D: Decoder>(d: &mut D) -> Result<ClosureSubsts<'tcx>, D::Error> {
275 let (func_substs, upvar_tys) = Decodable::decode(d)?;
276 cstore::tls::with_decoding_context(d, |dcx, _| {
278 func_substs: func_substs,
279 upvar_tys: dcx.tcx().mk_type_list(upvar_tys)
285 #[derive(Clone, PartialEq, Eq, Hash)]
286 pub struct TraitTy<'tcx> {
287 pub principal: ty::PolyTraitRef<'tcx>,
288 pub bounds: ExistentialBounds<'tcx>,
291 impl<'a, 'gcx, 'tcx> TraitTy<'tcx> {
292 pub fn principal_def_id(&self) -> DefId {
293 self.principal.0.def_id
296 /// Object types don't have a self-type specified. Therefore, when
297 /// we convert the principal trait-ref into a normal trait-ref,
298 /// you must give *some* self-type. A common choice is `mk_err()`
299 /// or some skolemized type.
300 pub fn principal_trait_ref_with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
302 -> ty::PolyTraitRef<'tcx>
304 // otherwise the escaping regions would be captured by the binder
305 assert!(!self_ty.has_escaping_regions());
307 ty::Binder(TraitRef {
308 def_id: self.principal.0.def_id,
309 substs: tcx.mk_substs(self.principal.0.substs.with_self_ty(self_ty)),
313 pub fn projection_bounds_with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
315 -> Vec<ty::PolyProjectionPredicate<'tcx>>
317 // otherwise the escaping regions would be captured by the binders
318 assert!(!self_ty.has_escaping_regions());
320 self.bounds.projection_bounds.iter()
321 .map(|in_poly_projection_predicate| {
322 let in_projection_ty = &in_poly_projection_predicate.0.projection_ty;
323 let substs = tcx.mk_substs(in_projection_ty.trait_ref.substs.with_self_ty(self_ty));
324 let trait_ref = ty::TraitRef::new(in_projection_ty.trait_ref.def_id,
326 let projection_ty = ty::ProjectionTy {
327 trait_ref: trait_ref,
328 item_name: in_projection_ty.item_name
330 ty::Binder(ty::ProjectionPredicate {
331 projection_ty: projection_ty,
332 ty: in_poly_projection_predicate.0.ty
339 /// A complete reference to a trait. These take numerous guises in syntax,
340 /// but perhaps the most recognizable form is in a where clause:
344 /// This would be represented by a trait-reference where the def-id is the
345 /// def-id for the trait `Foo` and the substs defines `T` as parameter 0 in the
346 /// `SelfSpace` and `U` as parameter 0 in the `TypeSpace`.
348 /// Trait references also appear in object types like `Foo<U>`, but in
349 /// that case the `Self` parameter is absent from the substitutions.
351 /// Note that a `TraitRef` introduces a level of region binding, to
352 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
353 /// U>` or higher-ranked object types.
354 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
355 pub struct TraitRef<'tcx> {
357 pub substs: &'tcx Substs<'tcx>,
360 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
362 impl<'tcx> PolyTraitRef<'tcx> {
363 pub fn self_ty(&self) -> Ty<'tcx> {
367 pub fn def_id(&self) -> DefId {
371 pub fn substs(&self) -> &'tcx Substs<'tcx> {
372 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
376 pub fn input_types(&self) -> &[Ty<'tcx>] {
377 // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
381 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
382 // Note that we preserve binding levels
383 Binder(ty::TraitPredicate { trait_ref: self.0.clone() })
387 /// Binder is a binder for higher-ranked lifetimes. It is part of the
388 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
389 /// (which would be represented by the type `PolyTraitRef ==
390 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
391 /// erase, or otherwise "discharge" these bound regions, we change the
392 /// type from `Binder<T>` to just `T` (see
393 /// e.g. `liberate_late_bound_regions`).
394 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
395 pub struct Binder<T>(pub T);
398 /// Skips the binder and returns the "bound" value. This is a
399 /// risky thing to do because it's easy to get confused about
400 /// debruijn indices and the like. It is usually better to
401 /// discharge the binder using `no_late_bound_regions` or
402 /// `replace_late_bound_regions` or something like
403 /// that. `skip_binder` is only valid when you are either
404 /// extracting data that has nothing to do with bound regions, you
405 /// are doing some sort of test that does not involve bound
406 /// regions, or you are being very careful about your depth
409 /// Some examples where `skip_binder` is reasonable:
410 /// - extracting the def-id from a PolyTraitRef;
411 /// - comparing the self type of a PolyTraitRef to see if it is equal to
412 /// a type parameter `X`, since the type `X` does not reference any regions
413 pub fn skip_binder(&self) -> &T {
417 pub fn as_ref(&self) -> Binder<&T> {
421 pub fn map_bound_ref<F,U>(&self, f: F) -> Binder<U>
422 where F: FnOnce(&T) -> U
424 self.as_ref().map_bound(f)
427 pub fn map_bound<F,U>(self, f: F) -> Binder<U>
428 where F: FnOnce(T) -> U
430 ty::Binder(f(self.0))
434 impl fmt::Debug for TypeFlags {
435 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
436 write!(f, "{}", self.bits)
440 /// Represents the projection of an associated type. In explicit UFCS
441 /// form this would be written `<T as Trait<..>>::N`.
442 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
443 pub struct ProjectionTy<'tcx> {
444 /// The trait reference `T as Trait<..>`.
445 pub trait_ref: ty::TraitRef<'tcx>,
447 /// The name `N` of the associated type.
451 impl<'tcx> ProjectionTy<'tcx> {
452 pub fn sort_key(&self) -> (DefId, Name) {
453 (self.trait_ref.def_id, self.item_name)
457 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
458 pub struct BareFnTy<'tcx> {
459 pub unsafety: hir::Unsafety,
461 pub sig: PolyFnSig<'tcx>,
464 #[derive(Clone, PartialEq, Eq, Hash)]
465 pub struct ClosureTy<'tcx> {
466 pub unsafety: hir::Unsafety,
468 pub sig: PolyFnSig<'tcx>,
471 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
472 pub enum FnOutput<'tcx> {
473 FnConverging(Ty<'tcx>),
477 impl<'tcx> FnOutput<'tcx> {
478 pub fn diverges(&self) -> bool {
482 pub fn unwrap(self) -> Ty<'tcx> {
484 ty::FnConverging(t) => t,
485 ty::FnDiverging => bug!()
489 pub fn unwrap_or(self, def: Ty<'tcx>) -> Ty<'tcx> {
491 ty::FnConverging(t) => t,
492 ty::FnDiverging => def
496 pub fn maybe_converging(self) -> Option<Ty<'tcx>> {
498 ty::FnConverging(t) => Some(t),
499 ty::FnDiverging => None
504 pub type PolyFnOutput<'tcx> = Binder<FnOutput<'tcx>>;
506 impl<'tcx> PolyFnOutput<'tcx> {
507 pub fn diverges(&self) -> bool {
512 /// Signature of a function type, which I have arbitrarily
513 /// decided to use to refer to the input/output types.
515 /// - `inputs` is the list of arguments and their modes.
516 /// - `output` is the return type.
517 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
518 #[derive(Clone, PartialEq, Eq, Hash)]
519 pub struct FnSig<'tcx> {
520 pub inputs: Vec<Ty<'tcx>>,
521 pub output: FnOutput<'tcx>,
525 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
527 impl<'tcx> PolyFnSig<'tcx> {
528 pub fn inputs(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
529 self.map_bound_ref(|fn_sig| fn_sig.inputs.clone())
531 pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
532 self.map_bound_ref(|fn_sig| fn_sig.inputs[index])
534 pub fn output(&self) -> ty::Binder<FnOutput<'tcx>> {
535 self.map_bound_ref(|fn_sig| fn_sig.output.clone())
537 pub fn variadic(&self) -> bool {
538 self.skip_binder().variadic
542 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
544 pub space: subst::ParamSpace,
549 impl<'a, 'gcx, 'tcx> ParamTy {
550 pub fn new(space: subst::ParamSpace,
554 ParamTy { space: space, idx: index, name: name }
557 pub fn for_self() -> ParamTy {
558 ParamTy::new(subst::SelfSpace, 0, keywords::SelfType.name())
561 pub fn for_def(def: &ty::TypeParameterDef) -> ParamTy {
562 ParamTy::new(def.space, def.index, def.name)
565 pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
566 tcx.mk_param(self.space, self.idx, self.name)
569 pub fn is_self(&self) -> bool {
570 self.space == subst::SelfSpace && self.idx == 0
574 /// A [De Bruijn index][dbi] is a standard means of representing
575 /// regions (and perhaps later types) in a higher-ranked setting. In
576 /// particular, imagine a type like this:
578 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
581 /// | +------------+ 1 | |
583 /// +--------------------------------+ 2 |
585 /// +------------------------------------------+ 1
587 /// In this type, there are two binders (the outer fn and the inner
588 /// fn). We need to be able to determine, for any given region, which
589 /// fn type it is bound by, the inner or the outer one. There are
590 /// various ways you can do this, but a De Bruijn index is one of the
591 /// more convenient and has some nice properties. The basic idea is to
592 /// count the number of binders, inside out. Some examples should help
593 /// clarify what I mean.
595 /// Let's start with the reference type `&'b isize` that is the first
596 /// argument to the inner function. This region `'b` is assigned a De
597 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
598 /// fn). The region `'a` that appears in the second argument type (`&'a
599 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
600 /// second-innermost binder". (These indices are written on the arrays
603 /// What is interesting is that De Bruijn index attached to a particular
604 /// variable will vary depending on where it appears. For example,
605 /// the final type `&'a char` also refers to the region `'a` declared on
606 /// the outermost fn. But this time, this reference is not nested within
607 /// any other binders (i.e., it is not an argument to the inner fn, but
608 /// rather the outer one). Therefore, in this case, it is assigned a
609 /// De Bruijn index of 1, because the innermost binder in that location
612 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
613 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)]
614 pub struct DebruijnIndex {
615 // We maintain the invariant that this is never 0. So 1 indicates
616 // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
620 /// Representation of regions.
622 /// Unlike types, most region variants are "fictitious", not concrete,
623 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
624 /// ones representing concrete regions.
628 /// These are regions that are stored behind a binder and must be substituted
629 /// with some concrete region before being used. There are 2 kind of
630 /// bound regions: early-bound, which are bound in a TypeScheme/TraitDef,
631 /// and are substituted by a Substs, and late-bound, which are part of
632 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
633 /// the likes of `liberate_late_bound_regions`. The distinction exists
634 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
636 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
637 /// outside their binder, e.g. in types passed to type inference, and
638 /// should first be substituted (by skolemized regions, free regions,
639 /// or region variables).
641 /// ## Skolemized and Free Regions
643 /// One often wants to work with bound regions without knowing their precise
644 /// identity. For example, when checking a function, the lifetime of a borrow
645 /// can end up being assigned to some region parameter. In these cases,
646 /// it must be ensured that bounds on the region can't be accidentally
647 /// assumed without being checked.
649 /// The process of doing that is called "skolemization". The bound regions
650 /// are replaced by skolemized markers, which don't satisfy any relation
651 /// not explicity provided.
653 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
654 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
655 /// to be used. These also support explicit bounds: both the internally-stored
656 /// *scope*, which the region is assumed to outlive, as well as other
657 /// relations stored in the `FreeRegionMap`. Note that these relations
658 /// aren't checked when you `make_subregion` (or `eq_types`), only by
659 /// `resolve_regions_and_report_errors`.
661 /// When working with higher-ranked types, some region relations aren't
662 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
663 /// `ReSkolemized` is designed for this purpose. In these contexts,
664 /// there's also the risk that some inference variable laying around will
665 /// get unified with your skolemized region: if you want to check whether
666 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
667 /// with a skolemized region `'%a`, the variable `'_` would just be
668 /// instantiated to the skolemized region `'%a`, which is wrong because
669 /// the inference variable is supposed to satisfy the relation
670 /// *for every value of the skolemized region*. To ensure that doesn't
671 /// happen, you can use `leak_check`. This is more clearly explained
672 /// by infer/higher_ranked/README.md.
674 /// [1] http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
675 /// [2] http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
676 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable)]
678 // Region bound in a type or fn declaration which will be
679 // substituted 'early' -- that is, at the same time when type
680 // parameters are substituted.
681 ReEarlyBound(EarlyBoundRegion),
683 // Region bound in a function scope, which will be substituted when the
684 // function is called.
685 ReLateBound(DebruijnIndex, BoundRegion),
687 /// When checking a function body, the types of all arguments and so forth
688 /// that refer to bound region parameters are modified to refer to free
689 /// region parameters.
692 /// A concrete region naming some statically determined extent
693 /// (e.g. an expression or sequence of statements) within the
694 /// current function.
695 ReScope(region::CodeExtent),
697 /// Static data that has an "infinite" lifetime. Top in the region lattice.
700 /// A region variable. Should not exist after typeck.
703 /// A skolemized region - basically the higher-ranked version of ReFree.
704 /// Should not exist after typeck.
705 ReSkolemized(SkolemizedRegionVid, BoundRegion),
707 /// Empty lifetime is for data that is never accessed.
708 /// Bottom in the region lattice. We treat ReEmpty somewhat
709 /// specially; at least right now, we do not generate instances of
710 /// it during the GLB computations, but rather
711 /// generate an error instead. This is to improve error messages.
712 /// The only way to get an instance of ReEmpty is to have a region
713 /// variable with no constraints.
716 /// Erased region, used by trait selection, in MIR and during trans.
720 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
721 pub struct EarlyBoundRegion {
722 pub space: subst::ParamSpace,
727 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
732 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
737 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
738 pub struct FloatVid {
742 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
743 pub struct RegionVid {
747 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
748 pub struct SkolemizedRegionVid {
752 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
758 /// A `FreshTy` is one that is generated as a replacement for an
759 /// unbound type variable. This is convenient for caching etc. See
760 /// `infer::freshen` for more details.
766 /// Bounds suitable for an existentially quantified type parameter
767 /// such as those that appear in object types or closure types.
768 #[derive(PartialEq, Eq, Hash, Clone)]
769 pub struct ExistentialBounds<'tcx> {
770 pub region_bound: ty::Region,
771 pub builtin_bounds: BuiltinBounds,
772 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
775 impl<'tcx> ExistentialBounds<'tcx> {
776 pub fn new(region_bound: ty::Region,
777 builtin_bounds: BuiltinBounds,
778 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>)
780 let mut projection_bounds = projection_bounds;
781 projection_bounds.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()));
783 region_bound: region_bound,
784 builtin_bounds: builtin_bounds,
785 projection_bounds: projection_bounds
790 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
791 pub struct BuiltinBounds(EnumSet<BuiltinBound>);
793 impl<'a, 'gcx, 'tcx> BuiltinBounds {
794 pub fn empty() -> BuiltinBounds {
795 BuiltinBounds(EnumSet::new())
798 pub fn iter(&self) -> enum_set::Iter<BuiltinBound> {
802 pub fn to_predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
804 -> Vec<ty::Predicate<'tcx>> {
805 self.iter().filter_map(|builtin_bound|
806 match tcx.trait_ref_for_builtin_bound(builtin_bound, self_ty) {
807 Ok(trait_ref) => Some(trait_ref.to_predicate()),
808 Err(ErrorReported) => { None }
814 impl ops::Deref for BuiltinBounds {
815 type Target = EnumSet<BuiltinBound>;
816 fn deref(&self) -> &Self::Target { &self.0 }
819 impl ops::DerefMut for BuiltinBounds {
820 fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
823 impl<'a> IntoIterator for &'a BuiltinBounds {
824 type Item = BuiltinBound;
825 type IntoIter = enum_set::Iter<BuiltinBound>;
826 fn into_iter(self) -> Self::IntoIter {
831 #[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
834 pub enum BuiltinBound {
841 impl CLike for BuiltinBound {
842 fn to_usize(&self) -> usize {
845 fn from_usize(v: usize) -> BuiltinBound {
846 unsafe { mem::transmute(v) }
850 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
851 pub fn try_add_builtin_trait(self,
853 builtin_bounds: &mut EnumSet<BuiltinBound>)
856 //! Checks whether `trait_ref` refers to one of the builtin
857 //! traits, like `Send`, and adds the corresponding
858 //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
859 //! is a builtin trait.
861 match self.lang_items.to_builtin_kind(trait_def_id) {
862 Some(bound) => { builtin_bounds.insert(bound); true }
869 pub fn new(depth: u32) -> DebruijnIndex {
871 DebruijnIndex { depth: depth }
874 pub fn shifted(&self, amount: u32) -> DebruijnIndex {
875 DebruijnIndex { depth: self.depth + amount }
881 pub fn is_bound(&self) -> bool {
883 ty::ReEarlyBound(..) => true,
884 ty::ReLateBound(..) => true,
889 pub fn needs_infer(&self) -> bool {
891 ty::ReVar(..) | ty::ReSkolemized(..) => true,
896 pub fn escapes_depth(&self, depth: u32) -> bool {
898 ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
903 /// Returns the depth of `self` from the (1-based) binding level `depth`
904 pub fn from_depth(&self, depth: u32) -> Region {
906 ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
907 depth: debruijn.depth - (depth - 1)
915 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
916 pub fn as_opt_param_ty(&self) -> Option<ty::ParamTy> {
918 ty::TyParam(ref d) => Some(d.clone()),
923 pub fn is_nil(&self) -> bool {
925 TyTuple(ref tys) => tys.is_empty(),
930 pub fn is_empty(&self, _cx: TyCtxt) -> bool {
931 // FIXME(#24885): be smarter here
933 TyEnum(def, _) | TyStruct(def, _) => def.is_empty(),
938 pub fn is_primitive(&self) -> bool {
940 TyBool | TyChar | TyInt(_) | TyUint(_) | TyFloat(_) => true,
945 pub fn is_ty_var(&self) -> bool {
947 TyInfer(TyVar(_)) => true,
952 pub fn is_phantom_data(&self) -> bool {
953 if let TyStruct(def, _) = self.sty {
954 def.is_phantom_data()
960 pub fn is_bool(&self) -> bool { self.sty == TyBool }
962 pub fn is_param(&self, space: subst::ParamSpace, index: u32) -> bool {
964 ty::TyParam(ref data) => data.space == space && data.idx == index,
969 pub fn is_self(&self) -> bool {
971 TyParam(ref p) => p.space == subst::SelfSpace,
976 pub fn is_slice(&self) -> bool {
978 TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
979 TySlice(_) | TyStr => true,
986 pub fn is_structural(&self) -> bool {
988 TyStruct(..) | TyTuple(_) | TyEnum(..) |
989 TyArray(..) | TyClosure(..) => true,
990 _ => self.is_slice() | self.is_trait()
995 pub fn is_simd(&self) -> bool {
997 TyStruct(def, _) => def.is_simd(),
1002 pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1004 TyArray(ty, _) | TySlice(ty) => ty,
1005 TyStr => tcx.mk_mach_uint(ast::UintTy::U8),
1006 _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1010 pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1012 TyStruct(def, substs) => {
1013 def.struct_variant().fields[0].ty(tcx, substs)
1015 _ => bug!("simd_type called on invalid type")
1019 pub fn simd_size(&self, _cx: TyCtxt) -> usize {
1021 TyStruct(def, _) => def.struct_variant().fields.len(),
1022 _ => bug!("simd_size called on invalid type")
1026 pub fn is_region_ptr(&self) -> bool {
1033 pub fn is_unsafe_ptr(&self) -> bool {
1035 TyRawPtr(_) => return true,
1040 pub fn is_unique(&self) -> bool {
1048 A scalar type is one that denotes an atomic datum, with no sub-components.
1049 (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1050 contents are abstract to rustc.)
1052 pub fn is_scalar(&self) -> bool {
1054 TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
1055 TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
1056 TyFnDef(..) | TyFnPtr(_) | TyRawPtr(_) => true,
1061 /// Returns true if this type is a floating point type and false otherwise.
1062 pub fn is_floating_point(&self) -> bool {
1065 TyInfer(FloatVar(_)) => true,
1070 pub fn is_trait(&self) -> bool {
1072 TyTrait(..) => true,
1077 pub fn is_integral(&self) -> bool {
1079 TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
1084 pub fn is_fresh(&self) -> bool {
1086 TyInfer(FreshTy(_)) => true,
1087 TyInfer(FreshIntTy(_)) => true,
1088 TyInfer(FreshFloatTy(_)) => true,
1093 pub fn is_uint(&self) -> bool {
1095 TyInfer(IntVar(_)) | TyUint(ast::UintTy::Us) => true,
1100 pub fn is_char(&self) -> bool {
1107 pub fn is_fp(&self) -> bool {
1109 TyInfer(FloatVar(_)) | TyFloat(_) => true,
1114 pub fn is_numeric(&self) -> bool {
1115 self.is_integral() || self.is_fp()
1118 pub fn is_signed(&self) -> bool {
1125 pub fn is_machine(&self) -> bool {
1127 TyInt(ast::IntTy::Is) | TyUint(ast::UintTy::Us) => false,
1128 TyInt(..) | TyUint(..) | TyFloat(..) => true,
1133 pub fn has_concrete_skeleton(&self) -> bool {
1135 TyParam(_) | TyInfer(_) | TyError => false,
1140 // Returns the type and mutability of *ty.
1142 // The parameter `explicit` indicates if this is an *explicit* dereference.
1143 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1144 pub fn builtin_deref(&self, explicit: bool, pref: ty::LvaluePreference)
1145 -> Option<TypeAndMut<'tcx>>
1151 mutbl: if pref == ty::PreferMutLvalue {
1158 TyRef(_, mt) => Some(mt),
1159 TyRawPtr(mt) if explicit => Some(mt),
1164 // Returns the type of ty[i]
1165 pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1167 TyArray(ty, _) | TySlice(ty) => Some(ty),
1172 pub fn fn_sig(&self) -> &'tcx PolyFnSig<'tcx> {
1174 TyFnDef(_, _, ref f) | TyFnPtr(ref f) => &f.sig,
1175 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1179 /// Returns the ABI of the given function.
1180 pub fn fn_abi(&self) -> abi::Abi {
1182 TyFnDef(_, _, ref f) | TyFnPtr(ref f) => f.abi,
1183 _ => bug!("Ty::fn_abi() called on non-fn type"),
1187 // Type accessors for substructures of types
1188 pub fn fn_args(&self) -> ty::Binder<Vec<Ty<'tcx>>> {
1189 self.fn_sig().inputs()
1192 pub fn fn_ret(&self) -> Binder<FnOutput<'tcx>> {
1193 self.fn_sig().output()
1196 pub fn is_fn(&self) -> bool {
1198 TyFnDef(..) | TyFnPtr(_) => true,
1203 pub fn ty_to_def_id(&self) -> Option<DefId> {
1205 TyTrait(ref tt) => Some(tt.principal_def_id()),
1207 TyEnum(def, _) => Some(def.did),
1208 TyClosure(id, _) => Some(id),
1213 pub fn ty_adt_def(&self) -> Option<AdtDef<'tcx>> {
1215 TyStruct(adt, _) | TyEnum(adt, _) => Some(adt),
1220 /// Returns the regions directly referenced from this type (but
1221 /// not types reachable from this type via `walk_tys`). This
1222 /// ignores late-bound regions binders.
1223 pub fn regions(&self) -> Vec<ty::Region> {
1225 TyRef(region, _) => {
1228 TyTrait(ref obj) => {
1229 let mut v = vec![obj.bounds.region_bound];
1230 v.extend_from_slice(obj.principal.skip_binder()
1231 .substs.regions.as_slice());
1235 TyStruct(_, substs) => {
1236 substs.regions.as_slice().to_vec()
1238 TyClosure(_, ref substs) => {
1239 substs.func_substs.regions.as_slice().to_vec()
1241 TyProjection(ref data) => {
1242 data.trait_ref.substs.regions.as_slice().to_vec()