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