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