]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/sty.rs
Remove `ReCanonical` in favor of `ReLateBound`
[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 TyKind and its major components
12
13 use hir::def_id::DefId;
14 use infer::canonical::Canonical;
15 use mir::interpret::ConstValue;
16 use middle::region;
17 use polonius_engine::Atom;
18 use rustc_data_structures::indexed_vec::Idx;
19 use ty::subst::{Substs, Subst, Kind, UnpackedKind};
20 use ty::{self, AdtDef, TypeFlags, Ty, TyCtxt, TypeFoldable};
21 use ty::{List, TyS, ParamEnvAnd, ParamEnv};
22 use util::captures::Captures;
23 use mir::interpret::{Scalar, Pointer};
24
25 use std::iter;
26 use std::cmp::Ordering;
27 use rustc_target::spec::abi;
28 use syntax::ast::{self, Ident};
29 use syntax::symbol::{keywords, InternedString};
30
31 use serialize;
32
33 use hir;
34
35 use self::InferTy::*;
36 use self::TyKind::*;
37
38 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
39 pub struct TypeAndMut<'tcx> {
40     pub ty: Ty<'tcx>,
41     pub mutbl: hir::Mutability,
42 }
43
44 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
45          RustcEncodable, RustcDecodable, Copy)]
46 /// A "free" region `fr` can be interpreted as "some region
47 /// at least as big as the scope `fr.scope`".
48 pub struct FreeRegion {
49     pub scope: DefId,
50     pub bound_region: BoundRegion,
51 }
52
53 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
54          RustcEncodable, RustcDecodable, Copy)]
55 pub enum BoundRegion {
56     /// An anonymous region parameter for a given fn (&T)
57     BrAnon(u32),
58
59     /// Named region parameters for functions (a in &'a T)
60     ///
61     /// The def-id is needed to distinguish free regions in
62     /// the event of shadowing.
63     BrNamed(DefId, InternedString),
64
65     /// Fresh bound identifiers created during GLB computations.
66     BrFresh(u32),
67
68     /// Anonymous region for the implicit env pointer parameter
69     /// to a closure
70     BrEnv,
71 }
72
73 impl BoundRegion {
74     pub fn is_named(&self) -> bool {
75         match *self {
76             BoundRegion::BrNamed(..) => true,
77             _ => false,
78         }
79     }
80
81     /// When canonicalizing, we replace unbound inference variables and free
82     /// regions with anonymous late bound regions. This method asserts that
83     /// we have an anonymous late bound region, which hence may refer to
84     /// a canonical variable.
85     pub fn as_bound_var(&self) -> BoundVar {
86         match *self {
87             BoundRegion::BrAnon(var) => BoundVar::from_u32(var),
88             _ => bug!("bound region is not anonymous"),
89         }
90     }
91 }
92
93 /// N.B., If you change this, you'll probably want to change the corresponding
94 /// AST structure in `libsyntax/ast.rs` as well.
95 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
96 pub enum TyKind<'tcx> {
97     /// The primitive boolean type. Written as `bool`.
98     Bool,
99
100     /// The primitive character type; holds a Unicode scalar value
101     /// (a non-surrogate code point).  Written as `char`.
102     Char,
103
104     /// A primitive signed integer type. For example, `i32`.
105     Int(ast::IntTy),
106
107     /// A primitive unsigned integer type. For example, `u32`.
108     Uint(ast::UintTy),
109
110     /// A primitive floating-point type. For example, `f64`.
111     Float(ast::FloatTy),
112
113     /// Structures, enumerations and unions.
114     ///
115     /// Substs here, possibly against intuition, *may* contain `Param`s.
116     /// That is, even after substitution it is possible that there are type
117     /// variables. This happens when the `Adt` corresponds to an ADT
118     /// definition and not a concrete use of it.
119     Adt(&'tcx AdtDef, &'tcx Substs<'tcx>),
120
121     Foreign(DefId),
122
123     /// The pointee of a string slice. Written as `str`.
124     Str,
125
126     /// An array with the given length. Written as `[T; n]`.
127     Array(Ty<'tcx>, &'tcx ty::Const<'tcx>),
128
129     /// The pointee of an array slice.  Written as `[T]`.
130     Slice(Ty<'tcx>),
131
132     /// A raw pointer. Written as `*mut T` or `*const T`
133     RawPtr(TypeAndMut<'tcx>),
134
135     /// A reference; a pointer with an associated lifetime. Written as
136     /// `&'a mut T` or `&'a T`.
137     Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability),
138
139     /// The anonymous type of a function declaration/definition. Each
140     /// function has a unique type, which is output (for a function
141     /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
142     ///
143     /// For example the type of `bar` here:
144     ///
145     /// ```rust
146     /// fn foo() -> i32 { 1 }
147     /// let bar = foo; // bar: fn() -> i32 {foo}
148     /// ```
149     FnDef(DefId, &'tcx Substs<'tcx>),
150
151     /// A pointer to a function.  Written as `fn() -> i32`.
152     ///
153     /// For example the type of `bar` here:
154     ///
155     /// ```rust
156     /// fn foo() -> i32 { 1 }
157     /// let bar: fn() -> i32 = foo;
158     /// ```
159     FnPtr(PolyFnSig<'tcx>),
160
161     /// A trait, defined with `trait`.
162     Dynamic(Binder<&'tcx List<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
163
164     /// The anonymous type of a closure. Used to represent the type of
165     /// `|a| a`.
166     Closure(DefId, ClosureSubsts<'tcx>),
167
168     /// The anonymous type of a generator. Used to represent the type of
169     /// `|a| yield a`.
170     Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
171
172     /// A type representin the types stored inside a generator.
173     /// This should only appear in GeneratorInteriors.
174     GeneratorWitness(Binder<&'tcx List<Ty<'tcx>>>),
175
176     /// The never type `!`
177     Never,
178
179     /// A tuple type.  For example, `(i32, bool)`.
180     Tuple(&'tcx List<Ty<'tcx>>),
181
182     /// The projection of an associated type.  For example,
183     /// `<T as Trait<..>>::N`.
184     Projection(ProjectionTy<'tcx>),
185
186     /// A placeholder type used when we do not have enough information
187     /// to normalize the projection of an associated type to an
188     /// existing concrete type. Currently only used with chalk-engine.
189     UnnormalizedProjection(ProjectionTy<'tcx>),
190
191     /// Opaque (`impl Trait`) type found in a return type.
192     /// The `DefId` comes either from
193     /// * the `impl Trait` ast::Ty node,
194     /// * or the `existential type` declaration
195     /// The substitutions are for the generics of the function in question.
196     /// After typeck, the concrete type can be found in the `types` map.
197     Opaque(DefId, &'tcx Substs<'tcx>),
198
199     /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
200     Param(ParamTy),
201
202     /// Bound type variable, used only when preparing a trait query.
203     Bound(BoundTy),
204
205     /// A type variable used during type checking.
206     Infer(InferTy),
207
208     /// A placeholder for a type which could not be computed; this is
209     /// propagated to avoid useless error messages.
210     Error,
211 }
212
213 /// A closure can be modeled as a struct that looks like:
214 ///
215 ///     struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
216 ///         upvar0: U0,
217 ///         ...
218 ///         upvark: Uk
219 ///     }
220 ///
221 /// where:
222 ///
223 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
224 ///   in scope on the function that defined the closure,
225 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
226 ///   is rather hackily encoded via a scalar type. See
227 ///   `TyS::to_opt_closure_kind` for details.
228 /// - CS represents the *closure signature*, representing as a `fn()`
229 ///   type. For example, `fn(u32, u32) -> u32` would mean that the closure
230 ///   implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
231 ///   specified above.
232 /// - U0...Uk are type parameters representing the types of its upvars
233 ///   (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
234 ///    and the up-var has the type `Foo`, then `Ui = &Foo`).
235 ///
236 /// So, for example, given this function:
237 ///
238 ///     fn foo<'a, T>(data: &'a mut T) {
239 ///          do(|| data.count += 1)
240 ///     }
241 ///
242 /// the type of the closure would be something like:
243 ///
244 ///     struct Closure<'a, T, U0> {
245 ///         data: U0
246 ///     }
247 ///
248 /// Note that the type of the upvar is not specified in the struct.
249 /// You may wonder how the impl would then be able to use the upvar,
250 /// if it doesn't know it's type? The answer is that the impl is
251 /// (conceptually) not fully generic over Closure but rather tied to
252 /// instances with the expected upvar types:
253 ///
254 ///     impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
255 ///         ...
256 ///     }
257 ///
258 /// You can see that the *impl* fully specified the type of the upvar
259 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
260 /// (Here, I am assuming that `data` is mut-borrowed.)
261 ///
262 /// Now, the last question you may ask is: Why include the upvar types
263 /// as extra type parameters? The reason for this design is that the
264 /// upvar types can reference lifetimes that are internal to the
265 /// creating function. In my example above, for example, the lifetime
266 /// `'b` represents the scope of the closure itself; this is some
267 /// subset of `foo`, probably just the scope of the call to the to
268 /// `do()`. If we just had the lifetime/type parameters from the
269 /// enclosing function, we couldn't name this lifetime `'b`. Note that
270 /// there can also be lifetimes in the types of the upvars themselves,
271 /// if one of them happens to be a reference to something that the
272 /// creating fn owns.
273 ///
274 /// OK, you say, so why not create a more minimal set of parameters
275 /// that just includes the extra lifetime parameters? The answer is
276 /// primarily that it would be hard --- we don't know at the time when
277 /// we create the closure type what the full types of the upvars are,
278 /// nor do we know which are borrowed and which are not. In this
279 /// design, we can just supply a fresh type parameter and figure that
280 /// out later.
281 ///
282 /// All right, you say, but why include the type parameters from the
283 /// original function then? The answer is that codegen may need them
284 /// when monomorphizing, and they may not appear in the upvars.  A
285 /// closure could capture no variables but still make use of some
286 /// in-scope type parameter with a bound (e.g., if our example above
287 /// had an extra `U: Default`, and the closure called `U::default()`).
288 ///
289 /// There is another reason. This design (implicitly) prohibits
290 /// closures from capturing themselves (except via a trait
291 /// object). This simplifies closure inference considerably, since it
292 /// means that when we infer the kind of a closure or its upvars, we
293 /// don't have to handle cycles where the decisions we make for
294 /// closure C wind up influencing the decisions we ought to make for
295 /// closure C (which would then require fixed point iteration to
296 /// handle). Plus it fixes an ICE. :P
297 ///
298 /// ## Generators
299 ///
300 /// Perhaps surprisingly, `ClosureSubsts` are also used for
301 /// generators.  In that case, what is written above is only half-true
302 /// -- the set of type parameters is similar, but the role of CK and
303 /// CS are different.  CK represents the "yield type" and CS
304 /// represents the "return type" of the generator.
305 ///
306 /// It'd be nice to split this struct into ClosureSubsts and
307 /// GeneratorSubsts, I believe. -nmatsakis
308 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
309 pub struct ClosureSubsts<'tcx> {
310     /// Lifetime and type parameters from the enclosing function,
311     /// concatenated with the types of the upvars.
312     ///
313     /// These are separated out because codegen wants to pass them around
314     /// when monomorphizing.
315     pub substs: &'tcx Substs<'tcx>,
316 }
317
318 /// Struct returned by `split()`. Note that these are subslices of the
319 /// parent slice and not canonical substs themselves.
320 struct SplitClosureSubsts<'tcx> {
321     closure_kind_ty: Ty<'tcx>,
322     closure_sig_ty: Ty<'tcx>,
323     upvar_kinds: &'tcx [Kind<'tcx>],
324 }
325
326 impl<'tcx> ClosureSubsts<'tcx> {
327     /// Divides the closure substs into their respective
328     /// components. Single source of truth with respect to the
329     /// ordering.
330     fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitClosureSubsts<'tcx> {
331         let generics = tcx.generics_of(def_id);
332         let parent_len = generics.parent_count;
333         SplitClosureSubsts {
334             closure_kind_ty: self.substs.type_at(parent_len),
335             closure_sig_ty: self.substs.type_at(parent_len + 1),
336             upvar_kinds: &self.substs[parent_len + 2..],
337         }
338     }
339
340     #[inline]
341     pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
342         impl Iterator<Item=Ty<'tcx>> + 'tcx
343     {
344         let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
345         upvar_kinds.iter().map(|t| {
346             if let UnpackedKind::Type(ty) = t.unpack() {
347                 ty
348             } else {
349                 bug!("upvar should be type")
350             }
351         })
352     }
353
354     /// Returns the closure kind for this closure; may return a type
355     /// variable during inference. To get the closure kind during
356     /// inference, use `infcx.closure_kind(def_id, substs)`.
357     pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
358         self.split(def_id, tcx).closure_kind_ty
359     }
360
361     /// Returns the type representing the closure signature for this
362     /// closure; may contain type variables during inference. To get
363     /// the closure signature during inference, use
364     /// `infcx.fn_sig(def_id)`.
365     pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
366         self.split(def_id, tcx).closure_sig_ty
367     }
368
369     /// Returns the closure kind for this closure; only usable outside
370     /// of an inference context, because in that context we know that
371     /// there are no type variables.
372     ///
373     /// If you have an inference context, use `infcx.closure_kind()`.
374     pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::ClosureKind {
375         self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
376     }
377
378     /// Extracts the signature from the closure; only usable outside
379     /// of an inference context, because in that context we know that
380     /// there are no type variables.
381     ///
382     /// If you have an inference context, use `infcx.closure_sig()`.
383     pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
384         match self.closure_sig_ty(def_id, tcx).sty {
385             ty::FnPtr(sig) => sig,
386             ref t => bug!("closure_sig_ty is not a fn-ptr: {:?}", t),
387         }
388     }
389 }
390
391 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
392 pub struct GeneratorSubsts<'tcx> {
393     pub substs: &'tcx Substs<'tcx>,
394 }
395
396 struct SplitGeneratorSubsts<'tcx> {
397     yield_ty: Ty<'tcx>,
398     return_ty: Ty<'tcx>,
399     witness: Ty<'tcx>,
400     upvar_kinds: &'tcx [Kind<'tcx>],
401 }
402
403 impl<'tcx> GeneratorSubsts<'tcx> {
404     fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitGeneratorSubsts<'tcx> {
405         let generics = tcx.generics_of(def_id);
406         let parent_len = generics.parent_count;
407         SplitGeneratorSubsts {
408             yield_ty: self.substs.type_at(parent_len),
409             return_ty: self.substs.type_at(parent_len + 1),
410             witness: self.substs.type_at(parent_len + 2),
411             upvar_kinds: &self.substs[parent_len + 3..],
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
419     /// in this tuple. Upvars are not counted here.
420     pub fn witness(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
421         self.split(def_id, tcx).witness
422     }
423
424     #[inline]
425     pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
426         impl Iterator<Item=Ty<'tcx>> + 'tcx
427     {
428         let SplitGeneratorSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
429         upvar_kinds.iter().map(|t| {
430             if let UnpackedKind::Type(ty) = t.unpack() {
431                 ty
432             } else {
433                 bug!("upvar should be type")
434             }
435         })
436     }
437
438     /// Returns the type representing the yield type of the generator.
439     pub fn yield_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
440         self.split(def_id, tcx).yield_ty
441     }
442
443     /// Returns the type representing the return type of the generator.
444     pub fn return_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
445         self.split(def_id, tcx).return_ty
446     }
447
448     /// Return the "generator signature", which consists of its yield
449     /// and return types.
450     ///
451     /// NB. Some bits of the code prefers to see this wrapped in a
452     /// binder, but it never contains bound regions. Probably this
453     /// function should be removed.
454     pub fn poly_sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> PolyGenSig<'tcx> {
455         ty::Binder::dummy(self.sig(def_id, tcx))
456     }
457
458     /// Return the "generator signature", which consists of its yield
459     /// and return types.
460     pub fn sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> GenSig<'tcx> {
461         ty::GenSig {
462             yield_ty: self.yield_ty(def_id, tcx),
463             return_ty: self.return_ty(def_id, tcx),
464         }
465     }
466 }
467
468 impl<'a, 'gcx, 'tcx> GeneratorSubsts<'tcx> {
469     /// This returns the types of the MIR locals which had to be stored across suspension points.
470     /// It is calculated in rustc_mir::transform::generator::StateTransform.
471     /// All the types here must be in the tuple in GeneratorInterior.
472     pub fn state_tys(
473         self,
474         def_id: DefId,
475         tcx: TyCtxt<'a, 'gcx, 'tcx>,
476     ) -> impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a {
477         let state = tcx.generator_layout(def_id).fields.iter();
478         state.map(move |d| d.ty.subst(tcx, self.substs))
479     }
480
481     /// This is the types of the fields of a generate which
482     /// is available before the generator transformation.
483     /// It includes the upvars and the state discriminant which is u32.
484     pub fn pre_transforms_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
485         impl Iterator<Item=Ty<'tcx>> + 'a
486     {
487         self.upvar_tys(def_id, tcx).chain(iter::once(tcx.types.u32))
488     }
489
490     /// This is the types of all the fields stored in a generator.
491     /// It includes the upvars, state types and the state discriminant which is u32.
492     pub fn field_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
493         impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a
494     {
495         self.pre_transforms_tys(def_id, tcx).chain(self.state_tys(def_id, tcx))
496     }
497 }
498
499 #[derive(Debug, Copy, Clone)]
500 pub enum UpvarSubsts<'tcx> {
501     Closure(ClosureSubsts<'tcx>),
502     Generator(GeneratorSubsts<'tcx>),
503 }
504
505 impl<'tcx> UpvarSubsts<'tcx> {
506     #[inline]
507     pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
508         impl Iterator<Item=Ty<'tcx>> + 'tcx
509     {
510         let upvar_kinds = match self {
511             UpvarSubsts::Closure(substs) => substs.split(def_id, tcx).upvar_kinds,
512             UpvarSubsts::Generator(substs) => substs.split(def_id, tcx).upvar_kinds,
513         };
514         upvar_kinds.iter().map(|t| {
515             if let UnpackedKind::Type(ty) = t.unpack() {
516                 ty
517             } else {
518                 bug!("upvar should be type")
519             }
520         })
521     }
522 }
523
524 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, RustcEncodable, RustcDecodable)]
525 pub enum ExistentialPredicate<'tcx> {
526     /// e.g. Iterator
527     Trait(ExistentialTraitRef<'tcx>),
528     /// e.g. Iterator::Item = T
529     Projection(ExistentialProjection<'tcx>),
530     /// e.g. Send
531     AutoTrait(DefId),
532 }
533
534 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
535     /// Compares via an ordering that will not change if modules are reordered or other changes are
536     /// made to the tree. In particular, this ordering is preserved across incremental compilations.
537     pub fn stable_cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
538         use self::ExistentialPredicate::*;
539         match (*self, *other) {
540             (Trait(_), Trait(_)) => Ordering::Equal,
541             (Projection(ref a), Projection(ref b)) =>
542                 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
543             (AutoTrait(ref a), AutoTrait(ref b)) =>
544                 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
545             (Trait(_), _) => Ordering::Less,
546             (Projection(_), Trait(_)) => Ordering::Greater,
547             (Projection(_), _) => Ordering::Less,
548             (AutoTrait(_), _) => Ordering::Greater,
549         }
550     }
551
552 }
553
554 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
555     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
556         -> ty::Predicate<'tcx> {
557         use ty::ToPredicate;
558         match *self.skip_binder() {
559             ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
560             ExistentialPredicate::Projection(p) =>
561                 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
562             ExistentialPredicate::AutoTrait(did) => {
563                 let trait_ref = Binder(ty::TraitRef {
564                     def_id: did,
565                     substs: tcx.mk_substs_trait(self_ty, &[]),
566                 });
567                 trait_ref.to_predicate()
568             }
569         }
570     }
571 }
572
573 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx List<ExistentialPredicate<'tcx>> {}
574
575 impl<'tcx> List<ExistentialPredicate<'tcx>> {
576     pub fn principal(&self) -> ExistentialTraitRef<'tcx> {
577         match self[0] {
578             ExistentialPredicate::Trait(tr) => tr,
579             other => bug!("first predicate is {:?}", other),
580         }
581     }
582
583     #[inline]
584     pub fn projection_bounds<'a>(&'a self) ->
585         impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
586         self.iter().filter_map(|predicate| {
587             match *predicate {
588                 ExistentialPredicate::Projection(p) => Some(p),
589                 _ => None,
590             }
591         })
592     }
593
594     #[inline]
595     pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
596         self.iter().filter_map(|predicate| {
597             match *predicate {
598                 ExistentialPredicate::AutoTrait(d) => Some(d),
599                 _ => None
600             }
601         })
602     }
603 }
604
605 impl<'tcx> Binder<&'tcx List<ExistentialPredicate<'tcx>>> {
606     pub fn principal(&self) -> PolyExistentialTraitRef<'tcx> {
607         Binder::bind(self.skip_binder().principal())
608     }
609
610     #[inline]
611     pub fn projection_bounds<'a>(&'a self) ->
612         impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
613         self.skip_binder().projection_bounds().map(Binder::bind)
614     }
615
616     #[inline]
617     pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
618         self.skip_binder().auto_traits()
619     }
620
621     pub fn iter<'a>(&'a self)
622         -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
623         self.skip_binder().iter().cloned().map(Binder::bind)
624     }
625 }
626
627 /// A complete reference to a trait. These take numerous guises in syntax,
628 /// but perhaps the most recognizable form is in a where clause:
629 ///
630 ///     T : Foo<U>
631 ///
632 /// This would be represented by a trait-reference where the def-id is the
633 /// def-id for the trait `Foo` and the substs define `T` as parameter 0,
634 /// and `U` as parameter 1.
635 ///
636 /// Trait references also appear in object types like `Foo<U>`, but in
637 /// that case the `Self` parameter is absent from the substitutions.
638 ///
639 /// Note that a `TraitRef` introduces a level of region binding, to
640 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
641 /// U>` or higher-ranked object types.
642 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
643 pub struct TraitRef<'tcx> {
644     pub def_id: DefId,
645     pub substs: &'tcx Substs<'tcx>,
646 }
647
648 impl<'tcx> TraitRef<'tcx> {
649     pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
650         TraitRef { def_id: def_id, substs: substs }
651     }
652
653     /// Returns a TraitRef of the form `P0: Foo<P1..Pn>` where `Pi`
654     /// are the parameters defined on trait.
655     pub fn identity<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, def_id: DefId) -> TraitRef<'tcx> {
656         TraitRef {
657             def_id,
658             substs: Substs::identity_for_item(tcx, def_id),
659         }
660     }
661
662     pub fn self_ty(&self) -> Ty<'tcx> {
663         self.substs.type_at(0)
664     }
665
666     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
667         // Select only the "input types" from a trait-reference. For
668         // now this is all the types that appear in the
669         // trait-reference, but it should eventually exclude
670         // associated types.
671         self.substs.types()
672     }
673
674     pub fn from_method(tcx: TyCtxt<'_, '_, 'tcx>,
675                        trait_id: DefId,
676                        substs: &Substs<'tcx>)
677                        -> ty::TraitRef<'tcx> {
678         let defs = tcx.generics_of(trait_id);
679
680         ty::TraitRef {
681             def_id: trait_id,
682             substs: tcx.intern_substs(&substs[..defs.params.len()])
683         }
684     }
685 }
686
687 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
688
689 impl<'tcx> PolyTraitRef<'tcx> {
690     pub fn self_ty(&self) -> Ty<'tcx> {
691         self.skip_binder().self_ty()
692     }
693
694     pub fn def_id(&self) -> DefId {
695         self.skip_binder().def_id
696     }
697
698     pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
699         // Note that we preserve binding levels
700         Binder(ty::TraitPredicate { trait_ref: self.skip_binder().clone() })
701     }
702 }
703
704 /// An existential reference to a trait, where `Self` is erased.
705 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
706 ///
707 ///     exists T. T: Trait<'a, 'b, X, Y>
708 ///
709 /// The substitutions don't include the erased `Self`, only trait
710 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
711 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
712 pub struct ExistentialTraitRef<'tcx> {
713     pub def_id: DefId,
714     pub substs: &'tcx Substs<'tcx>,
715 }
716
717 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
718     pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
719         // Select only the "input types" from a trait-reference. For
720         // now this is all the types that appear in the
721         // trait-reference, but it should eventually exclude
722         // associated types.
723         self.substs.types()
724     }
725
726     pub fn erase_self_ty(tcx: TyCtxt<'a, 'gcx, 'tcx>,
727                          trait_ref: ty::TraitRef<'tcx>)
728                          -> ty::ExistentialTraitRef<'tcx> {
729         // Assert there is a Self.
730         trait_ref.substs.type_at(0);
731
732         ty::ExistentialTraitRef {
733             def_id: trait_ref.def_id,
734             substs: tcx.intern_substs(&trait_ref.substs[1..])
735         }
736     }
737
738     /// Object types don't have a self-type specified. Therefore, when
739     /// we convert the principal trait-ref into a normal trait-ref,
740     /// you must give *some* self-type. A common choice is `mk_err()`
741     /// or some placeholder type.
742     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
743         -> ty::TraitRef<'tcx>  {
744         // otherwise the escaping vars would be captured by the binder
745         // debug_assert!(!self_ty.has_escaping_bound_vars());
746
747         ty::TraitRef {
748             def_id: self.def_id,
749             substs: tcx.mk_substs_trait(self_ty, self.substs)
750         }
751     }
752 }
753
754 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
755
756 impl<'tcx> PolyExistentialTraitRef<'tcx> {
757     pub fn def_id(&self) -> DefId {
758         self.skip_binder().def_id
759     }
760
761     /// Object types don't have a self-type specified. Therefore, when
762     /// we convert the principal trait-ref into a normal trait-ref,
763     /// you must give *some* self-type. A common choice is `mk_err()`
764     /// or some placeholder type.
765     pub fn with_self_ty(&self, tcx: TyCtxt<'_, '_, 'tcx>,
766                         self_ty: Ty<'tcx>)
767                         -> ty::PolyTraitRef<'tcx>  {
768         self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
769     }
770 }
771
772 /// Binder is a binder for higher-ranked lifetimes or types. It is part of the
773 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
774 /// (which would be represented by the type `PolyTraitRef ==
775 /// Binder<TraitRef>`). Note that when we instantiate,
776 /// erase, or otherwise "discharge" these bound vars, we change the
777 /// type from `Binder<T>` to just `T` (see
778 /// e.g. `liberate_late_bound_regions`).
779 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
780 pub struct Binder<T>(T);
781
782 impl<T> Binder<T> {
783     /// Wraps `value` in a binder, asserting that `value` does not
784     /// contain any bound vars that would be bound by the
785     /// binder. This is commonly used to 'inject' a value T into a
786     /// different binding level.
787     pub fn dummy<'tcx>(value: T) -> Binder<T>
788         where T: TypeFoldable<'tcx>
789     {
790         debug_assert!(!value.has_escaping_bound_vars());
791         Binder(value)
792     }
793
794     /// Wraps `value` in a binder, binding higher-ranked vars (if any).
795     pub fn bind<'tcx>(value: T) -> Binder<T> {
796         Binder(value)
797     }
798
799     /// Skips the binder and returns the "bound" value. This is a
800     /// risky thing to do because it's easy to get confused about
801     /// debruijn indices and the like. It is usually better to
802     /// discharge the binder using `no_late_bound_regions` or
803     /// `replace_late_bound_regions` or something like
804     /// that. `skip_binder` is only valid when you are either
805     /// extracting data that has nothing to do with bound regions, you
806     /// are doing some sort of test that does not involve bound
807     /// regions, or you are being very careful about your depth
808     /// accounting.
809     ///
810     /// Some examples where `skip_binder` is reasonable:
811     ///
812     /// - extracting the def-id from a PolyTraitRef;
813     /// - comparing the self type of a PolyTraitRef to see if it is equal to
814     ///   a type parameter `X`, since the type `X`  does not reference any regions
815     pub fn skip_binder(&self) -> &T {
816         &self.0
817     }
818
819     pub fn as_ref(&self) -> Binder<&T> {
820         Binder(&self.0)
821     }
822
823     pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
824         where F: FnOnce(&T) -> U
825     {
826         self.as_ref().map_bound(f)
827     }
828
829     pub fn map_bound<F, U>(self, f: F) -> Binder<U>
830         where F: FnOnce(T) -> U
831     {
832         Binder(f(self.0))
833     }
834
835     /// Unwraps and returns the value within, but only if it contains
836     /// no bound regions at all. (In other words, if this binder --
837     /// and indeed any enclosing binder -- doesn't bind anything at
838     /// all.) Otherwise, returns `None`.
839     ///
840     /// (One could imagine having a method that just unwraps a single
841     /// binder, but permits late-bound regions bound by enclosing
842     /// binders, but that would require adjusting the debruijn
843     /// indices, and given the shallow binding structure we often use,
844     /// would not be that useful.)
845     pub fn no_late_bound_regions<'tcx>(self) -> Option<T>
846         where T : TypeFoldable<'tcx>
847     {
848         if self.skip_binder().has_escaping_bound_vars() {
849             None
850         } else {
851             Some(self.skip_binder().clone())
852         }
853     }
854
855     /// Given two things that have the same binder level,
856     /// and an operation that wraps on their contents, execute the operation
857     /// and then wrap its result.
858     ///
859     /// `f` should consider bound regions at depth 1 to be free, and
860     /// anything it produces with bound regions at depth 1 will be
861     /// bound in the resulting return value.
862     pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
863         where F: FnOnce(T, U) -> R
864     {
865         Binder(f(self.0, u.0))
866     }
867
868     /// Split the contents into two things that share the same binder
869     /// level as the original, returning two distinct binders.
870     ///
871     /// `f` should consider bound regions at depth 1 to be free, and
872     /// anything it produces with bound regions at depth 1 will be
873     /// bound in the resulting return values.
874     pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
875         where F: FnOnce(T) -> (U, V)
876     {
877         let (u, v) = f(self.0);
878         (Binder(u), Binder(v))
879     }
880 }
881
882 /// Represents the projection of an associated type. In explicit UFCS
883 /// form this would be written `<T as Trait<..>>::N`.
884 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
885 pub struct ProjectionTy<'tcx> {
886     /// The parameters of the associated item.
887     pub substs: &'tcx Substs<'tcx>,
888
889     /// The DefId of the TraitItem for the associated type N.
890     ///
891     /// Note that this is not the DefId of the TraitRef containing this
892     /// associated type, which is in tcx.associated_item(item_def_id).container.
893     pub item_def_id: DefId,
894 }
895
896 impl<'a, 'tcx> ProjectionTy<'tcx> {
897     /// Construct a ProjectionTy by searching the trait from trait_ref for the
898     /// associated item named item_name.
899     pub fn from_ref_and_name(
900         tcx: TyCtxt<'_, '_, '_>, trait_ref: ty::TraitRef<'tcx>, item_name: Ident
901     ) -> ProjectionTy<'tcx> {
902         let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
903             item.kind == ty::AssociatedKind::Type &&
904             tcx.hygienic_eq(item_name, item.ident, trait_ref.def_id)
905         }).unwrap().def_id;
906
907         ProjectionTy {
908             substs: trait_ref.substs,
909             item_def_id,
910         }
911     }
912
913     /// Extracts the underlying trait reference from this projection.
914     /// For example, if this is a projection of `<T as Iterator>::Item`,
915     /// then this function would return a `T: Iterator` trait reference.
916     pub fn trait_ref(&self, tcx: TyCtxt<'_, '_, '_>) -> ty::TraitRef<'tcx> {
917         let def_id = tcx.associated_item(self.item_def_id).container.id();
918         ty::TraitRef {
919             def_id,
920             substs: self.substs,
921         }
922     }
923
924     pub fn self_ty(&self) -> Ty<'tcx> {
925         self.substs.type_at(0)
926     }
927 }
928
929 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
930 pub struct GenSig<'tcx> {
931     pub yield_ty: Ty<'tcx>,
932     pub return_ty: Ty<'tcx>,
933 }
934
935 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
936
937 impl<'tcx> PolyGenSig<'tcx> {
938     pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
939         self.map_bound_ref(|sig| sig.yield_ty)
940     }
941     pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
942         self.map_bound_ref(|sig| sig.return_ty)
943     }
944 }
945
946 /// Signature of a function type, which I have arbitrarily
947 /// decided to use to refer to the input/output types.
948 ///
949 /// - `inputs` is the list of arguments and their modes.
950 /// - `output` is the return type.
951 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
952 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
953 pub struct FnSig<'tcx> {
954     pub inputs_and_output: &'tcx List<Ty<'tcx>>,
955     pub variadic: bool,
956     pub unsafety: hir::Unsafety,
957     pub abi: abi::Abi,
958 }
959
960 impl<'tcx> FnSig<'tcx> {
961     pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
962         &self.inputs_and_output[..self.inputs_and_output.len() - 1]
963     }
964
965     pub fn output(&self) -> Ty<'tcx> {
966         self.inputs_and_output[self.inputs_and_output.len() - 1]
967     }
968 }
969
970 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
971
972 impl<'tcx> PolyFnSig<'tcx> {
973     pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
974         self.map_bound_ref(|fn_sig| fn_sig.inputs())
975     }
976     pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
977         self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
978     }
979     pub fn inputs_and_output(&self) -> ty::Binder<&'tcx List<Ty<'tcx>>> {
980         self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
981     }
982     pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
983         self.map_bound_ref(|fn_sig| fn_sig.output())
984     }
985     pub fn variadic(&self) -> bool {
986         self.skip_binder().variadic
987     }
988     pub fn unsafety(&self) -> hir::Unsafety {
989         self.skip_binder().unsafety
990     }
991     pub fn abi(&self) -> abi::Abi {
992         self.skip_binder().abi
993     }
994 }
995
996 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<FnSig<'tcx>>>;
997
998
999 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1000 pub struct ParamTy {
1001     pub idx: u32,
1002     pub name: InternedString,
1003 }
1004
1005 impl<'a, 'gcx, 'tcx> ParamTy {
1006     pub fn new(index: u32, name: InternedString) -> ParamTy {
1007         ParamTy { idx: index, name: name }
1008     }
1009
1010     pub fn for_self() -> ParamTy {
1011         ParamTy::new(0, keywords::SelfType.name().as_interned_str())
1012     }
1013
1014     pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1015         ParamTy::new(def.index, def.name)
1016     }
1017
1018     pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1019         tcx.mk_ty_param(self.idx, self.name)
1020     }
1021
1022     pub fn is_self(&self) -> bool {
1023         // FIXME(#50125): Ignoring `Self` with `idx != 0` might lead to weird behavior elsewhere,
1024         // but this should only be possible when using `-Z continue-parse-after-error` like
1025         // `compile-fail/issue-36638.rs`.
1026         self.name == keywords::SelfType.name().as_str() && self.idx == 0
1027     }
1028 }
1029
1030 /// A [De Bruijn index][dbi] is a standard means of representing
1031 /// regions (and perhaps later types) in a higher-ranked setting. In
1032 /// particular, imagine a type like this:
1033 ///
1034 ///     for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1035 ///     ^          ^            |        |         |
1036 ///     |          |            |        |         |
1037 ///     |          +------------+ 0      |         |
1038 ///     |                                |         |
1039 ///     +--------------------------------+ 1       |
1040 ///     |                                          |
1041 ///     +------------------------------------------+ 0
1042 ///
1043 /// In this type, there are two binders (the outer fn and the inner
1044 /// fn). We need to be able to determine, for any given region, which
1045 /// fn type it is bound by, the inner or the outer one. There are
1046 /// various ways you can do this, but a De Bruijn index is one of the
1047 /// more convenient and has some nice properties. The basic idea is to
1048 /// count the number of binders, inside out. Some examples should help
1049 /// clarify what I mean.
1050 ///
1051 /// Let's start with the reference type `&'b isize` that is the first
1052 /// argument to the inner function. This region `'b` is assigned a De
1053 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
1054 /// fn). The region `'a` that appears in the second argument type (`&'a
1055 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
1056 /// second-innermost binder". (These indices are written on the arrays
1057 /// in the diagram).
1058 ///
1059 /// What is interesting is that De Bruijn index attached to a particular
1060 /// variable will vary depending on where it appears. For example,
1061 /// the final type `&'a char` also refers to the region `'a` declared on
1062 /// the outermost fn. But this time, this reference is not nested within
1063 /// any other binders (i.e., it is not an argument to the inner fn, but
1064 /// rather the outer one). Therefore, in this case, it is assigned a
1065 /// De Bruijn index of 0, because the innermost binder in that location
1066 /// is the outer fn.
1067 ///
1068 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1069 newtype_index! {
1070     pub struct DebruijnIndex {
1071         DEBUG_FORMAT = "DebruijnIndex({})",
1072         const INNERMOST = 0,
1073     }
1074 }
1075
1076 pub type Region<'tcx> = &'tcx RegionKind;
1077
1078 /// Representation of regions.
1079 ///
1080 /// Unlike types, most region variants are "fictitious", not concrete,
1081 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1082 /// ones representing concrete regions.
1083 ///
1084 /// ## Bound Regions
1085 ///
1086 /// These are regions that are stored behind a binder and must be substituted
1087 /// with some concrete region before being used. There are 2 kind of
1088 /// bound regions: early-bound, which are bound in an item's Generics,
1089 /// and are substituted by a Substs,  and late-bound, which are part of
1090 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
1091 /// the likes of `liberate_late_bound_regions`. The distinction exists
1092 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1093 ///
1094 /// Unlike Param-s, bound regions are not supposed to exist "in the wild"
1095 /// outside their binder, e.g. in types passed to type inference, and
1096 /// should first be substituted (by placeholder regions, free regions,
1097 /// or region variables).
1098 ///
1099 /// ## Placeholder and Free Regions
1100 ///
1101 /// One often wants to work with bound regions without knowing their precise
1102 /// identity. For example, when checking a function, the lifetime of a borrow
1103 /// can end up being assigned to some region parameter. In these cases,
1104 /// it must be ensured that bounds on the region can't be accidentally
1105 /// assumed without being checked.
1106 ///
1107 /// To do this, we replace the bound regions with placeholder markers,
1108 /// which don't satisfy any relation not explicitly provided.
1109 ///
1110 /// There are 2 kinds of placeholder regions in rustc: `ReFree` and
1111 /// `RePlaceholder`. When checking an item's body, `ReFree` is supposed
1112 /// to be used. These also support explicit bounds: both the internally-stored
1113 /// *scope*, which the region is assumed to outlive, as well as other
1114 /// relations stored in the `FreeRegionMap`. Note that these relations
1115 /// aren't checked when you `make_subregion` (or `eq_types`), only by
1116 /// `resolve_regions_and_report_errors`.
1117 ///
1118 /// When working with higher-ranked types, some region relations aren't
1119 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1120 /// `RePlaceholder` is designed for this purpose. In these contexts,
1121 /// there's also the risk that some inference variable laying around will
1122 /// get unified with your placeholder region: if you want to check whether
1123 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1124 /// with a placeholder region `'%a`, the variable `'_` would just be
1125 /// instantiated to the placeholder region `'%a`, which is wrong because
1126 /// the inference variable is supposed to satisfy the relation
1127 /// *for every value of the placeholder region*. To ensure that doesn't
1128 /// happen, you can use `leak_check`. This is more clearly explained
1129 /// by the [rustc guide].
1130 ///
1131 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1132 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1133 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/traits/hrtb.html
1134 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1135 pub enum RegionKind {
1136     // Region bound in a type or fn declaration which will be
1137     // substituted 'early' -- that is, at the same time when type
1138     // parameters are substituted.
1139     ReEarlyBound(EarlyBoundRegion),
1140
1141     // Region bound in a function scope, which will be substituted when the
1142     // function is called.
1143     ReLateBound(DebruijnIndex, BoundRegion),
1144
1145     /// When checking a function body, the types of all arguments and so forth
1146     /// that refer to bound region parameters are modified to refer to free
1147     /// region parameters.
1148     ReFree(FreeRegion),
1149
1150     /// A concrete region naming some statically determined scope
1151     /// (e.g. an expression or sequence of statements) within the
1152     /// current function.
1153     ReScope(region::Scope),
1154
1155     /// Static data that has an "infinite" lifetime. Top in the region lattice.
1156     ReStatic,
1157
1158     /// A region variable.  Should not exist after typeck.
1159     ReVar(RegionVid),
1160
1161     /// A placeholder region - basically the higher-ranked version of ReFree.
1162     /// Should not exist after typeck.
1163     RePlaceholder(ty::Placeholder),
1164
1165     /// Empty lifetime is for data that is never accessed.
1166     /// Bottom in the region lattice. We treat ReEmpty somewhat
1167     /// specially; at least right now, we do not generate instances of
1168     /// it during the GLB computations, but rather
1169     /// generate an error instead. This is to improve error messages.
1170     /// The only way to get an instance of ReEmpty is to have a region
1171     /// variable with no constraints.
1172     ReEmpty,
1173
1174     /// Erased region, used by trait selection, in MIR and during codegen.
1175     ReErased,
1176
1177     /// These are regions bound in the "defining type" for a
1178     /// closure. They are used ONLY as part of the
1179     /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1180     /// See `ClosureRegionRequirements` for more details.
1181     ReClosureBound(RegionVid),
1182 }
1183
1184 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1185
1186 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1187 pub struct EarlyBoundRegion {
1188     pub def_id: DefId,
1189     pub index: u32,
1190     pub name: InternedString,
1191 }
1192
1193 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1194 pub struct TyVid {
1195     pub index: u32,
1196 }
1197
1198 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1199 pub struct IntVid {
1200     pub index: u32,
1201 }
1202
1203 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1204 pub struct FloatVid {
1205     pub index: u32,
1206 }
1207
1208 newtype_index! {
1209     pub struct RegionVid {
1210         DEBUG_FORMAT = custom,
1211     }
1212 }
1213
1214 impl Atom for RegionVid {
1215     fn index(self) -> usize {
1216         Idx::index(self)
1217     }
1218 }
1219
1220 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1221 pub enum InferTy {
1222     TyVar(TyVid),
1223     IntVar(IntVid),
1224     FloatVar(FloatVid),
1225
1226     /// A `FreshTy` is one that is generated as a replacement for an
1227     /// unbound type variable. This is convenient for caching etc. See
1228     /// `infer::freshen` for more details.
1229     FreshTy(u32),
1230     FreshIntTy(u32),
1231     FreshFloatTy(u32),
1232 }
1233
1234 newtype_index! {
1235     pub struct BoundVar { .. }
1236 }
1237
1238 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1239 pub struct BoundTy {
1240     pub index: DebruijnIndex,
1241     pub var: BoundVar,
1242     pub kind: BoundTyKind,
1243 }
1244
1245 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1246 pub enum BoundTyKind {
1247     Anon,
1248     Param(InternedString),
1249 }
1250
1251 impl_stable_hash_for!(struct BoundTy { index, var, kind });
1252 impl_stable_hash_for!(enum self::BoundTyKind { Anon, Param(a) });
1253
1254 impl BoundTy {
1255     pub fn new(index: DebruijnIndex, var: BoundVar) -> Self {
1256         BoundTy {
1257             index,
1258             var,
1259             kind: BoundTyKind::Anon,
1260         }
1261     }
1262 }
1263
1264 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1265 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1266 pub struct ExistentialProjection<'tcx> {
1267     pub item_def_id: DefId,
1268     pub substs: &'tcx Substs<'tcx>,
1269     pub ty: Ty<'tcx>,
1270 }
1271
1272 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1273
1274 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1275     /// Extracts the underlying existential trait reference from this projection.
1276     /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1277     /// then this function would return a `exists T. T: Iterator` existential trait
1278     /// reference.
1279     pub fn trait_ref(&self, tcx: TyCtxt<'_, '_, '_>) -> ty::ExistentialTraitRef<'tcx> {
1280         let def_id = tcx.associated_item(self.item_def_id).container.id();
1281         ty::ExistentialTraitRef{
1282             def_id,
1283             substs: self.substs,
1284         }
1285     }
1286
1287     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1288                         self_ty: Ty<'tcx>)
1289                         -> ty::ProjectionPredicate<'tcx>
1290     {
1291         // otherwise the escaping regions would be captured by the binders
1292         debug_assert!(!self_ty.has_escaping_bound_vars());
1293
1294         ty::ProjectionPredicate {
1295             projection_ty: ty::ProjectionTy {
1296                 item_def_id: self.item_def_id,
1297                 substs: tcx.mk_substs_trait(self_ty, self.substs),
1298             },
1299             ty: self.ty,
1300         }
1301     }
1302 }
1303
1304 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
1305     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
1306         -> ty::PolyProjectionPredicate<'tcx> {
1307         self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1308     }
1309
1310     pub fn item_def_id(&self) -> DefId {
1311         return self.skip_binder().item_def_id;
1312     }
1313 }
1314
1315 impl DebruijnIndex {
1316     /// Returns the resulting index when this value is moved into
1317     /// `amount` number of new binders. So e.g. if you had
1318     ///
1319     ///    for<'a> fn(&'a x)
1320     ///
1321     /// and you wanted to change to
1322     ///
1323     ///    for<'a> fn(for<'b> fn(&'a x))
1324     ///
1325     /// you would need to shift the index for `'a` into 1 new binder.
1326     #[must_use]
1327     pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
1328         DebruijnIndex::from_u32(self.as_u32() + amount)
1329     }
1330
1331     /// Update this index in place by shifting it "in" through
1332     /// `amount` number of binders.
1333     pub fn shift_in(&mut self, amount: u32) {
1334         *self = self.shifted_in(amount);
1335     }
1336
1337     /// Returns the resulting index when this value is moved out from
1338     /// `amount` number of new binders.
1339     #[must_use]
1340     pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
1341         DebruijnIndex::from_u32(self.as_u32() - amount)
1342     }
1343
1344     /// Update in place by shifting out from `amount` binders.
1345     pub fn shift_out(&mut self, amount: u32) {
1346         *self = self.shifted_out(amount);
1347     }
1348
1349     /// Adjusts any Debruijn Indices so as to make `to_binder` the
1350     /// innermost binder. That is, if we have something bound at `to_binder`,
1351     /// it will now be bound at INNERMOST. This is an appropriate thing to do
1352     /// when moving a region out from inside binders:
1353     ///
1354     /// ```
1355     ///             for<'a>   fn(for<'b>   for<'c>   fn(&'a u32), _)
1356     /// // Binder:  D3           D2        D1            ^^
1357     /// ```
1358     ///
1359     /// Here, the region `'a` would have the debruijn index D3,
1360     /// because it is the bound 3 binders out. However, if we wanted
1361     /// to refer to that region `'a` in the second argument (the `_`),
1362     /// those two binders would not be in scope. In that case, we
1363     /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1364     /// debruijn index of `'a` to D1 (the innermost binder).
1365     ///
1366     /// If we invoke `shift_out_to_binder` and the region is in fact
1367     /// bound by one of the binders we are shifting out of, that is an
1368     /// error (and should fail an assertion failure).
1369     pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
1370         self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
1371     }
1372 }
1373
1374 impl_stable_hash_for!(struct DebruijnIndex { private });
1375
1376 /// Region utilities
1377 impl RegionKind {
1378     /// Is this region named by the user?
1379     pub fn has_name(&self) -> bool {
1380         match *self {
1381             RegionKind::ReEarlyBound(ebr) => ebr.has_name(),
1382             RegionKind::ReLateBound(_, br) => br.is_named(),
1383             RegionKind::ReFree(fr) => fr.bound_region.is_named(),
1384             RegionKind::ReScope(..) => false,
1385             RegionKind::ReStatic => true,
1386             RegionKind::ReVar(..) => false,
1387             RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(),
1388             RegionKind::ReEmpty => false,
1389             RegionKind::ReErased => false,
1390             RegionKind::ReClosureBound(..) => false,
1391         }
1392     }
1393
1394     pub fn is_late_bound(&self) -> bool {
1395         match *self {
1396             ty::ReLateBound(..) => true,
1397             _ => false,
1398         }
1399     }
1400
1401     pub fn bound_at_or_above_binder(&self, index: DebruijnIndex) -> bool {
1402         match *self {
1403             ty::ReLateBound(debruijn, _) => debruijn >= index,
1404             _ => false,
1405         }
1406     }
1407
1408     /// Adjusts any Debruijn Indices so as to make `to_binder` the
1409     /// innermost binder. That is, if we have something bound at `to_binder`,
1410     /// it will now be bound at INNERMOST. This is an appropriate thing to do
1411     /// when moving a region out from inside binders:
1412     ///
1413     /// ```
1414     ///             for<'a>   fn(for<'b>   for<'c>   fn(&'a u32), _)
1415     /// // Binder:  D3           D2        D1            ^^
1416     /// ```
1417     ///
1418     /// Here, the region `'a` would have the debruijn index D3,
1419     /// because it is the bound 3 binders out. However, if we wanted
1420     /// to refer to that region `'a` in the second argument (the `_`),
1421     /// those two binders would not be in scope. In that case, we
1422     /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1423     /// debruijn index of `'a` to D1 (the innermost binder).
1424     ///
1425     /// If we invoke `shift_out_to_binder` and the region is in fact
1426     /// bound by one of the binders we are shifting out of, that is an
1427     /// error (and should fail an assertion failure).
1428     pub fn shifted_out_to_binder(&self, to_binder: ty::DebruijnIndex) -> RegionKind {
1429         match *self {
1430             ty::ReLateBound(debruijn, r) => ty::ReLateBound(
1431                 debruijn.shifted_out_to_binder(to_binder),
1432                 r,
1433             ),
1434             r => r
1435         }
1436     }
1437
1438     pub fn keep_in_local_tcx(&self) -> bool {
1439         if let ty::ReVar(..) = self {
1440             true
1441         } else {
1442             false
1443         }
1444     }
1445
1446     pub fn type_flags(&self) -> TypeFlags {
1447         let mut flags = TypeFlags::empty();
1448
1449         if self.keep_in_local_tcx() {
1450             flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1451         }
1452
1453         match *self {
1454             ty::ReVar(..) => {
1455                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1456                 flags = flags | TypeFlags::HAS_RE_INFER;
1457             }
1458             ty::RePlaceholder(..) => {
1459                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1460                 flags = flags | TypeFlags::HAS_RE_SKOL;
1461             }
1462             ty::ReLateBound(..) => {
1463                 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1464             }
1465             ty::ReEarlyBound(..) => {
1466                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1467                 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1468             }
1469             ty::ReEmpty |
1470             ty::ReStatic |
1471             ty::ReFree { .. } |
1472             ty::ReScope { .. } => {
1473                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1474             }
1475             ty::ReErased => {
1476             }
1477             ty::ReClosureBound(..) => {
1478                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1479             }
1480         }
1481
1482         match *self {
1483             ty::ReStatic | ty::ReEmpty | ty::ReErased | ty::ReLateBound(..) => (),
1484             _ => flags = flags | TypeFlags::HAS_FREE_LOCAL_NAMES,
1485         }
1486
1487         debug!("type_flags({:?}) = {:?}", self, flags);
1488
1489         flags
1490     }
1491
1492     /// Given an early-bound or free region, returns the def-id where it was bound.
1493     /// For example, consider the regions in this snippet of code:
1494     ///
1495     /// ```
1496     /// impl<'a> Foo {
1497     ///      ^^ -- early bound, declared on an impl
1498     ///
1499     ///     fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1500     ///            ^^  ^^     ^ anonymous, late-bound
1501     ///            |   early-bound, appears in where-clauses
1502     ///            late-bound, appears only in fn args
1503     ///     {..}
1504     /// }
1505     /// ```
1506     ///
1507     /// Here, `free_region_binding_scope('a)` would return the def-id
1508     /// of the impl, and for all the other highlighted regions, it
1509     /// would return the def-id of the function. In other cases (not shown), this
1510     /// function might return the def-id of a closure.
1511     pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_, '_, '_>) -> DefId {
1512         match self {
1513             ty::ReEarlyBound(br) => {
1514                 tcx.parent_def_id(br.def_id).unwrap()
1515             }
1516             ty::ReFree(fr) => fr.scope,
1517             _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1518         }
1519     }
1520 }
1521
1522 /// Type utilities
1523 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
1524     pub fn is_unit(&self) -> bool {
1525         match self.sty {
1526             Tuple(ref tys) => tys.is_empty(),
1527             _ => false,
1528         }
1529     }
1530
1531     pub fn is_never(&self) -> bool {
1532         match self.sty {
1533             Never => true,
1534             _ => false,
1535         }
1536     }
1537
1538     pub fn is_primitive(&self) -> bool {
1539         match self.sty {
1540             Bool | Char | Int(_) | Uint(_) | Float(_) => true,
1541             _ => false,
1542         }
1543     }
1544
1545     pub fn is_ty_var(&self) -> bool {
1546         match self.sty {
1547             Infer(TyVar(_)) => true,
1548             _ => false,
1549         }
1550     }
1551
1552     pub fn is_ty_infer(&self) -> bool {
1553         match self.sty {
1554             Infer(_) => true,
1555             _ => false,
1556         }
1557     }
1558
1559     pub fn is_phantom_data(&self) -> bool {
1560         if let Adt(def, _) = self.sty {
1561             def.is_phantom_data()
1562         } else {
1563             false
1564         }
1565     }
1566
1567     pub fn is_bool(&self) -> bool { self.sty == Bool }
1568
1569     pub fn is_param(&self, index: u32) -> bool {
1570         match self.sty {
1571             ty::Param(ref data) => data.idx == index,
1572             _ => false,
1573         }
1574     }
1575
1576     pub fn is_self(&self) -> bool {
1577         match self.sty {
1578             Param(ref p) => p.is_self(),
1579             _ => false,
1580         }
1581     }
1582
1583     pub fn is_slice(&self) -> bool {
1584         match self.sty {
1585             RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => match ty.sty {
1586                 Slice(_) | Str => true,
1587                 _ => false,
1588             },
1589             _ => false
1590         }
1591     }
1592
1593     #[inline]
1594     pub fn is_simd(&self) -> bool {
1595         match self.sty {
1596             Adt(def, _) => def.repr.simd(),
1597             _ => false,
1598         }
1599     }
1600
1601     pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1602         match self.sty {
1603             Array(ty, _) | Slice(ty) => ty,
1604             Str => tcx.mk_mach_uint(ast::UintTy::U8),
1605             _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1606         }
1607     }
1608
1609     pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1610         match self.sty {
1611             Adt(def, substs) => {
1612                 def.non_enum_variant().fields[0].ty(tcx, substs)
1613             }
1614             _ => bug!("simd_type called on invalid type")
1615         }
1616     }
1617
1618     pub fn simd_size(&self, _cx: TyCtxt<'_, '_, '_>) -> usize {
1619         match self.sty {
1620             Adt(def, _) => def.non_enum_variant().fields.len(),
1621             _ => bug!("simd_size called on invalid type")
1622         }
1623     }
1624
1625     pub fn is_region_ptr(&self) -> bool {
1626         match self.sty {
1627             Ref(..) => true,
1628             _ => false,
1629         }
1630     }
1631
1632     pub fn is_mutable_pointer(&self) -> bool {
1633         match self.sty {
1634             RawPtr(TypeAndMut { mutbl: hir::Mutability::MutMutable, .. }) |
1635             Ref(_, _, hir::Mutability::MutMutable) => true,
1636             _ => false
1637         }
1638     }
1639
1640     pub fn is_unsafe_ptr(&self) -> bool {
1641         match self.sty {
1642             RawPtr(_) => return true,
1643             _ => return false,
1644         }
1645     }
1646
1647     /// Returns `true` if this type is an `Arc<T>`.
1648     pub fn is_arc(&self) -> bool {
1649         match self.sty {
1650             Adt(def, _) => def.is_arc(),
1651             _ => false,
1652         }
1653     }
1654
1655     /// Returns `true` if this type is an `Rc<T>`.
1656     pub fn is_rc(&self) -> bool {
1657         match self.sty {
1658             Adt(def, _) => def.is_rc(),
1659             _ => false,
1660         }
1661     }
1662
1663     pub fn is_box(&self) -> bool {
1664         match self.sty {
1665             Adt(def, _) => def.is_box(),
1666             _ => false,
1667         }
1668     }
1669
1670     /// panics if called on any type other than `Box<T>`
1671     pub fn boxed_ty(&self) -> Ty<'tcx> {
1672         match self.sty {
1673             Adt(def, substs) if def.is_box() => substs.type_at(0),
1674             _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1675         }
1676     }
1677
1678     /// A scalar type is one that denotes an atomic datum, with no sub-components.
1679     /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1680     /// contents are abstract to rustc.)
1681     pub fn is_scalar(&self) -> bool {
1682         match self.sty {
1683             Bool | Char | Int(_) | Float(_) | Uint(_) |
1684             Infer(IntVar(_)) | Infer(FloatVar(_)) |
1685             FnDef(..) | FnPtr(_) | RawPtr(_) => true,
1686             _ => false
1687         }
1688     }
1689
1690     /// Returns true if this type is a floating point type and false otherwise.
1691     pub fn is_floating_point(&self) -> bool {
1692         match self.sty {
1693             Float(_) |
1694             Infer(FloatVar(_)) => true,
1695             _ => false,
1696         }
1697     }
1698
1699     pub fn is_trait(&self) -> bool {
1700         match self.sty {
1701             Dynamic(..) => true,
1702             _ => false,
1703         }
1704     }
1705
1706     pub fn is_enum(&self) -> bool {
1707         match self.sty {
1708             Adt(adt_def, _) => {
1709                 adt_def.is_enum()
1710             }
1711             _ => false,
1712         }
1713     }
1714
1715     pub fn is_closure(&self) -> bool {
1716         match self.sty {
1717             Closure(..) => true,
1718             _ => false,
1719         }
1720     }
1721
1722     pub fn is_generator(&self) -> bool {
1723         match self.sty {
1724             Generator(..) => true,
1725             _ => false,
1726         }
1727     }
1728
1729     pub fn is_integral(&self) -> bool {
1730         match self.sty {
1731             Infer(IntVar(_)) | Int(_) | Uint(_) => true,
1732             _ => false
1733         }
1734     }
1735
1736     pub fn is_fresh_ty(&self) -> bool {
1737         match self.sty {
1738             Infer(FreshTy(_)) => true,
1739             _ => false,
1740         }
1741     }
1742
1743     pub fn is_fresh(&self) -> bool {
1744         match self.sty {
1745             Infer(FreshTy(_)) => true,
1746             Infer(FreshIntTy(_)) => true,
1747             Infer(FreshFloatTy(_)) => true,
1748             _ => false,
1749         }
1750     }
1751
1752     pub fn is_char(&self) -> bool {
1753         match self.sty {
1754             Char => true,
1755             _ => false,
1756         }
1757     }
1758
1759     pub fn is_fp(&self) -> bool {
1760         match self.sty {
1761             Infer(FloatVar(_)) | Float(_) => true,
1762             _ => false
1763         }
1764     }
1765
1766     pub fn is_numeric(&self) -> bool {
1767         self.is_integral() || self.is_fp()
1768     }
1769
1770     pub fn is_signed(&self) -> bool {
1771         match self.sty {
1772             Int(_) => true,
1773             _ => false,
1774         }
1775     }
1776
1777     pub fn is_machine(&self) -> bool {
1778         match self.sty {
1779             Int(ast::IntTy::Isize) | Uint(ast::UintTy::Usize) => false,
1780             Int(..) | Uint(..) | Float(..) => true,
1781             _ => false,
1782         }
1783     }
1784
1785     pub fn has_concrete_skeleton(&self) -> bool {
1786         match self.sty {
1787             Param(_) | Infer(_) | Error => false,
1788             _ => true,
1789         }
1790     }
1791
1792     /// Returns the type and mutability of *ty.
1793     ///
1794     /// The parameter `explicit` indicates if this is an *explicit* dereference.
1795     /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1796     pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1797         match self.sty {
1798             Adt(def, _) if def.is_box() => {
1799                 Some(TypeAndMut {
1800                     ty: self.boxed_ty(),
1801                     mutbl: hir::MutImmutable,
1802                 })
1803             },
1804             Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
1805             RawPtr(mt) if explicit => Some(mt),
1806             _ => None,
1807         }
1808     }
1809
1810     /// Returns the type of `ty[i]`.
1811     pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1812         match self.sty {
1813             Array(ty, _) | Slice(ty) => Some(ty),
1814             _ => None,
1815         }
1816     }
1817
1818     pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1819         match self.sty {
1820             FnDef(def_id, substs) => {
1821                 tcx.fn_sig(def_id).subst(tcx, substs)
1822             }
1823             FnPtr(f) => f,
1824             _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1825         }
1826     }
1827
1828     pub fn is_fn(&self) -> bool {
1829         match self.sty {
1830             FnDef(..) | FnPtr(_) => true,
1831             _ => false,
1832         }
1833     }
1834
1835     pub fn is_impl_trait(&self) -> bool {
1836         match self.sty {
1837             Opaque(..) => true,
1838             _ => false,
1839         }
1840     }
1841
1842     pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1843         match self.sty {
1844             Adt(adt, _) => Some(adt),
1845             _ => None,
1846         }
1847     }
1848
1849     /// Returns the regions directly referenced from this type (but
1850     /// not types reachable from this type via `walk_tys`). This
1851     /// ignores late-bound regions binders.
1852     pub fn regions(&self) -> Vec<ty::Region<'tcx>> {
1853         match self.sty {
1854             Ref(region, _, _) => {
1855                 vec![region]
1856             }
1857             Dynamic(ref obj, region) => {
1858                 let mut v = vec![region];
1859                 v.extend(obj.principal().skip_binder().substs.regions());
1860                 v
1861             }
1862             Adt(_, substs) | Opaque(_, substs) => {
1863                 substs.regions().collect()
1864             }
1865             Closure(_, ClosureSubsts { ref substs }) |
1866             Generator(_, GeneratorSubsts { ref substs }, _) => {
1867                 substs.regions().collect()
1868             }
1869             Projection(ref data) | UnnormalizedProjection(ref data) => {
1870                 data.substs.regions().collect()
1871             }
1872             FnDef(..) |
1873             FnPtr(_) |
1874             GeneratorWitness(..) |
1875             Bool |
1876             Char |
1877             Int(_) |
1878             Uint(_) |
1879             Float(_) |
1880             Str |
1881             Array(..) |
1882             Slice(_) |
1883             RawPtr(_) |
1884             Never |
1885             Tuple(..) |
1886             Foreign(..) |
1887             Param(_) |
1888             Bound(..) |
1889             Infer(_) |
1890             Error => {
1891                 vec![]
1892             }
1893         }
1894     }
1895
1896     /// When we create a closure, we record its kind (i.e., what trait
1897     /// it implements) into its `ClosureSubsts` using a type
1898     /// parameter. This is kind of a phantom type, except that the
1899     /// most convenient thing for us to are the integral types. This
1900     /// function converts such a special type into the closure
1901     /// kind. To go the other way, use
1902     /// `tcx.closure_kind_ty(closure_kind)`.
1903     ///
1904     /// Note that during type checking, we use an inference variable
1905     /// to represent the closure kind, because it has not yet been
1906     /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
1907     /// is complete, that type variable will be unified.
1908     pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
1909         match self.sty {
1910             Int(int_ty) => match int_ty {
1911                 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
1912                 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1913                 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1914                 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1915             },
1916
1917             Infer(_) => None,
1918
1919             Error => Some(ty::ClosureKind::Fn),
1920
1921             _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1922         }
1923     }
1924
1925     /// Fast path helper for testing if a type is `Sized`.
1926     ///
1927     /// Returning true means the type is known to be sized. Returning
1928     /// `false` means nothing -- could be sized, might not be.
1929     pub fn is_trivially_sized(&self, tcx: TyCtxt<'_, '_, 'tcx>) -> bool {
1930         match self.sty {
1931             ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
1932             ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
1933             ty::FnDef(..) | ty::FnPtr(_) | ty::RawPtr(..) |
1934             ty::Char | ty::Ref(..) | ty::Generator(..) |
1935             ty::GeneratorWitness(..) | ty::Array(..) | ty::Closure(..) |
1936             ty::Never | ty::Error =>
1937                 true,
1938
1939             ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) =>
1940                 false,
1941
1942             ty::Tuple(tys) =>
1943                 tys.iter().all(|ty| ty.is_trivially_sized(tcx)),
1944
1945             ty::Adt(def, _substs) =>
1946                 def.sized_constraint(tcx).is_empty(),
1947
1948             ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
1949
1950             ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
1951
1952             ty::Infer(ty::TyVar(_)) => false,
1953
1954             ty::Bound(_) |
1955             ty::Infer(ty::FreshTy(_)) |
1956             ty::Infer(ty::FreshIntTy(_)) |
1957             ty::Infer(ty::FreshFloatTy(_)) =>
1958                 bug!("is_trivially_sized applied to unexpected type: {:?}", self),
1959         }
1960     }
1961 }
1962
1963 /// Typed constant value.
1964 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Eq, PartialEq, Ord, PartialOrd)]
1965 pub struct Const<'tcx> {
1966     pub ty: Ty<'tcx>,
1967
1968     pub val: ConstValue<'tcx>,
1969 }
1970
1971 impl<'tcx> Const<'tcx> {
1972     pub fn unevaluated(
1973         tcx: TyCtxt<'_, '_, 'tcx>,
1974         def_id: DefId,
1975         substs: &'tcx Substs<'tcx>,
1976         ty: Ty<'tcx>,
1977     ) -> &'tcx Self {
1978         tcx.mk_const(Const {
1979             val: ConstValue::Unevaluated(def_id, substs),
1980             ty,
1981         })
1982     }
1983
1984     #[inline]
1985     pub fn from_const_value(
1986         tcx: TyCtxt<'_, '_, 'tcx>,
1987         val: ConstValue<'tcx>,
1988         ty: Ty<'tcx>,
1989     ) -> &'tcx Self {
1990         tcx.mk_const(Const {
1991             val,
1992             ty,
1993         })
1994     }
1995
1996     #[inline]
1997     pub fn from_scalar(
1998         tcx: TyCtxt<'_, '_, 'tcx>,
1999         val: Scalar,
2000         ty: Ty<'tcx>,
2001     ) -> &'tcx Self {
2002         Self::from_const_value(tcx, ConstValue::Scalar(val), ty)
2003     }
2004
2005     #[inline]
2006     pub fn from_bits(
2007         tcx: TyCtxt<'_, '_, 'tcx>,
2008         bits: u128,
2009         ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2010     ) -> &'tcx Self {
2011         let ty = tcx.lift_to_global(&ty).unwrap();
2012         let size = tcx.layout_of(ty).unwrap_or_else(|e| {
2013             panic!("could not compute layout for {:?}: {:?}", ty, e)
2014         }).size;
2015         let shift = 128 - size.bits();
2016         let truncated = (bits << shift) >> shift;
2017         assert_eq!(truncated, bits, "from_bits called with untruncated value");
2018         Self::from_scalar(tcx, Scalar::Bits { bits, size: size.bytes() as u8 }, ty.value)
2019     }
2020
2021     #[inline]
2022     pub fn zero_sized(tcx: TyCtxt<'_, '_, 'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
2023         Self::from_scalar(tcx, Scalar::Bits { bits: 0, size: 0 }, ty)
2024     }
2025
2026     #[inline]
2027     pub fn from_bool(tcx: TyCtxt<'_, '_, 'tcx>, v: bool) -> &'tcx Self {
2028         Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
2029     }
2030
2031     #[inline]
2032     pub fn from_usize(tcx: TyCtxt<'_, '_, 'tcx>, n: u64) -> &'tcx Self {
2033         Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
2034     }
2035
2036     #[inline]
2037     pub fn to_bits(
2038         &self,
2039         tcx: TyCtxt<'_, '_, 'tcx>,
2040         ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2041     ) -> Option<u128> {
2042         if self.ty != ty.value {
2043             return None;
2044         }
2045         let ty = tcx.lift_to_global(&ty).unwrap();
2046         let size = tcx.layout_of(ty).ok()?.size;
2047         self.val.try_to_bits(size)
2048     }
2049
2050     #[inline]
2051     pub fn to_ptr(&self) -> Option<Pointer> {
2052         self.val.try_to_ptr()
2053     }
2054
2055     #[inline]
2056     pub fn assert_bits(
2057         &self,
2058         tcx: TyCtxt<'_, '_, '_>,
2059         ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2060     ) -> Option<u128> {
2061         assert_eq!(self.ty, ty.value);
2062         let ty = tcx.lift_to_global(&ty).unwrap();
2063         let size = tcx.layout_of(ty).ok()?.size;
2064         self.val.try_to_bits(size)
2065     }
2066
2067     #[inline]
2068     pub fn assert_bool(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<bool> {
2069         self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.bool)).and_then(|v| match v {
2070             0 => Some(false),
2071             1 => Some(true),
2072             _ => None,
2073         })
2074     }
2075
2076     #[inline]
2077     pub fn assert_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<u64> {
2078         self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.usize)).map(|v| v as u64)
2079     }
2080
2081     #[inline]
2082     pub fn unwrap_bits(
2083         &self,
2084         tcx: TyCtxt<'_, '_, '_>,
2085         ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2086     ) -> u128 {
2087         self.assert_bits(tcx, ty).unwrap_or_else(||
2088             bug!("expected bits of {}, got {:#?}", ty.value, self))
2089     }
2090
2091     #[inline]
2092     pub fn unwrap_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> u64 {
2093         self.assert_usize(tcx).unwrap_or_else(||
2094             bug!("expected constant usize, got {:#?}", self))
2095     }
2096 }
2097
2098 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}