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