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