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