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