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