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