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