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