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