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