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