]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/sty.rs
bb5c7b5fd2a5e0eddf38a9a041837c7415450109
[rust.git] / src / librustc / ty / sty.rs
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.
4 //
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.
10
11 //! This module contains TypeVariants and its major components
12
13 use hir::def_id::DefId;
14
15 use middle::const_val::ConstVal;
16 use middle::region;
17 use rustc_data_structures::indexed_vec::Idx;
18 use ty::subst::{Substs, Subst, Kind, UnpackedKind};
19 use ty::{self, AdtDef, TypeFlags, Ty, TyCtxt, TypeFoldable};
20 use ty::{Slice, TyS};
21
22 use std::iter;
23 use std::cmp::Ordering;
24 use syntax::abi;
25 use syntax::ast::{self, Name};
26 use syntax::symbol::keywords;
27
28 use serialize;
29
30 use hir;
31
32 use self::InferTy::*;
33 use self::TypeVariants::*;
34
35 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
36 pub struct TypeAndMut<'tcx> {
37     pub ty: Ty<'tcx>,
38     pub mutbl: hir::Mutability,
39 }
40
41 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
42          RustcEncodable, RustcDecodable, Copy)]
43 /// A "free" region `fr` can be interpreted as "some region
44 /// at least as big as the scope `fr.scope`".
45 pub struct FreeRegion {
46     pub scope: DefId,
47     pub bound_region: BoundRegion,
48 }
49
50 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
51          RustcEncodable, RustcDecodable, Copy)]
52 pub enum BoundRegion {
53     /// An anonymous region parameter for a given fn (&T)
54     BrAnon(u32),
55
56     /// Named region parameters for functions (a in &'a T)
57     ///
58     /// The def-id is needed to distinguish free regions in
59     /// the event of shadowing.
60     BrNamed(DefId, Name),
61
62     /// Fresh bound identifiers created during GLB computations.
63     BrFresh(u32),
64
65     /// Anonymous region for the implicit env pointer parameter
66     /// to a closure
67     BrEnv,
68 }
69
70 impl BoundRegion {
71     pub fn is_named(&self) -> bool {
72         match *self {
73             BoundRegion::BrNamed(..) => true,
74             _ => false,
75         }
76     }
77 }
78
79 /// NB: If you change this, you'll probably want to change the corresponding
80 /// AST structure in libsyntax/ast.rs as well.
81 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
82 pub enum TypeVariants<'tcx> {
83     /// The primitive boolean type. Written as `bool`.
84     TyBool,
85
86     /// The primitive character type; holds a Unicode scalar value
87     /// (a non-surrogate code point).  Written as `char`.
88     TyChar,
89
90     /// A primitive signed integer type. For example, `i32`.
91     TyInt(ast::IntTy),
92
93     /// A primitive unsigned integer type. For example, `u32`.
94     TyUint(ast::UintTy),
95
96     /// A primitive floating-point type. For example, `f64`.
97     TyFloat(ast::FloatTy),
98
99     /// Structures, enumerations and unions.
100     ///
101     /// Substs here, possibly against intuition, *may* contain `TyParam`s.
102     /// That is, even after substitution it is possible that there are type
103     /// variables. This happens when the `TyAdt` corresponds to an ADT
104     /// definition and not a concrete use of it.
105     TyAdt(&'tcx AdtDef, &'tcx Substs<'tcx>),
106
107     TyForeign(DefId),
108
109     /// The pointee of a string slice. Written as `str`.
110     TyStr,
111
112     /// An array with the given length. Written as `[T; n]`.
113     TyArray(Ty<'tcx>, &'tcx ty::Const<'tcx>),
114
115     /// The pointee of an array slice.  Written as `[T]`.
116     TySlice(Ty<'tcx>),
117
118     /// A raw pointer. Written as `*mut T` or `*const T`
119     TyRawPtr(TypeAndMut<'tcx>),
120
121     /// A reference; a pointer with an associated lifetime. Written as
122     /// `&'a mut T` or `&'a T`.
123     TyRef(Region<'tcx>, TypeAndMut<'tcx>),
124
125     /// The anonymous type of a function declaration/definition. Each
126     /// function has a unique type.
127     TyFnDef(DefId, &'tcx Substs<'tcx>),
128
129     /// A pointer to a function.  Written as `fn() -> i32`.
130     TyFnPtr(PolyFnSig<'tcx>),
131
132     /// A trait, defined with `trait`.
133     TyDynamic(Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
134
135     /// The anonymous type of a closure. Used to represent the type of
136     /// `|a| a`.
137     TyClosure(DefId, ClosureSubsts<'tcx>),
138
139     /// The anonymous type of a generator. Used to represent the type of
140     /// `|a| yield a`.
141     TyGenerator(DefId, ClosureSubsts<'tcx>, GeneratorInterior<'tcx>),
142
143     /// A type representin the types stored inside a generator.
144     /// This should only appear in GeneratorInteriors.
145     TyGeneratorWitness(Binder<&'tcx Slice<Ty<'tcx>>>),
146
147     /// The never type `!`
148     TyNever,
149
150     /// A tuple type.  For example, `(i32, bool)`.
151     TyTuple(&'tcx Slice<Ty<'tcx>>),
152
153     /// The projection of an associated type.  For example,
154     /// `<T as Trait<..>>::N`.
155     TyProjection(ProjectionTy<'tcx>),
156
157     /// Anonymized (`impl Trait`) type found in a return type.
158     /// The DefId comes from the `impl Trait` ast::Ty node, and the
159     /// substitutions are for the generics of the function in question.
160     /// After typeck, the concrete type can be found in the `types` map.
161     TyAnon(DefId, &'tcx Substs<'tcx>),
162
163     /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
164     TyParam(ParamTy),
165
166     /// A type variable used during type-checking.
167     TyInfer(InferTy),
168
169     /// A placeholder for a type which could not be computed; this is
170     /// propagated to avoid useless error messages.
171     TyError,
172 }
173
174 /// A closure can be modeled as a struct that looks like:
175 ///
176 ///     struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
177 ///         upvar0: U0,
178 ///         ...
179 ///         upvark: Uk
180 ///     }
181 ///
182 /// where:
183 ///
184 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
185 ///   in scope on the function that defined the closure,
186 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
187 ///   is rather hackily encoded via a scalar type. See
188 ///   `TyS::to_opt_closure_kind` for details.
189 /// - CS represents the *closure signature*, representing as a `fn()`
190 ///   type. For example, `fn(u32, u32) -> u32` would mean that the closure
191 ///   implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
192 ///   specified above.
193 /// - U0...Uk are type parameters representing the types of its upvars
194 ///   (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
195 ///    and the up-var has the type `Foo`, then `Ui = &Foo`).
196 ///
197 /// So, for example, given this function:
198 ///
199 ///     fn foo<'a, T>(data: &'a mut T) {
200 ///          do(|| data.count += 1)
201 ///     }
202 ///
203 /// the type of the closure would be something like:
204 ///
205 ///     struct Closure<'a, T, U0> {
206 ///         data: U0
207 ///     }
208 ///
209 /// Note that the type of the upvar is not specified in the struct.
210 /// You may wonder how the impl would then be able to use the upvar,
211 /// if it doesn't know it's type? The answer is that the impl is
212 /// (conceptually) not fully generic over Closure but rather tied to
213 /// instances with the expected upvar types:
214 ///
215 ///     impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
216 ///         ...
217 ///     }
218 ///
219 /// You can see that the *impl* fully specified the type of the upvar
220 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
221 /// (Here, I am assuming that `data` is mut-borrowed.)
222 ///
223 /// Now, the last question you may ask is: Why include the upvar types
224 /// as extra type parameters? The reason for this design is that the
225 /// upvar types can reference lifetimes that are internal to the
226 /// creating function. In my example above, for example, the lifetime
227 /// `'b` represents the scope of the closure itself; this is some
228 /// subset of `foo`, probably just the scope of the call to the to
229 /// `do()`. If we just had the lifetime/type parameters from the
230 /// enclosing function, we couldn't name this lifetime `'b`. Note that
231 /// there can also be lifetimes in the types of the upvars themselves,
232 /// if one of them happens to be a reference to something that the
233 /// creating fn owns.
234 ///
235 /// OK, you say, so why not create a more minimal set of parameters
236 /// that just includes the extra lifetime parameters? The answer is
237 /// primarily that it would be hard --- we don't know at the time when
238 /// we create the closure type what the full types of the upvars are,
239 /// nor do we know which are borrowed and which are not. In this
240 /// design, we can just supply a fresh type parameter and figure that
241 /// out later.
242 ///
243 /// All right, you say, but why include the type parameters from the
244 /// original function then? The answer is that trans may need them
245 /// when monomorphizing, and they may not appear in the upvars.  A
246 /// closure could capture no variables but still make use of some
247 /// in-scope type parameter with a bound (e.g., if our example above
248 /// had an extra `U: Default`, and the closure called `U::default()`).
249 ///
250 /// There is another reason. This design (implicitly) prohibits
251 /// closures from capturing themselves (except via a trait
252 /// object). This simplifies closure inference considerably, since it
253 /// means that when we infer the kind of a closure or its upvars, we
254 /// don't have to handle cycles where the decisions we make for
255 /// closure C wind up influencing the decisions we ought to make for
256 /// closure C (which would then require fixed point iteration to
257 /// handle). Plus it fixes an ICE. :P
258 ///
259 /// ## Generators
260 ///
261 /// Perhaps surprisingly, `ClosureSubsts` are also used for
262 /// generators.  In that case, what is written above is only half-true
263 /// -- the set of type parameters is similar, but the role of CK and
264 /// CS are different.  CK represents the "yield type" and CS
265 /// represents the "return type" of the generator.
266 ///
267 /// It'd be nice to split this struct into ClosureSubsts and
268 /// GeneratorSubsts, I believe. -nmatsakis
269 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
270 pub struct ClosureSubsts<'tcx> {
271     /// Lifetime and type parameters from the enclosing function,
272     /// concatenated with the types of the upvars.
273     ///
274     /// These are separated out because trans wants to pass them around
275     /// when monomorphizing.
276     pub substs: &'tcx Substs<'tcx>,
277 }
278
279 /// Struct returned by `split()`. Note that these are subslices of the
280 /// parent slice and not canonical substs themselves.
281 struct SplitClosureSubsts<'tcx> {
282     closure_kind_ty: Ty<'tcx>,
283     closure_sig_ty: Ty<'tcx>,
284     upvar_kinds: &'tcx [Kind<'tcx>],
285 }
286
287 impl<'tcx> ClosureSubsts<'tcx> {
288     /// Divides the closure substs into their respective
289     /// components. Single source of truth with respect to the
290     /// ordering.
291     fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitClosureSubsts<'tcx> {
292         let generics = tcx.generics_of(def_id);
293         let parent_len = generics.parent_count();
294         SplitClosureSubsts {
295             closure_kind_ty: self.substs.type_at(parent_len),
296             closure_sig_ty: self.substs.type_at(parent_len + 1),
297             upvar_kinds: &self.substs[parent_len + 2..],
298         }
299     }
300
301     #[inline]
302     pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
303         impl Iterator<Item=Ty<'tcx>> + 'tcx
304     {
305         let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
306         upvar_kinds.iter().map(|t| {
307             if let UnpackedKind::Type(ty) = t.unpack() {
308                 ty
309             } else {
310                 bug!("upvar should be type")
311             }
312         })
313     }
314
315     /// Returns the closure kind for this closure; may return a type
316     /// variable during inference. To get the closure kind during
317     /// inference, use `infcx.closure_kind(def_id, substs)`.
318     pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
319         self.split(def_id, tcx).closure_kind_ty
320     }
321
322     /// Returns the type representing the closure signature for this
323     /// closure; may contain type variables during inference. To get
324     /// the closure signature during inference, use
325     /// `infcx.fn_sig(def_id)`.
326     pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
327         self.split(def_id, tcx).closure_sig_ty
328     }
329
330     /// Returns the type representing the yield type of the generator.
331     pub fn generator_yield_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
332         self.closure_kind_ty(def_id, tcx)
333     }
334
335     /// Returns the type representing the return type of the generator.
336     pub fn generator_return_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
337         self.closure_sig_ty(def_id, tcx)
338     }
339
340     /// Return the "generator signature", which consists of its yield
341     /// and return types.
342     ///
343     /// NB. Some bits of the code prefers to see this wrapped in a
344     /// binder, but it never contains bound regions. Probably this
345     /// function should be removed.
346     pub fn generator_poly_sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> PolyGenSig<'tcx> {
347         ty::Binder(self.generator_sig(def_id, tcx))
348     }
349
350     /// Return the "generator signature", which consists of its yield
351     /// and return types.
352     pub fn generator_sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> GenSig<'tcx> {
353         ty::GenSig {
354             yield_ty: self.generator_yield_ty(def_id, tcx),
355             return_ty: self.generator_return_ty(def_id, tcx),
356         }
357     }
358 }
359
360 impl<'tcx> ClosureSubsts<'tcx> {
361     /// Returns the closure kind for this closure; only usable outside
362     /// of an inference context, because in that context we know that
363     /// there are no type variables.
364     ///
365     /// If you have an inference context, use `infcx.closure_kind()`.
366     pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::ClosureKind {
367         self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
368     }
369
370     /// Extracts the signature from the closure; only usable outside
371     /// of an inference context, because in that context we know that
372     /// there are no type variables.
373     ///
374     /// If you have an inference context, use `infcx.closure_sig()`.
375     pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
376         match self.closure_sig_ty(def_id, tcx).sty {
377             ty::TyFnPtr(sig) => sig,
378             ref t => bug!("closure_sig_ty is not a fn-ptr: {:?}", t),
379         }
380     }
381 }
382
383 impl<'a, 'gcx, 'tcx> ClosureSubsts<'tcx> {
384     /// This returns the types of the MIR locals which had to be stored across suspension points.
385     /// It is calculated in rustc_mir::transform::generator::StateTransform.
386     /// All the types here must be in the tuple in GeneratorInterior.
387     pub fn state_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
388         impl Iterator<Item=Ty<'tcx>> + 'a
389     {
390         let state = tcx.generator_layout(def_id).fields.iter();
391         state.map(move |d| d.ty.subst(tcx, self.substs))
392     }
393
394     /// This is the types of the fields of a generate which
395     /// is available before the generator transformation.
396     /// It includes the upvars and the state discriminant which is u32.
397     pub fn pre_transforms_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
398         impl Iterator<Item=Ty<'tcx>> + 'a
399     {
400         self.upvar_tys(def_id, tcx).chain(iter::once(tcx.types.u32))
401     }
402
403     /// This is the types of all the fields stored in a generator.
404     /// It includes the upvars, state types and the state discriminant which is u32.
405     pub fn field_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
406         impl Iterator<Item=Ty<'tcx>> + 'a
407     {
408         self.pre_transforms_tys(def_id, tcx).chain(self.state_tys(def_id, tcx))
409     }
410 }
411
412 /// This describes the types that can be contained in a generator.
413 /// It will be a type variable initially and unified in the last stages of typeck of a body.
414 /// It contains a tuple of all the types that could end up on a generator frame.
415 /// The state transformation MIR pass may only produce layouts which mention types in this tuple.
416 /// Upvars are not counted here.
417 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
418 pub struct GeneratorInterior<'tcx> {
419     pub witness: Ty<'tcx>,
420     pub movable: bool,
421 }
422
423 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
424 pub enum ExistentialPredicate<'tcx> {
425     /// e.g. Iterator
426     Trait(ExistentialTraitRef<'tcx>),
427     /// e.g. Iterator::Item = T
428     Projection(ExistentialProjection<'tcx>),
429     /// e.g. Send
430     AutoTrait(DefId),
431 }
432
433 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
434     pub fn cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
435         use self::ExistentialPredicate::*;
436         match (*self, *other) {
437             (Trait(_), Trait(_)) => Ordering::Equal,
438             (Projection(ref a), Projection(ref b)) =>
439                 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
440             (AutoTrait(ref a), AutoTrait(ref b)) =>
441                 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
442             (Trait(_), _) => Ordering::Less,
443             (Projection(_), Trait(_)) => Ordering::Greater,
444             (Projection(_), _) => Ordering::Less,
445             (AutoTrait(_), _) => Ordering::Greater,
446         }
447     }
448
449 }
450
451 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
452     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
453         -> ty::Predicate<'tcx> {
454         use ty::ToPredicate;
455         match *self.skip_binder() {
456             ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
457             ExistentialPredicate::Projection(p) =>
458                 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
459             ExistentialPredicate::AutoTrait(did) => {
460                 let trait_ref = Binder(ty::TraitRef {
461                     def_id: did,
462                     substs: tcx.mk_substs_trait(self_ty, &[]),
463                 });
464                 trait_ref.to_predicate()
465             }
466         }
467     }
468 }
469
470 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<ExistentialPredicate<'tcx>> {}
471
472 impl<'tcx> Slice<ExistentialPredicate<'tcx>> {
473     pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
474         match self.get(0) {
475             Some(&ExistentialPredicate::Trait(tr)) => Some(tr),
476             _ => None,
477         }
478     }
479
480     #[inline]
481     pub fn projection_bounds<'a>(&'a self) ->
482         impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
483         self.iter().filter_map(|predicate| {
484             match *predicate {
485                 ExistentialPredicate::Projection(p) => Some(p),
486                 _ => None,
487             }
488         })
489     }
490
491     #[inline]
492     pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
493         self.iter().filter_map(|predicate| {
494             match *predicate {
495                 ExistentialPredicate::AutoTrait(d) => Some(d),
496                 _ => None
497             }
498         })
499     }
500 }
501
502 impl<'tcx> Binder<&'tcx Slice<ExistentialPredicate<'tcx>>> {
503     pub fn principal(&self) -> Option<PolyExistentialTraitRef<'tcx>> {
504         self.skip_binder().principal().map(Binder)
505     }
506
507     #[inline]
508     pub fn projection_bounds<'a>(&'a self) ->
509         impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
510         self.skip_binder().projection_bounds().map(Binder)
511     }
512
513     #[inline]
514     pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
515         self.skip_binder().auto_traits()
516     }
517
518     pub fn iter<'a>(&'a self)
519         -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
520         self.skip_binder().iter().cloned().map(Binder)
521     }
522 }
523
524 /// A complete reference to a trait. These take numerous guises in syntax,
525 /// but perhaps the most recognizable form is in a where clause:
526 ///
527 ///     T : Foo<U>
528 ///
529 /// This would be represented by a trait-reference where the def-id is the
530 /// def-id for the trait `Foo` and the substs define `T` as parameter 0,
531 /// and `U` as parameter 1.
532 ///
533 /// Trait references also appear in object types like `Foo<U>`, but in
534 /// that case the `Self` parameter is absent from the substitutions.
535 ///
536 /// Note that a `TraitRef` introduces a level of region binding, to
537 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
538 /// U>` or higher-ranked object types.
539 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
540 pub struct TraitRef<'tcx> {
541     pub def_id: DefId,
542     pub substs: &'tcx Substs<'tcx>,
543 }
544
545 impl<'tcx> TraitRef<'tcx> {
546     pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
547         TraitRef { def_id: def_id, substs: substs }
548     }
549
550     pub fn self_ty(&self) -> Ty<'tcx> {
551         self.substs.type_at(0)
552     }
553
554     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
555         // Select only the "input types" from a trait-reference. For
556         // now this is all the types that appear in the
557         // trait-reference, but it should eventually exclude
558         // associated types.
559         self.substs.types()
560     }
561 }
562
563 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
564
565 impl<'tcx> PolyTraitRef<'tcx> {
566     pub fn self_ty(&self) -> Ty<'tcx> {
567         self.0.self_ty()
568     }
569
570     pub fn def_id(&self) -> DefId {
571         self.0.def_id
572     }
573
574     pub fn substs(&self) -> &'tcx Substs<'tcx> {
575         // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
576         self.0.substs
577     }
578
579     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
580         // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
581         self.0.input_types()
582     }
583
584     pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
585         // Note that we preserve binding levels
586         Binder(ty::TraitPredicate { trait_ref: self.0.clone() })
587     }
588 }
589
590 /// An existential reference to a trait, where `Self` is erased.
591 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
592 ///
593 ///     exists T. T: Trait<'a, 'b, X, Y>
594 ///
595 /// The substitutions don't include the erased `Self`, only trait
596 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
597 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
598 pub struct ExistentialTraitRef<'tcx> {
599     pub def_id: DefId,
600     pub substs: &'tcx Substs<'tcx>,
601 }
602
603 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
604     pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
605         // Select only the "input types" from a trait-reference. For
606         // now this is all the types that appear in the
607         // trait-reference, but it should eventually exclude
608         // associated types.
609         self.substs.types()
610     }
611
612     /// Object types don't have a self-type specified. Therefore, when
613     /// we convert the principal trait-ref into a normal trait-ref,
614     /// you must give *some* self-type. A common choice is `mk_err()`
615     /// or some skolemized type.
616     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
617         -> ty::TraitRef<'tcx>  {
618         // otherwise the escaping regions would be captured by the binder
619         assert!(!self_ty.has_escaping_regions());
620
621         ty::TraitRef {
622             def_id: self.def_id,
623             substs: tcx.mk_substs(
624                 iter::once(self_ty.into()).chain(self.substs.iter().cloned()))
625         }
626     }
627 }
628
629 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
630
631 impl<'tcx> PolyExistentialTraitRef<'tcx> {
632     pub fn def_id(&self) -> DefId {
633         self.0.def_id
634     }
635
636     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
637         // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<>
638         self.0.input_types()
639     }
640 }
641
642 /// Binder is a binder for higher-ranked lifetimes. It is part of the
643 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
644 /// (which would be represented by the type `PolyTraitRef ==
645 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
646 /// erase, or otherwise "discharge" these bound regions, we change the
647 /// type from `Binder<T>` to just `T` (see
648 /// e.g. `liberate_late_bound_regions`).
649 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
650 pub struct Binder<T>(pub T);
651
652 impl<T> Binder<T> {
653     /// Wraps `value` in a binder, asserting that `value` does not
654     /// contain any bound regions that would be bound by the
655     /// binder. This is commonly used to 'inject' a value T into a
656     /// different binding level.
657     pub fn dummy<'tcx>(value: T) -> Binder<T>
658         where T: TypeFoldable<'tcx>
659     {
660         assert!(!value.has_escaping_regions());
661         Binder(value)
662     }
663
664     /// Skips the binder and returns the "bound" value. This is a
665     /// risky thing to do because it's easy to get confused about
666     /// debruijn indices and the like. It is usually better to
667     /// discharge the binder using `no_late_bound_regions` or
668     /// `replace_late_bound_regions` or something like
669     /// that. `skip_binder` is only valid when you are either
670     /// extracting data that has nothing to do with bound regions, you
671     /// are doing some sort of test that does not involve bound
672     /// regions, or you are being very careful about your depth
673     /// accounting.
674     ///
675     /// Some examples where `skip_binder` is reasonable:
676     ///
677     /// - extracting the def-id from a PolyTraitRef;
678     /// - comparing the self type of a PolyTraitRef to see if it is equal to
679     ///   a type parameter `X`, since the type `X`  does not reference any regions
680     pub fn skip_binder(&self) -> &T {
681         &self.0
682     }
683
684     pub fn as_ref(&self) -> Binder<&T> {
685         ty::Binder(&self.0)
686     }
687
688     pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
689         where F: FnOnce(&T) -> U
690     {
691         self.as_ref().map_bound(f)
692     }
693
694     pub fn map_bound<F, U>(self, f: F) -> Binder<U>
695         where F: FnOnce(T) -> U
696     {
697         ty::Binder(f(self.0))
698     }
699
700     /// Unwraps and returns the value within, but only if it contains
701     /// no bound regions at all. (In other words, if this binder --
702     /// and indeed any enclosing binder -- doesn't bind anything at
703     /// all.) Otherwise, returns `None`.
704     ///
705     /// (One could imagine having a method that just unwraps a single
706     /// binder, but permits late-bound regions bound by enclosing
707     /// binders, but that would require adjusting the debruijn
708     /// indices, and given the shallow binding structure we often use,
709     /// would not be that useful.)
710     pub fn no_late_bound_regions<'tcx>(self) -> Option<T>
711         where T : TypeFoldable<'tcx>
712     {
713         if self.skip_binder().has_escaping_regions() {
714             None
715         } else {
716             Some(self.skip_binder().clone())
717         }
718     }
719
720     /// Given two things that have the same binder level,
721     /// and an operation that wraps on their contents, execute the operation
722     /// and then wrap its result.
723     ///
724     /// `f` should consider bound regions at depth 1 to be free, and
725     /// anything it produces with bound regions at depth 1 will be
726     /// bound in the resulting return value.
727     pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
728         where F: FnOnce(T, U) -> R
729     {
730         ty::Binder(f(self.0, u.0))
731     }
732
733     /// Split the contents into two things that share the same binder
734     /// level as the original, returning two distinct binders.
735     ///
736     /// `f` should consider bound regions at depth 1 to be free, and
737     /// anything it produces with bound regions at depth 1 will be
738     /// bound in the resulting return values.
739     pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
740         where F: FnOnce(T) -> (U, V)
741     {
742         let (u, v) = f(self.0);
743         (ty::Binder(u), ty::Binder(v))
744     }
745 }
746
747 /// Represents the projection of an associated type. In explicit UFCS
748 /// form this would be written `<T as Trait<..>>::N`.
749 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
750 pub struct ProjectionTy<'tcx> {
751     /// The parameters of the associated item.
752     pub substs: &'tcx Substs<'tcx>,
753
754     /// The DefId of the TraitItem for the associated type N.
755     ///
756     /// Note that this is not the DefId of the TraitRef containing this
757     /// associated type, which is in tcx.associated_item(item_def_id).container.
758     pub item_def_id: DefId,
759 }
760
761 impl<'a, 'tcx> ProjectionTy<'tcx> {
762     /// Construct a ProjectionTy by searching the trait from trait_ref for the
763     /// associated item named item_name.
764     pub fn from_ref_and_name(
765         tcx: TyCtxt, trait_ref: ty::TraitRef<'tcx>, item_name: Name
766     ) -> ProjectionTy<'tcx> {
767         let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
768             item.kind == ty::AssociatedKind::Type &&
769             tcx.hygienic_eq(item_name, item.name, trait_ref.def_id)
770         }).unwrap().def_id;
771
772         ProjectionTy {
773             substs: trait_ref.substs,
774             item_def_id,
775         }
776     }
777
778     /// Extracts the underlying trait reference from this projection.
779     /// For example, if this is a projection of `<T as Iterator>::Item`,
780     /// then this function would return a `T: Iterator` trait reference.
781     pub fn trait_ref(&self, tcx: TyCtxt) -> ty::TraitRef<'tcx> {
782         let def_id = tcx.associated_item(self.item_def_id).container.id();
783         ty::TraitRef {
784             def_id,
785             substs: self.substs,
786         }
787     }
788
789     pub fn self_ty(&self) -> Ty<'tcx> {
790         self.substs.type_at(0)
791     }
792 }
793
794 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
795 pub struct GenSig<'tcx> {
796     pub yield_ty: Ty<'tcx>,
797     pub return_ty: Ty<'tcx>,
798 }
799
800 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
801
802 impl<'tcx> PolyGenSig<'tcx> {
803     pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
804         self.map_bound_ref(|sig| sig.yield_ty)
805     }
806     pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
807         self.map_bound_ref(|sig| sig.return_ty)
808     }
809 }
810
811 /// Signature of a function type, which I have arbitrarily
812 /// decided to use to refer to the input/output types.
813 ///
814 /// - `inputs` is the list of arguments and their modes.
815 /// - `output` is the return type.
816 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
817 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
818 pub struct FnSig<'tcx> {
819     pub inputs_and_output: &'tcx Slice<Ty<'tcx>>,
820     pub variadic: bool,
821     pub unsafety: hir::Unsafety,
822     pub abi: abi::Abi,
823 }
824
825 impl<'tcx> FnSig<'tcx> {
826     pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
827         &self.inputs_and_output[..self.inputs_and_output.len() - 1]
828     }
829
830     pub fn output(&self) -> Ty<'tcx> {
831         self.inputs_and_output[self.inputs_and_output.len() - 1]
832     }
833 }
834
835 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
836
837 impl<'tcx> PolyFnSig<'tcx> {
838     pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
839         Binder(self.skip_binder().inputs())
840     }
841     pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
842         self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
843     }
844     pub fn inputs_and_output(&self) -> ty::Binder<&'tcx Slice<Ty<'tcx>>> {
845         self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
846     }
847     pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
848         self.map_bound_ref(|fn_sig| fn_sig.output().clone())
849     }
850     pub fn variadic(&self) -> bool {
851         self.skip_binder().variadic
852     }
853     pub fn unsafety(&self) -> hir::Unsafety {
854         self.skip_binder().unsafety
855     }
856     pub fn abi(&self) -> abi::Abi {
857         self.skip_binder().abi
858     }
859 }
860
861 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
862 pub struct ParamTy {
863     pub idx: u32,
864     pub name: Name,
865 }
866
867 impl<'a, 'gcx, 'tcx> ParamTy {
868     pub fn new(index: u32, name: Name) -> ParamTy {
869         ParamTy { idx: index, name: name }
870     }
871
872     pub fn for_self() -> ParamTy {
873         ParamTy::new(0, keywords::SelfType.name())
874     }
875
876     pub fn for_def(def: &ty::TypeParameterDef) -> ParamTy {
877         ParamTy::new(def.index, def.name)
878     }
879
880     pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
881         tcx.mk_param(self.idx, self.name)
882     }
883
884     pub fn is_self(&self) -> bool {
885         if self.name == keywords::SelfType.name() {
886             assert_eq!(self.idx, 0);
887             true
888         } else {
889             false
890         }
891     }
892 }
893
894 /// A [De Bruijn index][dbi] is a standard means of representing
895 /// regions (and perhaps later types) in a higher-ranked setting. In
896 /// particular, imagine a type like this:
897 ///
898 ///     for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
899 ///     ^          ^            |        |         |
900 ///     |          |            |        |         |
901 ///     |          +------------+ 1      |         |
902 ///     |                                |         |
903 ///     +--------------------------------+ 2       |
904 ///     |                                          |
905 ///     +------------------------------------------+ 1
906 ///
907 /// In this type, there are two binders (the outer fn and the inner
908 /// fn). We need to be able to determine, for any given region, which
909 /// fn type it is bound by, the inner or the outer one. There are
910 /// various ways you can do this, but a De Bruijn index is one of the
911 /// more convenient and has some nice properties. The basic idea is to
912 /// count the number of binders, inside out. Some examples should help
913 /// clarify what I mean.
914 ///
915 /// Let's start with the reference type `&'b isize` that is the first
916 /// argument to the inner function. This region `'b` is assigned a De
917 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
918 /// fn). The region `'a` that appears in the second argument type (`&'a
919 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
920 /// second-innermost binder". (These indices are written on the arrays
921 /// in the diagram).
922 ///
923 /// What is interesting is that De Bruijn index attached to a particular
924 /// variable will vary depending on where it appears. For example,
925 /// the final type `&'a char` also refers to the region `'a` declared on
926 /// the outermost fn. But this time, this reference is not nested within
927 /// any other binders (i.e., it is not an argument to the inner fn, but
928 /// rather the outer one). Therefore, in this case, it is assigned a
929 /// De Bruijn index of 1, because the innermost binder in that location
930 /// is the outer fn.
931 ///
932 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
933 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy, PartialOrd, Ord)]
934 pub struct DebruijnIndex {
935     /// We maintain the invariant that this is never 0. So 1 indicates
936     /// the innermost binder. To ensure this, create with `DebruijnIndex::new`.
937     pub depth: u32,
938 }
939
940 pub type Region<'tcx> = &'tcx RegionKind;
941
942 /// Representation of regions.
943 ///
944 /// Unlike types, most region variants are "fictitious", not concrete,
945 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
946 /// ones representing concrete regions.
947 ///
948 /// ## Bound Regions
949 ///
950 /// These are regions that are stored behind a binder and must be substituted
951 /// with some concrete region before being used. There are 2 kind of
952 /// bound regions: early-bound, which are bound in an item's Generics,
953 /// and are substituted by a Substs,  and late-bound, which are part of
954 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
955 /// the likes of `liberate_late_bound_regions`. The distinction exists
956 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
957 ///
958 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
959 /// outside their binder, e.g. in types passed to type inference, and
960 /// should first be substituted (by skolemized regions, free regions,
961 /// or region variables).
962 ///
963 /// ## Skolemized and Free Regions
964 ///
965 /// One often wants to work with bound regions without knowing their precise
966 /// identity. For example, when checking a function, the lifetime of a borrow
967 /// can end up being assigned to some region parameter. In these cases,
968 /// it must be ensured that bounds on the region can't be accidentally
969 /// assumed without being checked.
970 ///
971 /// The process of doing that is called "skolemization". The bound regions
972 /// are replaced by skolemized markers, which don't satisfy any relation
973 /// not explicitly provided.
974 ///
975 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
976 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
977 /// to be used. These also support explicit bounds: both the internally-stored
978 /// *scope*, which the region is assumed to outlive, as well as other
979 /// relations stored in the `FreeRegionMap`. Note that these relations
980 /// aren't checked when you `make_subregion` (or `eq_types`), only by
981 /// `resolve_regions_and_report_errors`.
982 ///
983 /// When working with higher-ranked types, some region relations aren't
984 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
985 /// `ReSkolemized` is designed for this purpose. In these contexts,
986 /// there's also the risk that some inference variable laying around will
987 /// get unified with your skolemized region: if you want to check whether
988 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
989 /// with a skolemized region `'%a`, the variable `'_` would just be
990 /// instantiated to the skolemized region `'%a`, which is wrong because
991 /// the inference variable is supposed to satisfy the relation
992 /// *for every value of the skolemized region*. To ensure that doesn't
993 /// happen, you can use `leak_check`. This is more clearly explained
994 /// by the [rustc guide].
995 ///
996 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
997 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
998 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/trait-hrtb.html
999 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1000 pub enum RegionKind {
1001     // Region bound in a type or fn declaration which will be
1002     // substituted 'early' -- that is, at the same time when type
1003     // parameters are substituted.
1004     ReEarlyBound(EarlyBoundRegion),
1005
1006     // Region bound in a function scope, which will be substituted when the
1007     // function is called.
1008     ReLateBound(DebruijnIndex, BoundRegion),
1009
1010     /// When checking a function body, the types of all arguments and so forth
1011     /// that refer to bound region parameters are modified to refer to free
1012     /// region parameters.
1013     ReFree(FreeRegion),
1014
1015     /// A concrete region naming some statically determined scope
1016     /// (e.g. an expression or sequence of statements) within the
1017     /// current function.
1018     ReScope(region::Scope),
1019
1020     /// Static data that has an "infinite" lifetime. Top in the region lattice.
1021     ReStatic,
1022
1023     /// A region variable.  Should not exist after typeck.
1024     ReVar(RegionVid),
1025
1026     /// A skolemized region - basically the higher-ranked version of ReFree.
1027     /// Should not exist after typeck.
1028     ReSkolemized(ty::UniverseIndex, BoundRegion),
1029
1030     /// Empty lifetime is for data that is never accessed.
1031     /// Bottom in the region lattice. We treat ReEmpty somewhat
1032     /// specially; at least right now, we do not generate instances of
1033     /// it during the GLB computations, but rather
1034     /// generate an error instead. This is to improve error messages.
1035     /// The only way to get an instance of ReEmpty is to have a region
1036     /// variable with no constraints.
1037     ReEmpty,
1038
1039     /// Erased region, used by trait selection, in MIR and during trans.
1040     ReErased,
1041
1042     /// These are regions bound in the "defining type" for a
1043     /// closure. They are used ONLY as part of the
1044     /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1045     /// See `ClosureRegionRequirements` for more details.
1046     ReClosureBound(RegionVid),
1047
1048     /// Canonicalized region, used only when preparing a trait query.
1049     ReCanonical(CanonicalVar),
1050 }
1051
1052 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1053
1054 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1055 pub struct EarlyBoundRegion {
1056     pub def_id: DefId,
1057     pub index: u32,
1058     pub name: Name,
1059 }
1060
1061 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1062 pub struct TyVid {
1063     pub index: u32,
1064 }
1065
1066 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1067 pub struct IntVid {
1068     pub index: u32,
1069 }
1070
1071 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1072 pub struct FloatVid {
1073     pub index: u32,
1074 }
1075
1076 newtype_index!(RegionVid
1077     {
1078         pub idx
1079         DEBUG_FORMAT = custom,
1080     });
1081
1082 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1083 pub enum InferTy {
1084     TyVar(TyVid),
1085     IntVar(IntVid),
1086     FloatVar(FloatVid),
1087
1088     /// A `FreshTy` is one that is generated as a replacement for an
1089     /// unbound type variable. This is convenient for caching etc. See
1090     /// `infer::freshen` for more details.
1091     FreshTy(u32),
1092     FreshIntTy(u32),
1093     FreshFloatTy(u32),
1094
1095     /// Canonicalized type variable, used only when preparing a trait query.
1096     CanonicalTy(CanonicalVar),
1097 }
1098
1099 newtype_index!(CanonicalVar);
1100
1101 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1102 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1103 pub struct ExistentialProjection<'tcx> {
1104     pub item_def_id: DefId,
1105     pub substs: &'tcx Substs<'tcx>,
1106     pub ty: Ty<'tcx>,
1107 }
1108
1109 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1110
1111 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1112     /// Extracts the underlying existential trait reference from this projection.
1113     /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1114     /// then this function would return a `exists T. T: Iterator` existential trait
1115     /// reference.
1116     pub fn trait_ref(&self, tcx: TyCtxt) -> ty::ExistentialTraitRef<'tcx> {
1117         let def_id = tcx.associated_item(self.item_def_id).container.id();
1118         ty::ExistentialTraitRef{
1119             def_id,
1120             substs: self.substs,
1121         }
1122     }
1123
1124     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1125                         self_ty: Ty<'tcx>)
1126                         -> ty::ProjectionPredicate<'tcx>
1127     {
1128         // otherwise the escaping regions would be captured by the binders
1129         assert!(!self_ty.has_escaping_regions());
1130
1131         ty::ProjectionPredicate {
1132             projection_ty: ty::ProjectionTy {
1133                 item_def_id: self.item_def_id,
1134                 substs: tcx.mk_substs(
1135                 iter::once(self_ty.into()).chain(self.substs.iter().cloned())),
1136             },
1137             ty: self.ty,
1138         }
1139     }
1140 }
1141
1142 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
1143     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
1144         -> ty::PolyProjectionPredicate<'tcx> {
1145         self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1146     }
1147 }
1148
1149 impl DebruijnIndex {
1150     pub fn new(depth: u32) -> DebruijnIndex {
1151         assert!(depth > 0);
1152         DebruijnIndex { depth: depth }
1153     }
1154
1155     pub fn shifted(&self, amount: u32) -> DebruijnIndex {
1156         DebruijnIndex { depth: self.depth + amount }
1157     }
1158 }
1159
1160 /// Region utilities
1161 impl RegionKind {
1162     pub fn is_late_bound(&self) -> bool {
1163         match *self {
1164             ty::ReLateBound(..) => true,
1165             _ => false,
1166         }
1167     }
1168
1169     pub fn needs_infer(&self) -> bool {
1170         match *self {
1171             ty::ReVar(..) | ty::ReSkolemized(..) => true,
1172             _ => false
1173         }
1174     }
1175
1176     pub fn escapes_depth(&self, depth: u32) -> bool {
1177         match *self {
1178             ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1179             _ => false,
1180         }
1181     }
1182
1183     /// Returns the depth of `self` from the (1-based) binding level `depth`
1184     pub fn from_depth(&self, depth: u32) -> RegionKind {
1185         match *self {
1186             ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
1187                 depth: debruijn.depth - (depth - 1)
1188             }, r),
1189             r => r
1190         }
1191     }
1192
1193     pub fn type_flags(&self) -> TypeFlags {
1194         let mut flags = TypeFlags::empty();
1195
1196         match *self {
1197             ty::ReVar(..) => {
1198                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1199                 flags = flags | TypeFlags::HAS_RE_INFER;
1200                 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1201             }
1202             ty::ReSkolemized(..) => {
1203                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1204                 flags = flags | TypeFlags::HAS_RE_INFER;
1205                 flags = flags | TypeFlags::HAS_RE_SKOL;
1206                 flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1207             }
1208             ty::ReLateBound(..) => { }
1209             ty::ReEarlyBound(..) => {
1210                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1211                 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1212             }
1213             ty::ReEmpty |
1214             ty::ReStatic |
1215             ty::ReFree { .. } |
1216             ty::ReScope { .. } => {
1217                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1218             }
1219             ty::ReErased => {
1220             }
1221             ty::ReCanonical(..) => {
1222                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1223                 flags = flags | TypeFlags::HAS_CANONICAL_VARS;
1224             }
1225             ty::ReClosureBound(..) => {
1226                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1227             }
1228         }
1229
1230         match *self {
1231             ty::ReStatic | ty::ReEmpty | ty::ReErased => (),
1232             _ => flags = flags | TypeFlags::HAS_LOCAL_NAMES,
1233         }
1234
1235         debug!("type_flags({:?}) = {:?}", self, flags);
1236
1237         flags
1238     }
1239
1240     /// Given an early-bound or free region, returns the def-id where it was bound.
1241     /// For example, consider the regions in this snippet of code:
1242     ///
1243     /// ```
1244     /// impl<'a> Foo {
1245     ///      ^^ -- early bound, declared on an impl
1246     ///
1247     ///     fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1248     ///            ^^  ^^     ^ anonymous, late-bound
1249     ///            |   early-bound, appears in where-clauses
1250     ///            late-bound, appears only in fn args
1251     ///     {..}
1252     /// }
1253     /// ```
1254     ///
1255     /// Here, `free_region_binding_scope('a)` would return the def-id
1256     /// of the impl, and for all the other highlighted regions, it
1257     /// would return the def-id of the function. In other cases (not shown), this
1258     /// function might return the def-id of a closure.
1259     pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_, '_, '_>) -> DefId {
1260         match self {
1261             ty::ReEarlyBound(br) => {
1262                 tcx.parent_def_id(br.def_id).unwrap()
1263             }
1264             ty::ReFree(fr) => fr.scope,
1265             _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1266         }
1267     }
1268 }
1269
1270 /// Type utilities
1271 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
1272     pub fn is_nil(&self) -> bool {
1273         match self.sty {
1274             TyTuple(ref tys) => tys.is_empty(),
1275             _ => false,
1276         }
1277     }
1278
1279     pub fn is_never(&self) -> bool {
1280         match self.sty {
1281             TyNever => true,
1282             _ => false,
1283         }
1284     }
1285
1286     pub fn is_primitive(&self) -> bool {
1287         match self.sty {
1288             TyBool | TyChar | TyInt(_) | TyUint(_) | TyFloat(_) => true,
1289             _ => false,
1290         }
1291     }
1292
1293     pub fn is_ty_var(&self) -> bool {
1294         match self.sty {
1295             TyInfer(TyVar(_)) => true,
1296             _ => false,
1297         }
1298     }
1299
1300     pub fn is_ty_infer(&self) -> bool {
1301         match self.sty {
1302             TyInfer(_) => true,
1303             _ => false,
1304         }
1305     }
1306
1307     pub fn is_phantom_data(&self) -> bool {
1308         if let TyAdt(def, _) = self.sty {
1309             def.is_phantom_data()
1310         } else {
1311             false
1312         }
1313     }
1314
1315     pub fn is_bool(&self) -> bool { self.sty == TyBool }
1316
1317     pub fn is_param(&self, index: u32) -> bool {
1318         match self.sty {
1319             ty::TyParam(ref data) => data.idx == index,
1320             _ => false,
1321         }
1322     }
1323
1324     pub fn is_self(&self) -> bool {
1325         match self.sty {
1326             TyParam(ref p) => p.is_self(),
1327             _ => false,
1328         }
1329     }
1330
1331     pub fn is_slice(&self) -> bool {
1332         match self.sty {
1333             TyRawPtr(mt) | TyRef(_, mt) => match mt.ty.sty {
1334                 TySlice(_) | TyStr => true,
1335                 _ => false,
1336             },
1337             _ => false
1338         }
1339     }
1340
1341     #[inline]
1342     pub fn is_simd(&self) -> bool {
1343         match self.sty {
1344             TyAdt(def, _) => def.repr.simd(),
1345             _ => false,
1346         }
1347     }
1348
1349     pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1350         match self.sty {
1351             TyArray(ty, _) | TySlice(ty) => ty,
1352             TyStr => tcx.mk_mach_uint(ast::UintTy::U8),
1353             _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1354         }
1355     }
1356
1357     pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1358         match self.sty {
1359             TyAdt(def, substs) => {
1360                 def.non_enum_variant().fields[0].ty(tcx, substs)
1361             }
1362             _ => bug!("simd_type called on invalid type")
1363         }
1364     }
1365
1366     pub fn simd_size(&self, _cx: TyCtxt) -> usize {
1367         match self.sty {
1368             TyAdt(def, _) => def.non_enum_variant().fields.len(),
1369             _ => bug!("simd_size called on invalid type")
1370         }
1371     }
1372
1373     pub fn is_region_ptr(&self) -> bool {
1374         match self.sty {
1375             TyRef(..) => true,
1376             _ => false,
1377         }
1378     }
1379
1380     pub fn is_mutable_pointer(&self) -> bool {
1381         match self.sty {
1382             TyRawPtr(tnm) | TyRef(_, tnm) => if let hir::Mutability::MutMutable = tnm.mutbl {
1383                 true
1384             } else {
1385                 false
1386             },
1387             _ => false
1388         }
1389     }
1390
1391     pub fn is_unsafe_ptr(&self) -> bool {
1392         match self.sty {
1393             TyRawPtr(_) => return true,
1394             _ => return false,
1395         }
1396     }
1397
1398     pub fn is_box(&self) -> bool {
1399         match self.sty {
1400             TyAdt(def, _) => def.is_box(),
1401             _ => false,
1402         }
1403     }
1404
1405     /// panics if called on any type other than `Box<T>`
1406     pub fn boxed_ty(&self) -> Ty<'tcx> {
1407         match self.sty {
1408             TyAdt(def, substs) if def.is_box() => substs.type_at(0),
1409             _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1410         }
1411     }
1412
1413     /// A scalar type is one that denotes an atomic datum, with no sub-components.
1414     /// (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1415     /// contents are abstract to rustc.)
1416     pub fn is_scalar(&self) -> bool {
1417         match self.sty {
1418             TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
1419             TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
1420             TyFnDef(..) | TyFnPtr(_) | TyRawPtr(_) => true,
1421             _ => false
1422         }
1423     }
1424
1425     /// Returns true if this type is a floating point type and false otherwise.
1426     pub fn is_floating_point(&self) -> bool {
1427         match self.sty {
1428             TyFloat(_) |
1429             TyInfer(FloatVar(_)) => true,
1430             _ => false,
1431         }
1432     }
1433
1434     pub fn is_trait(&self) -> bool {
1435         match self.sty {
1436             TyDynamic(..) => true,
1437             _ => false,
1438         }
1439     }
1440
1441     pub fn is_enum(&self) -> bool {
1442         match self.sty {
1443             TyAdt(adt_def, _) => {
1444                 adt_def.is_enum()
1445             }
1446             _ => false,
1447         }
1448     }
1449
1450     pub fn is_closure(&self) -> bool {
1451         match self.sty {
1452             TyClosure(..) => true,
1453             _ => false,
1454         }
1455     }
1456
1457     pub fn is_generator(&self) -> bool {
1458         match self.sty {
1459             TyGenerator(..) => true,
1460             _ => false,
1461         }
1462     }
1463
1464     pub fn is_integral(&self) -> bool {
1465         match self.sty {
1466             TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
1467             _ => false
1468         }
1469     }
1470
1471     pub fn is_fresh_ty(&self) -> bool {
1472         match self.sty {
1473             TyInfer(FreshTy(_)) => true,
1474             _ => false,
1475         }
1476     }
1477
1478     pub fn is_fresh(&self) -> bool {
1479         match self.sty {
1480             TyInfer(FreshTy(_)) => true,
1481             TyInfer(FreshIntTy(_)) => true,
1482             TyInfer(FreshFloatTy(_)) => true,
1483             _ => false,
1484         }
1485     }
1486
1487     pub fn is_char(&self) -> bool {
1488         match self.sty {
1489             TyChar => true,
1490             _ => false,
1491         }
1492     }
1493
1494     pub fn is_fp(&self) -> bool {
1495         match self.sty {
1496             TyInfer(FloatVar(_)) | TyFloat(_) => true,
1497             _ => false
1498         }
1499     }
1500
1501     pub fn is_numeric(&self) -> bool {
1502         self.is_integral() || self.is_fp()
1503     }
1504
1505     pub fn is_signed(&self) -> bool {
1506         match self.sty {
1507             TyInt(_) => true,
1508             _ => false,
1509         }
1510     }
1511
1512     pub fn is_machine(&self) -> bool {
1513         match self.sty {
1514             TyInt(ast::IntTy::Isize) | TyUint(ast::UintTy::Usize) => false,
1515             TyInt(..) | TyUint(..) | TyFloat(..) => true,
1516             _ => false,
1517         }
1518     }
1519
1520     pub fn has_concrete_skeleton(&self) -> bool {
1521         match self.sty {
1522             TyParam(_) | TyInfer(_) | TyError => false,
1523             _ => true,
1524         }
1525     }
1526
1527     /// Returns the type and mutability of *ty.
1528     ///
1529     /// The parameter `explicit` indicates if this is an *explicit* dereference.
1530     /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1531     pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1532         match self.sty {
1533             TyAdt(def, _) if def.is_box() => {
1534                 Some(TypeAndMut {
1535                     ty: self.boxed_ty(),
1536                     mutbl: hir::MutImmutable,
1537                 })
1538             },
1539             TyRef(_, mt) => Some(mt),
1540             TyRawPtr(mt) if explicit => Some(mt),
1541             _ => None,
1542         }
1543     }
1544
1545     /// Returns the type of ty[i]
1546     pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1547         match self.sty {
1548             TyArray(ty, _) | TySlice(ty) => Some(ty),
1549             _ => None,
1550         }
1551     }
1552
1553     pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1554         match self.sty {
1555             TyFnDef(def_id, substs) => {
1556                 tcx.fn_sig(def_id).subst(tcx, substs)
1557             }
1558             TyFnPtr(f) => f,
1559             _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1560         }
1561     }
1562
1563     pub fn is_fn(&self) -> bool {
1564         match self.sty {
1565             TyFnDef(..) | TyFnPtr(_) => true,
1566             _ => false,
1567         }
1568     }
1569
1570     pub fn ty_to_def_id(&self) -> Option<DefId> {
1571         match self.sty {
1572             TyDynamic(ref tt, ..) => tt.principal().map(|p| p.def_id()),
1573             TyAdt(def, _) => Some(def.did),
1574             TyForeign(did) => Some(did),
1575             TyClosure(id, _) => Some(id),
1576             TyFnDef(id, _) => Some(id),
1577             _ => None,
1578         }
1579     }
1580
1581     pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1582         match self.sty {
1583             TyAdt(adt, _) => Some(adt),
1584             _ => None,
1585         }
1586     }
1587
1588     /// Returns the regions directly referenced from this type (but
1589     /// not types reachable from this type via `walk_tys`). This
1590     /// ignores late-bound regions binders.
1591     pub fn regions(&self) -> Vec<ty::Region<'tcx>> {
1592         match self.sty {
1593             TyRef(region, _) => {
1594                 vec![region]
1595             }
1596             TyDynamic(ref obj, region) => {
1597                 let mut v = vec![region];
1598                 if let Some(p) = obj.principal() {
1599                     v.extend(p.skip_binder().substs.regions());
1600                 }
1601                 v
1602             }
1603             TyAdt(_, substs) | TyAnon(_, substs) => {
1604                 substs.regions().collect()
1605             }
1606             TyClosure(_, ref substs) | TyGenerator(_, ref substs, _) => {
1607                 substs.substs.regions().collect()
1608             }
1609             TyProjection(ref data) => {
1610                 data.substs.regions().collect()
1611             }
1612             TyFnDef(..) |
1613             TyFnPtr(_) |
1614             TyGeneratorWitness(..) |
1615             TyBool |
1616             TyChar |
1617             TyInt(_) |
1618             TyUint(_) |
1619             TyFloat(_) |
1620             TyStr |
1621             TyArray(..) |
1622             TySlice(_) |
1623             TyRawPtr(_) |
1624             TyNever |
1625             TyTuple(..) |
1626             TyForeign(..) |
1627             TyParam(_) |
1628             TyInfer(_) |
1629             TyError => {
1630                 vec![]
1631             }
1632         }
1633     }
1634
1635     /// When we create a closure, we record its kind (i.e., what trait
1636     /// it implements) into its `ClosureSubsts` using a type
1637     /// parameter. This is kind of a phantom type, except that the
1638     /// most convenient thing for us to are the integral types. This
1639     /// function converts such a special type into the closure
1640     /// kind. To go the other way, use
1641     /// `tcx.closure_kind_ty(closure_kind)`.
1642     ///
1643     /// Note that during type checking, we use an inference variable
1644     /// to represent the closure kind, because it has not yet been
1645     /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
1646     /// is complete, that type variable will be unified.
1647     pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
1648         match self.sty {
1649             TyInt(int_ty) => match int_ty {
1650                 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
1651                 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1652                 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1653                 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1654             },
1655
1656             TyInfer(_) => None,
1657
1658             TyError => Some(ty::ClosureKind::Fn),
1659
1660             _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1661         }
1662     }
1663 }
1664
1665 /// Typed constant value.
1666 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Eq, PartialEq)]
1667 pub struct Const<'tcx> {
1668     pub ty: Ty<'tcx>,
1669
1670     // FIXME(eddyb) Replace this with a miri value.
1671     pub val: ConstVal<'tcx>,
1672 }
1673
1674 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}