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