]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/sty.rs
Fix conversion from Miri Value to ConstValue
[rust.git] / src / librustc / ty / sty.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! This module contains TypeVariants and its major components
12
13 use hir::def_id::DefId;
14
15 use middle::const_val::ConstVal;
16 use middle::region;
17 use rustc_data_structures::indexed_vec::Idx;
18 use ty::subst::{Substs, Subst, Kind, UnpackedKind};
19 use ty::{self, AdtDef, TypeFlags, Ty, TyCtxt, TypeFoldable};
20 use ty::{Slice, TyS};
21 use util::captures::Captures;
22 use mir::interpret::{Allocation, PrimVal, MemoryPointer, Value, ConstValue};
23
24 use std::iter;
25 use std::cmp::Ordering;
26 use rustc_target::spec::abi;
27 use syntax::ast::{self, Name};
28 use syntax::symbol::{keywords, InternedString};
29
30 use serialize;
31
32 use hir;
33
34 use self::InferTy::*;
35 use self::TypeVariants::*;
36
37 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
38 pub struct TypeAndMut<'tcx> {
39     pub ty: Ty<'tcx>,
40     pub mutbl: hir::Mutability,
41 }
42
43 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
44          RustcEncodable, RustcDecodable, Copy)]
45 /// A "free" region `fr` can be interpreted as "some region
46 /// at least as big as the scope `fr.scope`".
47 pub struct FreeRegion {
48     pub scope: DefId,
49     pub bound_region: BoundRegion,
50 }
51
52 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
53          RustcEncodable, RustcDecodable, Copy)]
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 def-id is needed to distinguish free regions in
61     /// the event of shadowing.
62     BrNamed(DefId, InternedString),
63
64     /// Fresh bound identifiers created during GLB computations.
65     BrFresh(u32),
66
67     /// Anonymous region for the implicit env pointer parameter
68     /// to a closure
69     BrEnv,
70 }
71
72 impl BoundRegion {
73     pub fn is_named(&self) -> bool {
74         match *self {
75             BoundRegion::BrNamed(..) => true,
76             _ => false,
77         }
78     }
79 }
80
81 /// NB: If you change this, you'll probably want to change the corresponding
82 /// AST structure in libsyntax/ast.rs as well.
83 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
84 pub enum TypeVariants<'tcx> {
85     /// The primitive boolean type. Written as `bool`.
86     TyBool,
87
88     /// The primitive character type; holds a Unicode scalar value
89     /// (a non-surrogate code point).  Written as `char`.
90     TyChar,
91
92     /// A primitive signed integer type. For example, `i32`.
93     TyInt(ast::IntTy),
94
95     /// A primitive unsigned integer type. For example, `u32`.
96     TyUint(ast::UintTy),
97
98     /// A primitive floating-point type. For example, `f64`.
99     TyFloat(ast::FloatTy),
100
101     /// Structures, enumerations and unions.
102     ///
103     /// Substs here, possibly against intuition, *may* contain `TyParam`s.
104     /// That is, even after substitution it is possible that there are type
105     /// variables. This happens when the `TyAdt` corresponds to an ADT
106     /// definition and not a concrete use of it.
107     TyAdt(&'tcx AdtDef, &'tcx Substs<'tcx>),
108
109     TyForeign(DefId),
110
111     /// The pointee of a string slice. Written as `str`.
112     TyStr,
113
114     /// An array with the given length. Written as `[T; n]`.
115     TyArray(Ty<'tcx>, &'tcx ty::Const<'tcx>),
116
117     /// The pointee of an array slice.  Written as `[T]`.
118     TySlice(Ty<'tcx>),
119
120     /// A raw pointer. Written as `*mut T` or `*const T`
121     TyRawPtr(TypeAndMut<'tcx>),
122
123     /// A reference; a pointer with an associated lifetime. Written as
124     /// `&'a mut T` or `&'a T`.
125     TyRef(Region<'tcx>, Ty<'tcx>, hir::Mutability),
126
127     /// The anonymous type of a function declaration/definition. Each
128     /// function has a unique type.
129     TyFnDef(DefId, &'tcx Substs<'tcx>),
130
131     /// A pointer to a function.  Written as `fn() -> i32`.
132     TyFnPtr(PolyFnSig<'tcx>),
133
134     /// A trait, defined with `trait`.
135     TyDynamic(Binder<&'tcx Slice<ExistentialPredicate<'tcx>>>, ty::Region<'tcx>),
136
137     /// The anonymous type of a closure. Used to represent the type of
138     /// `|a| a`.
139     TyClosure(DefId, ClosureSubsts<'tcx>),
140
141     /// The anonymous type of a generator. Used to represent the type of
142     /// `|a| yield a`.
143     TyGenerator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
144
145     /// A type representin the types stored inside a generator.
146     /// This should only appear in GeneratorInteriors.
147     TyGeneratorWitness(Binder<&'tcx Slice<Ty<'tcx>>>),
148
149     /// The never type `!`
150     TyNever,
151
152     /// A tuple type.  For example, `(i32, bool)`.
153     TyTuple(&'tcx Slice<Ty<'tcx>>),
154
155     /// The projection of an associated type.  For example,
156     /// `<T as Trait<..>>::N`.
157     TyProjection(ProjectionTy<'tcx>),
158
159     /// Anonymized (`impl Trait`) type found in a return type.
160     /// The DefId comes from the `impl Trait` ast::Ty node, and the
161     /// substitutions are for the generics of the function in question.
162     /// After typeck, the concrete type can be found in the `types` map.
163     TyAnon(DefId, &'tcx Substs<'tcx>),
164
165     /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
166     TyParam(ParamTy),
167
168     /// A type variable used during type-checking.
169     TyInfer(InferTy),
170
171     /// A placeholder for a type which could not be computed; this is
172     /// propagated to avoid useless error messages.
173     TyError,
174 }
175
176 /// A closure can be modeled as a struct that looks like:
177 ///
178 ///     struct Closure<'l0...'li, T0...Tj, CK, CS, U0...Uk> {
179 ///         upvar0: U0,
180 ///         ...
181 ///         upvark: Uk
182 ///     }
183 ///
184 /// where:
185 ///
186 /// - 'l0...'li and T0...Tj are the lifetime and type parameters
187 ///   in scope on the function that defined the closure,
188 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
189 ///   is rather hackily encoded via a scalar type. See
190 ///   `TyS::to_opt_closure_kind` for details.
191 /// - CS represents the *closure signature*, representing as a `fn()`
192 ///   type. For example, `fn(u32, u32) -> u32` would mean that the closure
193 ///   implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
194 ///   specified above.
195 /// - U0...Uk are type parameters representing the types of its upvars
196 ///   (borrowed, if appropriate; that is, if Ui represents a by-ref upvar,
197 ///    and the up-var has the type `Foo`, then `Ui = &Foo`).
198 ///
199 /// So, for example, given this function:
200 ///
201 ///     fn foo<'a, T>(data: &'a mut T) {
202 ///          do(|| data.count += 1)
203 ///     }
204 ///
205 /// the type of the closure would be something like:
206 ///
207 ///     struct Closure<'a, T, U0> {
208 ///         data: U0
209 ///     }
210 ///
211 /// Note that the type of the upvar is not specified in the struct.
212 /// You may wonder how the impl would then be able to use the upvar,
213 /// if it doesn't know it's type? The answer is that the impl is
214 /// (conceptually) not fully generic over Closure but rather tied to
215 /// instances with the expected upvar types:
216 ///
217 ///     impl<'b, 'a, T> FnMut() for Closure<'a, T, &'b mut &'a mut T> {
218 ///         ...
219 ///     }
220 ///
221 /// You can see that the *impl* fully specified the type of the upvar
222 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
223 /// (Here, I am assuming that `data` is mut-borrowed.)
224 ///
225 /// Now, the last question you may ask is: Why include the upvar types
226 /// as extra type parameters? The reason for this design is that the
227 /// upvar types can reference lifetimes that are internal to the
228 /// creating function. In my example above, for example, the lifetime
229 /// `'b` represents the scope of the closure itself; this is some
230 /// subset of `foo`, probably just the scope of the call to the to
231 /// `do()`. If we just had the lifetime/type parameters from the
232 /// enclosing function, we couldn't name this lifetime `'b`. Note that
233 /// there can also be lifetimes in the types of the upvars themselves,
234 /// if one of them happens to be a reference to something that the
235 /// creating fn owns.
236 ///
237 /// OK, you say, so why not create a more minimal set of parameters
238 /// that just includes the extra lifetime parameters? The answer is
239 /// primarily that it would be hard --- we don't know at the time when
240 /// we create the closure type what the full types of the upvars are,
241 /// nor do we know which are borrowed and which are not. In this
242 /// design, we can just supply a fresh type parameter and figure that
243 /// out later.
244 ///
245 /// All right, you say, but why include the type parameters from the
246 /// original function then? The answer is that trans may need them
247 /// when monomorphizing, and they may not appear in the upvars.  A
248 /// closure could capture no variables but still make use of some
249 /// in-scope type parameter with a bound (e.g., if our example above
250 /// had an extra `U: Default`, and the closure called `U::default()`).
251 ///
252 /// There is another reason. This design (implicitly) prohibits
253 /// closures from capturing themselves (except via a trait
254 /// object). This simplifies closure inference considerably, since it
255 /// means that when we infer the kind of a closure or its upvars, we
256 /// don't have to handle cycles where the decisions we make for
257 /// closure C wind up influencing the decisions we ought to make for
258 /// closure C (which would then require fixed point iteration to
259 /// handle). Plus it fixes an ICE. :P
260 ///
261 /// ## Generators
262 ///
263 /// Perhaps surprisingly, `ClosureSubsts` are also used for
264 /// generators.  In that case, what is written above is only half-true
265 /// -- the set of type parameters is similar, but the role of CK and
266 /// CS are different.  CK represents the "yield type" and CS
267 /// represents the "return type" of the generator.
268 ///
269 /// It'd be nice to split this struct into ClosureSubsts and
270 /// GeneratorSubsts, I believe. -nmatsakis
271 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
272 pub struct ClosureSubsts<'tcx> {
273     /// Lifetime and type parameters from the enclosing function,
274     /// concatenated with the types of the upvars.
275     ///
276     /// These are separated out because trans wants to pass them around
277     /// when monomorphizing.
278     pub substs: &'tcx Substs<'tcx>,
279 }
280
281 /// Struct returned by `split()`. Note that these are subslices of the
282 /// parent slice and not canonical substs themselves.
283 struct SplitClosureSubsts<'tcx> {
284     closure_kind_ty: Ty<'tcx>,
285     closure_sig_ty: Ty<'tcx>,
286     upvar_kinds: &'tcx [Kind<'tcx>],
287 }
288
289 impl<'tcx> ClosureSubsts<'tcx> {
290     /// Divides the closure substs into their respective
291     /// components. Single source of truth with respect to the
292     /// ordering.
293     fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitClosureSubsts<'tcx> {
294         let generics = tcx.generics_of(def_id);
295         let parent_len = generics.parent_count();
296         SplitClosureSubsts {
297             closure_kind_ty: self.substs.type_at(parent_len),
298             closure_sig_ty: self.substs.type_at(parent_len + 1),
299             upvar_kinds: &self.substs[parent_len + 2..],
300         }
301     }
302
303     #[inline]
304     pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
305         impl Iterator<Item=Ty<'tcx>> + 'tcx
306     {
307         let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
308         upvar_kinds.iter().map(|t| {
309             if let UnpackedKind::Type(ty) = t.unpack() {
310                 ty
311             } else {
312                 bug!("upvar should be type")
313             }
314         })
315     }
316
317     /// Returns the closure kind for this closure; may return a type
318     /// variable during inference. To get the closure kind during
319     /// inference, use `infcx.closure_kind(def_id, substs)`.
320     pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
321         self.split(def_id, tcx).closure_kind_ty
322     }
323
324     /// Returns the type representing the closure signature for this
325     /// closure; may contain type variables during inference. To get
326     /// the closure signature during inference, use
327     /// `infcx.fn_sig(def_id)`.
328     pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
329         self.split(def_id, tcx).closure_sig_ty
330     }
331
332     /// Returns the closure kind for this closure; only usable outside
333     /// of an inference context, because in that context we know that
334     /// there are no type variables.
335     ///
336     /// If you have an inference context, use `infcx.closure_kind()`.
337     pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::ClosureKind {
338         self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap()
339     }
340
341     /// Extracts the signature from the closure; only usable outside
342     /// of an inference context, because in that context we know that
343     /// there are no type variables.
344     ///
345     /// If you have an inference context, use `infcx.closure_sig()`.
346     pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'_, 'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
347         match self.closure_sig_ty(def_id, tcx).sty {
348             ty::TyFnPtr(sig) => sig,
349             ref t => bug!("closure_sig_ty is not a fn-ptr: {:?}", t),
350         }
351     }
352 }
353
354 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
355 pub struct GeneratorSubsts<'tcx> {
356     pub substs: &'tcx Substs<'tcx>,
357 }
358
359 struct SplitGeneratorSubsts<'tcx> {
360     yield_ty: Ty<'tcx>,
361     return_ty: Ty<'tcx>,
362     witness: Ty<'tcx>,
363     upvar_kinds: &'tcx [Kind<'tcx>],
364 }
365
366 impl<'tcx> GeneratorSubsts<'tcx> {
367     fn split(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> SplitGeneratorSubsts<'tcx> {
368         let generics = tcx.generics_of(def_id);
369         let parent_len = generics.parent_count();
370         SplitGeneratorSubsts {
371             yield_ty: self.substs.type_at(parent_len),
372             return_ty: self.substs.type_at(parent_len + 1),
373             witness: self.substs.type_at(parent_len + 2),
374             upvar_kinds: &self.substs[parent_len + 3..],
375         }
376     }
377
378     /// This describes the types that can be contained in a generator.
379     /// It will be a type variable initially and unified in the last stages of typeck of a body.
380     /// It contains a tuple of all the types that could end up on a generator frame.
381     /// The state transformation MIR pass may only produce layouts which mention types
382     /// in this tuple. Upvars are not counted here.
383     pub fn witness(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
384         self.split(def_id, tcx).witness
385     }
386
387     #[inline]
388     pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
389         impl Iterator<Item=Ty<'tcx>> + 'tcx
390     {
391         let SplitGeneratorSubsts { upvar_kinds, .. } = self.split(def_id, tcx);
392         upvar_kinds.iter().map(|t| {
393             if let UnpackedKind::Type(ty) = t.unpack() {
394                 ty
395             } else {
396                 bug!("upvar should be type")
397             }
398         })
399     }
400
401     /// Returns the type representing the yield type of the generator.
402     pub fn yield_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
403         self.split(def_id, tcx).yield_ty
404     }
405
406     /// Returns the type representing the return type of the generator.
407     pub fn return_ty(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> Ty<'tcx> {
408         self.split(def_id, tcx).return_ty
409     }
410
411     /// Return the "generator signature", which consists of its yield
412     /// and return types.
413     ///
414     /// NB. Some bits of the code prefers to see this wrapped in a
415     /// binder, but it never contains bound regions. Probably this
416     /// function should be removed.
417     pub fn poly_sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> PolyGenSig<'tcx> {
418         ty::Binder::dummy(self.sig(def_id, tcx))
419     }
420
421     /// Return the "generator signature", which consists of its yield
422     /// and return types.
423     pub fn sig(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) -> GenSig<'tcx> {
424         ty::GenSig {
425             yield_ty: self.yield_ty(def_id, tcx),
426             return_ty: self.return_ty(def_id, tcx),
427         }
428     }
429 }
430
431 impl<'a, 'gcx, 'tcx> GeneratorSubsts<'tcx> {
432     /// This returns the types of the MIR locals which had to be stored across suspension points.
433     /// It is calculated in rustc_mir::transform::generator::StateTransform.
434     /// All the types here must be in the tuple in GeneratorInterior.
435     pub fn state_tys(
436         self,
437         def_id: DefId,
438         tcx: TyCtxt<'a, 'gcx, 'tcx>,
439     ) -> impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a {
440         let state = tcx.generator_layout(def_id).fields.iter();
441         state.map(move |d| d.ty.subst(tcx, self.substs))
442     }
443
444     /// This is the types of the fields of a generate which
445     /// is available before the generator transformation.
446     /// It includes the upvars and the state discriminant which is u32.
447     pub fn pre_transforms_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
448         impl Iterator<Item=Ty<'tcx>> + 'a
449     {
450         self.upvar_tys(def_id, tcx).chain(iter::once(tcx.types.u32))
451     }
452
453     /// This is the types of all the fields stored in a generator.
454     /// It includes the upvars, state types and the state discriminant which is u32.
455     pub fn field_tys(self, def_id: DefId, tcx: TyCtxt<'a, 'gcx, 'tcx>) ->
456         impl Iterator<Item=Ty<'tcx>> + Captures<'gcx> + 'a
457     {
458         self.pre_transforms_tys(def_id, tcx).chain(self.state_tys(def_id, tcx))
459     }
460 }
461
462 #[derive(Debug, Copy, Clone)]
463 pub enum UpvarSubsts<'tcx> {
464     Closure(ClosureSubsts<'tcx>),
465     Generator(GeneratorSubsts<'tcx>),
466 }
467
468 impl<'tcx> UpvarSubsts<'tcx> {
469     #[inline]
470     pub fn upvar_tys(self, def_id: DefId, tcx: TyCtxt<'_, '_, '_>) ->
471         impl Iterator<Item=Ty<'tcx>> + 'tcx
472     {
473         let upvar_kinds = match self {
474             UpvarSubsts::Closure(substs) => substs.split(def_id, tcx).upvar_kinds,
475             UpvarSubsts::Generator(substs) => substs.split(def_id, tcx).upvar_kinds,
476         };
477         upvar_kinds.iter().map(|t| {
478             if let UnpackedKind::Type(ty) = t.unpack() {
479                 ty
480             } else {
481                 bug!("upvar should be type")
482             }
483         })
484     }
485 }
486
487 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
488 pub enum ExistentialPredicate<'tcx> {
489     /// e.g. Iterator
490     Trait(ExistentialTraitRef<'tcx>),
491     /// e.g. Iterator::Item = T
492     Projection(ExistentialProjection<'tcx>),
493     /// e.g. Send
494     AutoTrait(DefId),
495 }
496
497 impl<'a, 'gcx, 'tcx> ExistentialPredicate<'tcx> {
498     pub fn cmp(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, other: &Self) -> Ordering {
499         use self::ExistentialPredicate::*;
500         match (*self, *other) {
501             (Trait(_), Trait(_)) => Ordering::Equal,
502             (Projection(ref a), Projection(ref b)) =>
503                 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)),
504             (AutoTrait(ref a), AutoTrait(ref b)) =>
505                 tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash),
506             (Trait(_), _) => Ordering::Less,
507             (Projection(_), Trait(_)) => Ordering::Greater,
508             (Projection(_), _) => Ordering::Less,
509             (AutoTrait(_), _) => Ordering::Greater,
510         }
511     }
512
513 }
514
515 impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
516     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
517         -> ty::Predicate<'tcx> {
518         use ty::ToPredicate;
519         match *self.skip_binder() {
520             ExistentialPredicate::Trait(tr) => Binder(tr).with_self_ty(tcx, self_ty).to_predicate(),
521             ExistentialPredicate::Projection(p) =>
522                 ty::Predicate::Projection(Binder(p.with_self_ty(tcx, self_ty))),
523             ExistentialPredicate::AutoTrait(did) => {
524                 let trait_ref = Binder(ty::TraitRef {
525                     def_id: did,
526                     substs: tcx.mk_substs_trait(self_ty, &[]),
527                 });
528                 trait_ref.to_predicate()
529             }
530         }
531     }
532 }
533
534 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<ExistentialPredicate<'tcx>> {}
535
536 impl<'tcx> Slice<ExistentialPredicate<'tcx>> {
537     pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
538         match self.get(0) {
539             Some(&ExistentialPredicate::Trait(tr)) => Some(tr),
540             _ => None,
541         }
542     }
543
544     #[inline]
545     pub fn projection_bounds<'a>(&'a self) ->
546         impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
547         self.iter().filter_map(|predicate| {
548             match *predicate {
549                 ExistentialPredicate::Projection(p) => Some(p),
550                 _ => None,
551             }
552         })
553     }
554
555     #[inline]
556     pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
557         self.iter().filter_map(|predicate| {
558             match *predicate {
559                 ExistentialPredicate::AutoTrait(d) => Some(d),
560                 _ => None
561             }
562         })
563     }
564 }
565
566 impl<'tcx> Binder<&'tcx Slice<ExistentialPredicate<'tcx>>> {
567     pub fn principal(&self) -> Option<PolyExistentialTraitRef<'tcx>> {
568         self.skip_binder().principal().map(Binder::bind)
569     }
570
571     #[inline]
572     pub fn projection_bounds<'a>(&'a self) ->
573         impl Iterator<Item=PolyExistentialProjection<'tcx>> + 'a {
574         self.skip_binder().projection_bounds().map(Binder::bind)
575     }
576
577     #[inline]
578     pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item=DefId> + 'a {
579         self.skip_binder().auto_traits()
580     }
581
582     pub fn iter<'a>(&'a self)
583         -> impl DoubleEndedIterator<Item=Binder<ExistentialPredicate<'tcx>>> + 'tcx {
584         self.skip_binder().iter().cloned().map(Binder::bind)
585     }
586 }
587
588 /// A complete reference to a trait. These take numerous guises in syntax,
589 /// but perhaps the most recognizable form is in a where clause:
590 ///
591 ///     T : Foo<U>
592 ///
593 /// This would be represented by a trait-reference where the def-id is the
594 /// def-id for the trait `Foo` and the substs define `T` as parameter 0,
595 /// and `U` as parameter 1.
596 ///
597 /// Trait references also appear in object types like `Foo<U>`, but in
598 /// that case the `Self` parameter is absent from the substitutions.
599 ///
600 /// Note that a `TraitRef` introduces a level of region binding, to
601 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
602 /// U>` or higher-ranked object types.
603 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
604 pub struct TraitRef<'tcx> {
605     pub def_id: DefId,
606     pub substs: &'tcx Substs<'tcx>,
607 }
608
609 impl<'tcx> TraitRef<'tcx> {
610     pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
611         TraitRef { def_id: def_id, substs: substs }
612     }
613
614     pub fn self_ty(&self) -> Ty<'tcx> {
615         self.substs.type_at(0)
616     }
617
618     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
619         // Select only the "input types" from a trait-reference. For
620         // now this is all the types that appear in the
621         // trait-reference, but it should eventually exclude
622         // associated types.
623         self.substs.types()
624     }
625 }
626
627 pub type PolyTraitRef<'tcx> = Binder<TraitRef<'tcx>>;
628
629 impl<'tcx> PolyTraitRef<'tcx> {
630     pub fn self_ty(&self) -> Ty<'tcx> {
631         self.skip_binder().self_ty()
632     }
633
634     pub fn def_id(&self) -> DefId {
635         self.skip_binder().def_id
636     }
637
638     pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
639         // Note that we preserve binding levels
640         Binder(ty::TraitPredicate { trait_ref: self.skip_binder().clone() })
641     }
642 }
643
644 /// An existential reference to a trait, where `Self` is erased.
645 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
646 ///
647 ///     exists T. T: Trait<'a, 'b, X, Y>
648 ///
649 /// The substitutions don't include the erased `Self`, only trait
650 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
651 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
652 pub struct ExistentialTraitRef<'tcx> {
653     pub def_id: DefId,
654     pub substs: &'tcx Substs<'tcx>,
655 }
656
657 impl<'a, 'gcx, 'tcx> ExistentialTraitRef<'tcx> {
658     pub fn input_types<'b>(&'b self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'b {
659         // Select only the "input types" from a trait-reference. For
660         // now this is all the types that appear in the
661         // trait-reference, but it should eventually exclude
662         // associated types.
663         self.substs.types()
664     }
665
666     /// Object types don't have a self-type specified. Therefore, when
667     /// we convert the principal trait-ref into a normal trait-ref,
668     /// you must give *some* self-type. A common choice is `mk_err()`
669     /// or some skolemized type.
670     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
671         -> ty::TraitRef<'tcx>  {
672         // otherwise the escaping regions would be captured by the binder
673         assert!(!self_ty.has_escaping_regions());
674
675         ty::TraitRef {
676             def_id: self.def_id,
677             substs: tcx.mk_substs(
678                 iter::once(self_ty.into()).chain(self.substs.iter().cloned()))
679         }
680     }
681 }
682
683 pub type PolyExistentialTraitRef<'tcx> = Binder<ExistentialTraitRef<'tcx>>;
684
685 impl<'tcx> PolyExistentialTraitRef<'tcx> {
686     pub fn def_id(&self) -> DefId {
687         self.skip_binder().def_id
688     }
689 }
690
691 /// Binder is a binder for higher-ranked lifetimes. It is part of the
692 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
693 /// (which would be represented by the type `PolyTraitRef ==
694 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
695 /// erase, or otherwise "discharge" these bound regions, we change the
696 /// type from `Binder<T>` to just `T` (see
697 /// e.g. `liberate_late_bound_regions`).
698 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
699 pub struct Binder<T>(T);
700
701 impl<T> Binder<T> {
702     /// Wraps `value` in a binder, asserting that `value` does not
703     /// contain any bound regions that would be bound by the
704     /// binder. This is commonly used to 'inject' a value T into a
705     /// different binding level.
706     pub fn dummy<'tcx>(value: T) -> Binder<T>
707         where T: TypeFoldable<'tcx>
708     {
709         assert!(!value.has_escaping_regions());
710         Binder(value)
711     }
712
713     /// Wraps `value` in a binder, binding late-bound regions (if any).
714     pub fn bind<'tcx>(value: T) -> Binder<T>
715     {
716         Binder(value)
717     }
718
719     /// Skips the binder and returns the "bound" value. This is a
720     /// risky thing to do because it's easy to get confused about
721     /// debruijn indices and the like. It is usually better to
722     /// discharge the binder using `no_late_bound_regions` or
723     /// `replace_late_bound_regions` or something like
724     /// that. `skip_binder` is only valid when you are either
725     /// extracting data that has nothing to do with bound regions, you
726     /// are doing some sort of test that does not involve bound
727     /// regions, or you are being very careful about your depth
728     /// accounting.
729     ///
730     /// Some examples where `skip_binder` is reasonable:
731     ///
732     /// - extracting the def-id from a PolyTraitRef;
733     /// - comparing the self type of a PolyTraitRef to see if it is equal to
734     ///   a type parameter `X`, since the type `X`  does not reference any regions
735     pub fn skip_binder(&self) -> &T {
736         &self.0
737     }
738
739     pub fn as_ref(&self) -> Binder<&T> {
740         Binder(&self.0)
741     }
742
743     pub fn map_bound_ref<F, U>(&self, f: F) -> Binder<U>
744         where F: FnOnce(&T) -> U
745     {
746         self.as_ref().map_bound(f)
747     }
748
749     pub fn map_bound<F, U>(self, f: F) -> Binder<U>
750         where F: FnOnce(T) -> U
751     {
752         Binder(f(self.0))
753     }
754
755     /// Unwraps and returns the value within, but only if it contains
756     /// no bound regions at all. (In other words, if this binder --
757     /// and indeed any enclosing binder -- doesn't bind anything at
758     /// all.) Otherwise, returns `None`.
759     ///
760     /// (One could imagine having a method that just unwraps a single
761     /// binder, but permits late-bound regions bound by enclosing
762     /// binders, but that would require adjusting the debruijn
763     /// indices, and given the shallow binding structure we often use,
764     /// would not be that useful.)
765     pub fn no_late_bound_regions<'tcx>(self) -> Option<T>
766         where T : TypeFoldable<'tcx>
767     {
768         if self.skip_binder().has_escaping_regions() {
769             None
770         } else {
771             Some(self.skip_binder().clone())
772         }
773     }
774
775     /// Given two things that have the same binder level,
776     /// and an operation that wraps on their contents, execute the operation
777     /// and then wrap its result.
778     ///
779     /// `f` should consider bound regions at depth 1 to be free, and
780     /// anything it produces with bound regions at depth 1 will be
781     /// bound in the resulting return value.
782     pub fn fuse<U,F,R>(self, u: Binder<U>, f: F) -> Binder<R>
783         where F: FnOnce(T, U) -> R
784     {
785         Binder(f(self.0, u.0))
786     }
787
788     /// Split the contents into two things that share the same binder
789     /// level as the original, returning two distinct binders.
790     ///
791     /// `f` should consider bound regions at depth 1 to be free, and
792     /// anything it produces with bound regions at depth 1 will be
793     /// bound in the resulting return values.
794     pub fn split<U,V,F>(self, f: F) -> (Binder<U>, Binder<V>)
795         where F: FnOnce(T) -> (U, V)
796     {
797         let (u, v) = f(self.0);
798         (Binder(u), Binder(v))
799     }
800 }
801
802 /// Represents the projection of an associated type. In explicit UFCS
803 /// form this would be written `<T as Trait<..>>::N`.
804 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
805 pub struct ProjectionTy<'tcx> {
806     /// The parameters of the associated item.
807     pub substs: &'tcx Substs<'tcx>,
808
809     /// The DefId of the TraitItem for the associated type N.
810     ///
811     /// Note that this is not the DefId of the TraitRef containing this
812     /// associated type, which is in tcx.associated_item(item_def_id).container.
813     pub item_def_id: DefId,
814 }
815
816 impl<'a, 'tcx> ProjectionTy<'tcx> {
817     /// Construct a ProjectionTy by searching the trait from trait_ref for the
818     /// associated item named item_name.
819     pub fn from_ref_and_name(
820         tcx: TyCtxt, trait_ref: ty::TraitRef<'tcx>, item_name: Name
821     ) -> ProjectionTy<'tcx> {
822         let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| {
823             item.kind == ty::AssociatedKind::Type &&
824             tcx.hygienic_eq(item_name, item.name, trait_ref.def_id)
825         }).unwrap().def_id;
826
827         ProjectionTy {
828             substs: trait_ref.substs,
829             item_def_id,
830         }
831     }
832
833     /// Extracts the underlying trait reference from this projection.
834     /// For example, if this is a projection of `<T as Iterator>::Item`,
835     /// then this function would return a `T: Iterator` trait reference.
836     pub fn trait_ref(&self, tcx: TyCtxt) -> ty::TraitRef<'tcx> {
837         let def_id = tcx.associated_item(self.item_def_id).container.id();
838         ty::TraitRef {
839             def_id,
840             substs: self.substs,
841         }
842     }
843
844     pub fn self_ty(&self) -> Ty<'tcx> {
845         self.substs.type_at(0)
846     }
847 }
848
849 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
850 pub struct GenSig<'tcx> {
851     pub yield_ty: Ty<'tcx>,
852     pub return_ty: Ty<'tcx>,
853 }
854
855 pub type PolyGenSig<'tcx> = Binder<GenSig<'tcx>>;
856
857 impl<'tcx> PolyGenSig<'tcx> {
858     pub fn yield_ty(&self) -> ty::Binder<Ty<'tcx>> {
859         self.map_bound_ref(|sig| sig.yield_ty)
860     }
861     pub fn return_ty(&self) -> ty::Binder<Ty<'tcx>> {
862         self.map_bound_ref(|sig| sig.return_ty)
863     }
864 }
865
866 /// Signature of a function type, which I have arbitrarily
867 /// decided to use to refer to the input/output types.
868 ///
869 /// - `inputs` is the list of arguments and their modes.
870 /// - `output` is the return type.
871 /// - `variadic` indicates whether this is a variadic function. (only true for foreign fns)
872 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
873 pub struct FnSig<'tcx> {
874     pub inputs_and_output: &'tcx Slice<Ty<'tcx>>,
875     pub variadic: bool,
876     pub unsafety: hir::Unsafety,
877     pub abi: abi::Abi,
878 }
879
880 impl<'tcx> FnSig<'tcx> {
881     pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
882         &self.inputs_and_output[..self.inputs_and_output.len() - 1]
883     }
884
885     pub fn output(&self) -> Ty<'tcx> {
886         self.inputs_and_output[self.inputs_and_output.len() - 1]
887     }
888 }
889
890 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
891
892 impl<'tcx> PolyFnSig<'tcx> {
893     pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
894         self.map_bound_ref(|fn_sig| fn_sig.inputs())
895     }
896     pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
897         self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
898     }
899     pub fn inputs_and_output(&self) -> ty::Binder<&'tcx Slice<Ty<'tcx>>> {
900         self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
901     }
902     pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
903         self.map_bound_ref(|fn_sig| fn_sig.output().clone())
904     }
905     pub fn variadic(&self) -> bool {
906         self.skip_binder().variadic
907     }
908     pub fn unsafety(&self) -> hir::Unsafety {
909         self.skip_binder().unsafety
910     }
911     pub fn abi(&self) -> abi::Abi {
912         self.skip_binder().abi
913     }
914 }
915
916 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
917 pub struct ParamTy {
918     pub idx: u32,
919     pub name: InternedString,
920 }
921
922 impl<'a, 'gcx, 'tcx> ParamTy {
923     pub fn new(index: u32, name: InternedString) -> ParamTy {
924         ParamTy { idx: index, name: name }
925     }
926
927     pub fn for_self() -> ParamTy {
928         ParamTy::new(0, keywords::SelfType.name().as_interned_str())
929     }
930
931     pub fn for_def(def: &ty::TypeParameterDef) -> ParamTy {
932         ParamTy::new(def.index, def.name)
933     }
934
935     pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
936         tcx.mk_param(self.idx, self.name)
937     }
938
939     pub fn is_self(&self) -> bool {
940         // FIXME(#50125): Ignoring `Self` with `idx != 0` might lead to weird behavior elsewhere,
941         // but this should only be possible when using `-Z continue-parse-after-error` like
942         // `compile-fail/issue-36638.rs`.
943         if self.name == keywords::SelfType.name().as_str() && self.idx == 0 {
944             true
945         } else {
946             false
947         }
948     }
949 }
950
951 /// A [De Bruijn index][dbi] is a standard means of representing
952 /// regions (and perhaps later types) in a higher-ranked setting. In
953 /// particular, imagine a type like this:
954 ///
955 ///     for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
956 ///     ^          ^            |        |         |
957 ///     |          |            |        |         |
958 ///     |          +------------+ 1      |         |
959 ///     |                                |         |
960 ///     +--------------------------------+ 2       |
961 ///     |                                          |
962 ///     +------------------------------------------+ 1
963 ///
964 /// In this type, there are two binders (the outer fn and the inner
965 /// fn). We need to be able to determine, for any given region, which
966 /// fn type it is bound by, the inner or the outer one. There are
967 /// various ways you can do this, but a De Bruijn index is one of the
968 /// more convenient and has some nice properties. The basic idea is to
969 /// count the number of binders, inside out. Some examples should help
970 /// clarify what I mean.
971 ///
972 /// Let's start with the reference type `&'b isize` that is the first
973 /// argument to the inner function. This region `'b` is assigned a De
974 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
975 /// fn). The region `'a` that appears in the second argument type (`&'a
976 /// isize`) would then be assigned a De Bruijn index of 2, meaning "the
977 /// second-innermost binder". (These indices are written on the arrays
978 /// in the diagram).
979 ///
980 /// What is interesting is that De Bruijn index attached to a particular
981 /// variable will vary depending on where it appears. For example,
982 /// the final type `&'a char` also refers to the region `'a` declared on
983 /// the outermost fn. But this time, this reference is not nested within
984 /// any other binders (i.e., it is not an argument to the inner fn, but
985 /// rather the outer one). Therefore, in this case, it is assigned a
986 /// De Bruijn index of 1, because the innermost binder in that location
987 /// is the outer fn.
988 ///
989 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
990 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy, PartialOrd, Ord)]
991 pub struct DebruijnIndex {
992     /// We maintain the invariant that this is never 0. So 1 indicates
993     /// the innermost binder. To ensure this, create with `DebruijnIndex::new`.
994     pub depth: u32,
995 }
996
997 pub type Region<'tcx> = &'tcx RegionKind;
998
999 /// Representation of regions.
1000 ///
1001 /// Unlike types, most region variants are "fictitious", not concrete,
1002 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1003 /// ones representing concrete regions.
1004 ///
1005 /// ## Bound Regions
1006 ///
1007 /// These are regions that are stored behind a binder and must be substituted
1008 /// with some concrete region before being used. There are 2 kind of
1009 /// bound regions: early-bound, which are bound in an item's Generics,
1010 /// and are substituted by a Substs,  and late-bound, which are part of
1011 /// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
1012 /// the likes of `liberate_late_bound_regions`. The distinction exists
1013 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1014 ///
1015 /// Unlike TyParam-s, bound regions are not supposed to exist "in the wild"
1016 /// outside their binder, e.g. in types passed to type inference, and
1017 /// should first be substituted (by skolemized regions, free regions,
1018 /// or region variables).
1019 ///
1020 /// ## Skolemized and Free Regions
1021 ///
1022 /// One often wants to work with bound regions without knowing their precise
1023 /// identity. For example, when checking a function, the lifetime of a borrow
1024 /// can end up being assigned to some region parameter. In these cases,
1025 /// it must be ensured that bounds on the region can't be accidentally
1026 /// assumed without being checked.
1027 ///
1028 /// The process of doing that is called "skolemization". The bound regions
1029 /// are replaced by skolemized markers, which don't satisfy any relation
1030 /// not explicitly provided.
1031 ///
1032 /// There are 2 kinds of skolemized regions in rustc: `ReFree` and
1033 /// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
1034 /// to be used. These also support explicit bounds: both the internally-stored
1035 /// *scope*, which the region is assumed to outlive, as well as other
1036 /// relations stored in the `FreeRegionMap`. Note that these relations
1037 /// aren't checked when you `make_subregion` (or `eq_types`), only by
1038 /// `resolve_regions_and_report_errors`.
1039 ///
1040 /// When working with higher-ranked types, some region relations aren't
1041 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1042 /// `ReSkolemized` is designed for this purpose. In these contexts,
1043 /// there's also the risk that some inference variable laying around will
1044 /// get unified with your skolemized region: if you want to check whether
1045 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1046 /// with a skolemized region `'%a`, the variable `'_` would just be
1047 /// instantiated to the skolemized region `'%a`, which is wrong because
1048 /// the inference variable is supposed to satisfy the relation
1049 /// *for every value of the skolemized region*. To ensure that doesn't
1050 /// happen, you can use `leak_check`. This is more clearly explained
1051 /// by the [rustc guide].
1052 ///
1053 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1054 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1055 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/trait-hrtb.html
1056 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1057 pub enum RegionKind {
1058     // Region bound in a type or fn declaration which will be
1059     // substituted 'early' -- that is, at the same time when type
1060     // parameters are substituted.
1061     ReEarlyBound(EarlyBoundRegion),
1062
1063     // Region bound in a function scope, which will be substituted when the
1064     // function is called.
1065     ReLateBound(DebruijnIndex, BoundRegion),
1066
1067     /// When checking a function body, the types of all arguments and so forth
1068     /// that refer to bound region parameters are modified to refer to free
1069     /// region parameters.
1070     ReFree(FreeRegion),
1071
1072     /// A concrete region naming some statically determined scope
1073     /// (e.g. an expression or sequence of statements) within the
1074     /// current function.
1075     ReScope(region::Scope),
1076
1077     /// Static data that has an "infinite" lifetime. Top in the region lattice.
1078     ReStatic,
1079
1080     /// A region variable.  Should not exist after typeck.
1081     ReVar(RegionVid),
1082
1083     /// A skolemized region - basically the higher-ranked version of ReFree.
1084     /// Should not exist after typeck.
1085     ReSkolemized(ty::UniverseIndex, BoundRegion),
1086
1087     /// Empty lifetime is for data that is never accessed.
1088     /// Bottom in the region lattice. We treat ReEmpty somewhat
1089     /// specially; at least right now, we do not generate instances of
1090     /// it during the GLB computations, but rather
1091     /// generate an error instead. This is to improve error messages.
1092     /// The only way to get an instance of ReEmpty is to have a region
1093     /// variable with no constraints.
1094     ReEmpty,
1095
1096     /// Erased region, used by trait selection, in MIR and during trans.
1097     ReErased,
1098
1099     /// These are regions bound in the "defining type" for a
1100     /// closure. They are used ONLY as part of the
1101     /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1102     /// See `ClosureRegionRequirements` for more details.
1103     ReClosureBound(RegionVid),
1104
1105     /// Canonicalized region, used only when preparing a trait query.
1106     ReCanonical(CanonicalVar),
1107 }
1108
1109 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1110
1111 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1112 pub struct EarlyBoundRegion {
1113     pub def_id: DefId,
1114     pub index: u32,
1115     pub name: InternedString,
1116 }
1117
1118 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1119 pub struct TyVid {
1120     pub index: u32,
1121 }
1122
1123 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1124 pub struct IntVid {
1125     pub index: u32,
1126 }
1127
1128 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1129 pub struct FloatVid {
1130     pub index: u32,
1131 }
1132
1133 newtype_index!(RegionVid
1134     {
1135         pub idx
1136         DEBUG_FORMAT = custom,
1137     });
1138
1139 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1140 pub enum InferTy {
1141     TyVar(TyVid),
1142     IntVar(IntVid),
1143     FloatVar(FloatVid),
1144
1145     /// A `FreshTy` is one that is generated as a replacement for an
1146     /// unbound type variable. This is convenient for caching etc. See
1147     /// `infer::freshen` for more details.
1148     FreshTy(u32),
1149     FreshIntTy(u32),
1150     FreshFloatTy(u32),
1151
1152     /// Canonicalized type variable, used only when preparing a trait query.
1153     CanonicalTy(CanonicalVar),
1154 }
1155
1156 newtype_index!(CanonicalVar);
1157
1158 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1159 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1160 pub struct ExistentialProjection<'tcx> {
1161     pub item_def_id: DefId,
1162     pub substs: &'tcx Substs<'tcx>,
1163     pub ty: Ty<'tcx>,
1164 }
1165
1166 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1167
1168 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1169     /// Extracts the underlying existential trait reference from this projection.
1170     /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1171     /// then this function would return a `exists T. T: Iterator` existential trait
1172     /// reference.
1173     pub fn trait_ref(&self, tcx: TyCtxt) -> ty::ExistentialTraitRef<'tcx> {
1174         let def_id = tcx.associated_item(self.item_def_id).container.id();
1175         ty::ExistentialTraitRef{
1176             def_id,
1177             substs: self.substs,
1178         }
1179     }
1180
1181     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1182                         self_ty: Ty<'tcx>)
1183                         -> ty::ProjectionPredicate<'tcx>
1184     {
1185         // otherwise the escaping regions would be captured by the binders
1186         assert!(!self_ty.has_escaping_regions());
1187
1188         ty::ProjectionPredicate {
1189             projection_ty: ty::ProjectionTy {
1190                 item_def_id: self.item_def_id,
1191                 substs: tcx.mk_substs(
1192                 iter::once(self_ty.into()).chain(self.substs.iter().cloned())),
1193             },
1194             ty: self.ty,
1195         }
1196     }
1197 }
1198
1199 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
1200     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
1201         -> ty::PolyProjectionPredicate<'tcx> {
1202         self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1203     }
1204
1205     pub fn item_def_id(&self) -> DefId {
1206         return self.skip_binder().item_def_id;
1207     }
1208 }
1209
1210 impl DebruijnIndex {
1211     pub fn new(depth: u32) -> DebruijnIndex {
1212         assert!(depth > 0);
1213         DebruijnIndex { depth: depth }
1214     }
1215
1216     pub fn shifted(&self, amount: u32) -> DebruijnIndex {
1217         DebruijnIndex { depth: self.depth + amount }
1218     }
1219 }
1220
1221 /// Region utilities
1222 impl RegionKind {
1223     pub fn is_late_bound(&self) -> bool {
1224         match *self {
1225             ty::ReLateBound(..) => true,
1226             _ => false,
1227         }
1228     }
1229
1230     pub fn escapes_depth(&self, depth: u32) -> bool {
1231         match *self {
1232             ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1233             _ => false,
1234         }
1235     }
1236
1237     /// Returns the depth of `self` from the (1-based) binding level `depth`
1238     pub fn from_depth(&self, depth: u32) -> RegionKind {
1239         match *self {
1240             ty::ReLateBound(debruijn, r) => ty::ReLateBound(DebruijnIndex {
1241                 depth: debruijn.depth - (depth - 1)
1242             }, r),
1243             r => r
1244         }
1245     }
1246
1247     pub fn keep_in_local_tcx(&self) -> bool {
1248         if let ty::ReVar(..) = self {
1249             true
1250         } else {
1251             false
1252         }
1253     }
1254
1255     pub fn type_flags(&self) -> TypeFlags {
1256         let mut flags = TypeFlags::empty();
1257
1258         if self.keep_in_local_tcx() {
1259             flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1260         }
1261
1262         match *self {
1263             ty::ReVar(..) => {
1264                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1265                 flags = flags | TypeFlags::HAS_RE_INFER;
1266             }
1267             ty::ReSkolemized(..) => {
1268                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1269                 flags = flags | TypeFlags::HAS_RE_SKOL;
1270             }
1271             ty::ReLateBound(..) => { }
1272             ty::ReEarlyBound(..) => {
1273                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1274                 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1275             }
1276             ty::ReEmpty |
1277             ty::ReStatic |
1278             ty::ReFree { .. } |
1279             ty::ReScope { .. } => {
1280                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1281             }
1282             ty::ReErased => {
1283             }
1284             ty::ReCanonical(..) => {
1285                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1286                 flags = flags | TypeFlags::HAS_CANONICAL_VARS;
1287             }
1288             ty::ReClosureBound(..) => {
1289                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1290             }
1291         }
1292
1293         match *self {
1294             ty::ReStatic | ty::ReEmpty | ty::ReErased => (),
1295             _ => flags = flags | TypeFlags::HAS_LOCAL_NAMES,
1296         }
1297
1298         debug!("type_flags({:?}) = {:?}", self, flags);
1299
1300         flags
1301     }
1302
1303     /// Given an early-bound or free region, returns the def-id where it was bound.
1304     /// For example, consider the regions in this snippet of code:
1305     ///
1306     /// ```
1307     /// impl<'a> Foo {
1308     ///      ^^ -- early bound, declared on an impl
1309     ///
1310     ///     fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1311     ///            ^^  ^^     ^ anonymous, late-bound
1312     ///            |   early-bound, appears in where-clauses
1313     ///            late-bound, appears only in fn args
1314     ///     {..}
1315     /// }
1316     /// ```
1317     ///
1318     /// Here, `free_region_binding_scope('a)` would return the def-id
1319     /// of the impl, and for all the other highlighted regions, it
1320     /// would return the def-id of the function. In other cases (not shown), this
1321     /// function might return the def-id of a closure.
1322     pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_, '_, '_>) -> DefId {
1323         match self {
1324             ty::ReEarlyBound(br) => {
1325                 tcx.parent_def_id(br.def_id).unwrap()
1326             }
1327             ty::ReFree(fr) => fr.scope,
1328             _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1329         }
1330     }
1331 }
1332
1333 /// Type utilities
1334 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
1335     pub fn is_nil(&self) -> bool {
1336         match self.sty {
1337             TyTuple(ref tys) => tys.is_empty(),
1338             _ => false,
1339         }
1340     }
1341
1342     pub fn is_never(&self) -> bool {
1343         match self.sty {
1344             TyNever => true,
1345             _ => false,
1346         }
1347     }
1348
1349     pub fn is_primitive(&self) -> bool {
1350         match self.sty {
1351             TyBool | TyChar | TyInt(_) | TyUint(_) | TyFloat(_) => true,
1352             _ => false,
1353         }
1354     }
1355
1356     pub fn is_ty_var(&self) -> bool {
1357         match self.sty {
1358             TyInfer(TyVar(_)) => true,
1359             _ => false,
1360         }
1361     }
1362
1363     pub fn is_ty_infer(&self) -> bool {
1364         match self.sty {
1365             TyInfer(_) => true,
1366             _ => false,
1367         }
1368     }
1369
1370     pub fn is_phantom_data(&self) -> bool {
1371         if let TyAdt(def, _) = self.sty {
1372             def.is_phantom_data()
1373         } else {
1374             false
1375         }
1376     }
1377
1378     pub fn is_bool(&self) -> bool { self.sty == TyBool }
1379
1380     pub fn is_param(&self, index: u32) -> bool {
1381         match self.sty {
1382             ty::TyParam(ref data) => data.idx == index,
1383             _ => false,
1384         }
1385     }
1386
1387     pub fn is_self(&self) -> bool {
1388         match self.sty {
1389             TyParam(ref p) => p.is_self(),
1390             _ => false,
1391         }
1392     }
1393
1394     pub fn is_slice(&self) -> bool {
1395         match self.sty {
1396             TyRawPtr(TypeAndMut { ty, .. }) | TyRef(_, ty, _) => match ty.sty {
1397                 TySlice(_) | TyStr => true,
1398                 _ => false,
1399             },
1400             _ => false
1401         }
1402     }
1403
1404     #[inline]
1405     pub fn is_simd(&self) -> bool {
1406         match self.sty {
1407             TyAdt(def, _) => def.repr.simd(),
1408             _ => false,
1409         }
1410     }
1411
1412     pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1413         match self.sty {
1414             TyArray(ty, _) | TySlice(ty) => ty,
1415             TyStr => tcx.mk_mach_uint(ast::UintTy::U8),
1416             _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1417         }
1418     }
1419
1420     pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1421         match self.sty {
1422             TyAdt(def, substs) => {
1423                 def.non_enum_variant().fields[0].ty(tcx, substs)
1424             }
1425             _ => bug!("simd_type called on invalid type")
1426         }
1427     }
1428
1429     pub fn simd_size(&self, _cx: TyCtxt) -> usize {
1430         match self.sty {
1431             TyAdt(def, _) => def.non_enum_variant().fields.len(),
1432             _ => bug!("simd_size called on invalid type")
1433         }
1434     }
1435
1436     pub fn is_region_ptr(&self) -> bool {
1437         match self.sty {
1438             TyRef(..) => true,
1439             _ => false,
1440         }
1441     }
1442
1443     pub fn is_mutable_pointer(&self) -> bool {
1444         match self.sty {
1445             TyRawPtr(TypeAndMut { mutbl: hir::Mutability::MutMutable, .. }) |
1446             TyRef(_, _, hir::Mutability::MutMutable) => true,
1447             _ => false
1448         }
1449     }
1450
1451     pub fn is_unsafe_ptr(&self) -> bool {
1452         match self.sty {
1453             TyRawPtr(_) => return true,
1454             _ => return false,
1455         }
1456     }
1457
1458     pub fn is_box(&self) -> bool {
1459         match self.sty {
1460             TyAdt(def, _) => def.is_box(),
1461             _ => false,
1462         }
1463     }
1464
1465     /// panics if called on any type other than `Box<T>`
1466     pub fn boxed_ty(&self) -> Ty<'tcx> {
1467         match self.sty {
1468             TyAdt(def, substs) if def.is_box() => substs.type_at(0),
1469             _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1470         }
1471     }
1472
1473     /// A scalar type is one that denotes an atomic datum, with no sub-components.
1474     /// (A TyRawPtr is scalar because it represents a non-managed pointer, so its
1475     /// contents are abstract to rustc.)
1476     pub fn is_scalar(&self) -> bool {
1477         match self.sty {
1478             TyBool | TyChar | TyInt(_) | TyFloat(_) | TyUint(_) |
1479             TyInfer(IntVar(_)) | TyInfer(FloatVar(_)) |
1480             TyFnDef(..) | TyFnPtr(_) | TyRawPtr(_) => true,
1481             _ => false
1482         }
1483     }
1484
1485     /// Returns true if this type is a floating point type and false otherwise.
1486     pub fn is_floating_point(&self) -> bool {
1487         match self.sty {
1488             TyFloat(_) |
1489             TyInfer(FloatVar(_)) => true,
1490             _ => false,
1491         }
1492     }
1493
1494     pub fn is_trait(&self) -> bool {
1495         match self.sty {
1496             TyDynamic(..) => true,
1497             _ => false,
1498         }
1499     }
1500
1501     pub fn is_enum(&self) -> bool {
1502         match self.sty {
1503             TyAdt(adt_def, _) => {
1504                 adt_def.is_enum()
1505             }
1506             _ => false,
1507         }
1508     }
1509
1510     pub fn is_closure(&self) -> bool {
1511         match self.sty {
1512             TyClosure(..) => true,
1513             _ => false,
1514         }
1515     }
1516
1517     pub fn is_generator(&self) -> bool {
1518         match self.sty {
1519             TyGenerator(..) => true,
1520             _ => false,
1521         }
1522     }
1523
1524     pub fn is_integral(&self) -> bool {
1525         match self.sty {
1526             TyInfer(IntVar(_)) | TyInt(_) | TyUint(_) => true,
1527             _ => false
1528         }
1529     }
1530
1531     pub fn is_fresh_ty(&self) -> bool {
1532         match self.sty {
1533             TyInfer(FreshTy(_)) => true,
1534             _ => false,
1535         }
1536     }
1537
1538     pub fn is_fresh(&self) -> bool {
1539         match self.sty {
1540             TyInfer(FreshTy(_)) => true,
1541             TyInfer(FreshIntTy(_)) => true,
1542             TyInfer(FreshFloatTy(_)) => true,
1543             _ => false,
1544         }
1545     }
1546
1547     pub fn is_char(&self) -> bool {
1548         match self.sty {
1549             TyChar => true,
1550             _ => false,
1551         }
1552     }
1553
1554     pub fn is_fp(&self) -> bool {
1555         match self.sty {
1556             TyInfer(FloatVar(_)) | TyFloat(_) => true,
1557             _ => false
1558         }
1559     }
1560
1561     pub fn is_numeric(&self) -> bool {
1562         self.is_integral() || self.is_fp()
1563     }
1564
1565     pub fn is_signed(&self) -> bool {
1566         match self.sty {
1567             TyInt(_) => true,
1568             _ => false,
1569         }
1570     }
1571
1572     pub fn is_machine(&self) -> bool {
1573         match self.sty {
1574             TyInt(ast::IntTy::Isize) | TyUint(ast::UintTy::Usize) => false,
1575             TyInt(..) | TyUint(..) | TyFloat(..) => true,
1576             _ => false,
1577         }
1578     }
1579
1580     pub fn has_concrete_skeleton(&self) -> bool {
1581         match self.sty {
1582             TyParam(_) | TyInfer(_) | TyError => false,
1583             _ => true,
1584         }
1585     }
1586
1587     /// Returns the type and mutability of *ty.
1588     ///
1589     /// The parameter `explicit` indicates if this is an *explicit* dereference.
1590     /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
1591     pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1592         match self.sty {
1593             TyAdt(def, _) if def.is_box() => {
1594                 Some(TypeAndMut {
1595                     ty: self.boxed_ty(),
1596                     mutbl: hir::MutImmutable,
1597                 })
1598             },
1599             TyRef(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
1600             TyRawPtr(mt) if explicit => Some(mt),
1601             _ => None,
1602         }
1603     }
1604
1605     /// Returns the type of `ty[i]`.
1606     pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1607         match self.sty {
1608             TyArray(ty, _) | TySlice(ty) => Some(ty),
1609             _ => None,
1610         }
1611     }
1612
1613     pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1614         match self.sty {
1615             TyFnDef(def_id, substs) => {
1616                 tcx.fn_sig(def_id).subst(tcx, substs)
1617             }
1618             TyFnPtr(f) => f,
1619             _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1620         }
1621     }
1622
1623     pub fn is_fn(&self) -> bool {
1624         match self.sty {
1625             TyFnDef(..) | TyFnPtr(_) => true,
1626             _ => false,
1627         }
1628     }
1629
1630     pub fn ty_to_def_id(&self) -> Option<DefId> {
1631         match self.sty {
1632             TyDynamic(ref tt, ..) => tt.principal().map(|p| p.def_id()),
1633             TyAdt(def, _) => Some(def.did),
1634             TyForeign(did) => Some(did),
1635             TyClosure(id, _) => Some(id),
1636             TyFnDef(id, _) => Some(id),
1637             _ => None,
1638         }
1639     }
1640
1641     pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1642         match self.sty {
1643             TyAdt(adt, _) => Some(adt),
1644             _ => None,
1645         }
1646     }
1647
1648     /// Returns the regions directly referenced from this type (but
1649     /// not types reachable from this type via `walk_tys`). This
1650     /// ignores late-bound regions binders.
1651     pub fn regions(&self) -> Vec<ty::Region<'tcx>> {
1652         match self.sty {
1653             TyRef(region, _, _) => {
1654                 vec![region]
1655             }
1656             TyDynamic(ref obj, region) => {
1657                 let mut v = vec![region];
1658                 if let Some(p) = obj.principal() {
1659                     v.extend(p.skip_binder().substs.regions());
1660                 }
1661                 v
1662             }
1663             TyAdt(_, substs) | TyAnon(_, substs) => {
1664                 substs.regions().collect()
1665             }
1666             TyClosure(_, ClosureSubsts { ref substs }) |
1667             TyGenerator(_, GeneratorSubsts { ref substs }, _) => {
1668                 substs.regions().collect()
1669             }
1670             TyProjection(ref data) => {
1671                 data.substs.regions().collect()
1672             }
1673             TyFnDef(..) |
1674             TyFnPtr(_) |
1675             TyGeneratorWitness(..) |
1676             TyBool |
1677             TyChar |
1678             TyInt(_) |
1679             TyUint(_) |
1680             TyFloat(_) |
1681             TyStr |
1682             TyArray(..) |
1683             TySlice(_) |
1684             TyRawPtr(_) |
1685             TyNever |
1686             TyTuple(..) |
1687             TyForeign(..) |
1688             TyParam(_) |
1689             TyInfer(_) |
1690             TyError => {
1691                 vec![]
1692             }
1693         }
1694     }
1695
1696     /// When we create a closure, we record its kind (i.e., what trait
1697     /// it implements) into its `ClosureSubsts` using a type
1698     /// parameter. This is kind of a phantom type, except that the
1699     /// most convenient thing for us to are the integral types. This
1700     /// function converts such a special type into the closure
1701     /// kind. To go the other way, use
1702     /// `tcx.closure_kind_ty(closure_kind)`.
1703     ///
1704     /// Note that during type checking, we use an inference variable
1705     /// to represent the closure kind, because it has not yet been
1706     /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
1707     /// is complete, that type variable will be unified.
1708     pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
1709         match self.sty {
1710             TyInt(int_ty) => match int_ty {
1711                 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
1712                 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1713                 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1714                 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1715             },
1716
1717             TyInfer(_) => None,
1718
1719             TyError => Some(ty::ClosureKind::Fn),
1720
1721             _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1722         }
1723     }
1724 }
1725
1726 /// Typed constant value.
1727 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Eq, PartialEq)]
1728 pub struct Const<'tcx> {
1729     pub ty: Ty<'tcx>,
1730
1731     pub val: ConstVal<'tcx>,
1732 }
1733
1734 impl<'tcx> Const<'tcx> {
1735     pub fn unevaluated(
1736         tcx: TyCtxt<'_, '_, 'tcx>,
1737         def_id: DefId,
1738         substs: &'tcx Substs<'tcx>,
1739         ty: Ty<'tcx>,
1740     ) -> &'tcx Self {
1741         tcx.mk_const(Const {
1742             val: ConstVal::Unevaluated(def_id, substs),
1743             ty,
1744         })
1745     }
1746
1747     #[inline]
1748     pub fn from_const_val(
1749         tcx: TyCtxt<'_, '_, 'tcx>,
1750         val: ConstVal<'tcx>,
1751         ty: Ty<'tcx>,
1752     ) -> &'tcx Self {
1753         tcx.mk_const(Const {
1754             val,
1755             ty,
1756         })
1757     }
1758
1759     #[inline]
1760     pub fn from_const_value(
1761         tcx: TyCtxt<'_, '_, 'tcx>,
1762         val: ConstValue<'tcx>,
1763         ty: Ty<'tcx>,
1764     ) -> &'tcx Self {
1765         Self::from_const_val(tcx, ConstVal::Value(val), ty)
1766     }
1767
1768     #[inline]
1769     pub fn from_alloc(
1770         tcx: TyCtxt<'_, '_, 'tcx>,
1771         alloc: &'tcx Allocation,
1772         ty: Ty<'tcx>,
1773     ) -> &'tcx Self {
1774         Self::from_const_value(tcx, ConstValue::ByRef(alloc), ty)
1775     }
1776
1777     #[inline]
1778     pub fn from_byval_value(
1779         tcx: TyCtxt<'_, '_, 'tcx>,
1780         val: Value,
1781         ty: Ty<'tcx>,
1782     ) -> &'tcx Self {
1783         Self::from_const_value(tcx, ConstValue::from_byval_value(val), ty)
1784     }
1785
1786     #[inline]
1787     pub fn from_primval(
1788         tcx: TyCtxt<'_, '_, 'tcx>,
1789         val: PrimVal,
1790         ty: Ty<'tcx>,
1791     ) -> &'tcx Self {
1792         Self::from_const_value(tcx, ConstValue::from_primval(val), ty)
1793     }
1794
1795     #[inline]
1796     pub fn from_bits(
1797         tcx: TyCtxt<'_, '_, 'tcx>,
1798         val: u128,
1799         ty: Ty<'tcx>,
1800     ) -> &'tcx Self {
1801         Self::from_primval(tcx, PrimVal::Bytes(val), ty)
1802     }
1803
1804     #[inline]
1805     pub fn zero_sized(tcx: TyCtxt<'_, '_, 'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
1806         Self::from_primval(tcx, PrimVal::Undef, ty)
1807     }
1808
1809     #[inline]
1810     pub fn from_bool(tcx: TyCtxt<'_, '_, 'tcx>, v: bool) -> &'tcx Self {
1811         Self::from_bits(tcx, v as u128, tcx.types.bool)
1812     }
1813
1814     #[inline]
1815     pub fn from_usize(tcx: TyCtxt<'_, '_, 'tcx>, n: u64) -> &'tcx Self {
1816         Self::from_bits(tcx, n as u128, tcx.types.usize)
1817     }
1818
1819     #[inline]
1820     pub fn to_bits(&self, ty: Ty<'_>) -> Option<u128> {
1821         if self.ty != ty {
1822             return None;
1823         }
1824         match self.val {
1825             ConstVal::Value(val) => val.to_bits(),
1826             _ => None,
1827         }
1828     }
1829
1830     #[inline]
1831     pub fn to_ptr(&self) -> Option<MemoryPointer> {
1832         match self.val {
1833             ConstVal::Value(val) => val.to_ptr(),
1834             _ => None,
1835         }
1836     }
1837
1838     #[inline]
1839     pub fn to_primval(&self) -> Option<PrimVal> {
1840         match self.val {
1841             ConstVal::Value(val) => val.to_primval(),
1842             _ => None,
1843         }
1844     }
1845
1846     #[inline]
1847     pub fn assert_bits(&self, ty: Ty<'_>) -> Option<u128> {
1848         assert_eq!(self.ty, ty);
1849         match self.val {
1850             ConstVal::Value(val) => val.to_bits(),
1851             _ => None,
1852         }
1853     }
1854
1855     #[inline]
1856     pub fn assert_bool(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<bool> {
1857         self.assert_bits(tcx.types.bool).and_then(|v| match v {
1858             0 => Some(false),
1859             1 => Some(true),
1860             _ => None,
1861         })
1862     }
1863
1864     #[inline]
1865     pub fn assert_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<u64> {
1866         self.assert_bits(tcx.types.usize).map(|v| v as u64)
1867     }
1868
1869     #[inline]
1870     pub fn unwrap_bits(&self, ty: Ty<'_>) -> u128 {
1871         match self.assert_bits(ty) {
1872             Some(val) => val,
1873             None => bug!("expected bits of {}, got {:#?}", ty, self),
1874         }
1875     }
1876
1877     #[inline]
1878     pub fn unwrap_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> u64 {
1879         match self.assert_usize(tcx) {
1880             Some(val) => val,
1881             None => bug!("expected constant usize, got {:#?}", self),
1882         }
1883     }
1884 }
1885
1886 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}