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