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