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