]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/sty.rs
Rollup merge of #59634 - DevQps:explain-E0704, r=estebank
[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, DefIdTree, 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, Debug)]
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::Const<'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(SubstsRef<'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>> + '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     // Create a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible method
1012     fn fake() -> FnSig<'tcx> {
1013         FnSig {
1014             inputs_and_output: List::empty(),
1015             c_variadic: false,
1016             unsafety: hir::Unsafety::Normal,
1017             abi: abi::Abi::Rust,
1018         }
1019     }
1020 }
1021
1022 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1023
1024 impl<'tcx> PolyFnSig<'tcx> {
1025     #[inline]
1026     pub fn inputs(&self) -> Binder<&'tcx [Ty<'tcx>]> {
1027         self.map_bound_ref(|fn_sig| fn_sig.inputs())
1028     }
1029     #[inline]
1030     pub fn input(&self, index: usize) -> ty::Binder<Ty<'tcx>> {
1031         self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
1032     }
1033     pub fn inputs_and_output(&self) -> ty::Binder<&'tcx List<Ty<'tcx>>> {
1034         self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
1035     }
1036     #[inline]
1037     pub fn output(&self) -> ty::Binder<Ty<'tcx>> {
1038         self.map_bound_ref(|fn_sig| fn_sig.output())
1039     }
1040     pub fn c_variadic(&self) -> bool {
1041         self.skip_binder().c_variadic
1042     }
1043     pub fn unsafety(&self) -> hir::Unsafety {
1044         self.skip_binder().unsafety
1045     }
1046     pub fn abi(&self) -> abi::Abi {
1047         self.skip_binder().abi
1048     }
1049 }
1050
1051 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<FnSig<'tcx>>>;
1052
1053
1054 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
1055          Hash, RustcEncodable, RustcDecodable, HashStable)]
1056 pub struct ParamTy {
1057     pub idx: u32,
1058     pub name: InternedString,
1059 }
1060
1061 impl<'a, 'gcx, 'tcx> ParamTy {
1062     pub fn new(index: u32, name: InternedString) -> ParamTy {
1063         ParamTy { idx: index, name: name }
1064     }
1065
1066     pub fn for_self() -> ParamTy {
1067         ParamTy::new(0, keywords::SelfUpper.name().as_interned_str())
1068     }
1069
1070     pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1071         ParamTy::new(def.index, def.name)
1072     }
1073
1074     pub fn to_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1075         tcx.mk_ty_param(self.idx, self.name)
1076     }
1077
1078     pub fn is_self(&self) -> bool {
1079         // FIXME(#50125): Ignoring `Self` with `idx != 0` might lead to weird behavior elsewhere,
1080         // but this should only be possible when using `-Z continue-parse-after-error` like
1081         // `compile-fail/issue-36638.rs`.
1082         self.name == keywords::SelfUpper.name().as_str() && self.idx == 0
1083     }
1084 }
1085
1086 #[derive(Copy, Clone, Hash, RustcEncodable, RustcDecodable,
1087          Eq, PartialEq, Ord, PartialOrd, HashStable)]
1088 pub struct ParamConst {
1089     pub index: u32,
1090     pub name: InternedString,
1091 }
1092
1093 impl<'a, 'gcx, 'tcx> ParamConst {
1094     pub fn new(index: u32, name: InternedString) -> ParamConst {
1095         ParamConst { index, name }
1096     }
1097
1098     pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
1099         ParamConst::new(def.index, def.name)
1100     }
1101
1102     pub fn to_const(self, tcx: TyCtxt<'a, 'gcx, 'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> {
1103         tcx.mk_const_param(self.index, self.name, ty)
1104     }
1105 }
1106
1107 newtype_index! {
1108     /// A [De Bruijn index][dbi] is a standard means of representing
1109     /// regions (and perhaps later types) in a higher-ranked setting. In
1110     /// particular, imagine a type like this:
1111     ///
1112     ///     for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
1113     ///     ^          ^            |        |         |
1114     ///     |          |            |        |         |
1115     ///     |          +------------+ 0      |         |
1116     ///     |                                |         |
1117     ///     +--------------------------------+ 1       |
1118     ///     |                                          |
1119     ///     +------------------------------------------+ 0
1120     ///
1121     /// In this type, there are two binders (the outer fn and the inner
1122     /// fn). We need to be able to determine, for any given region, which
1123     /// fn type it is bound by, the inner or the outer one. There are
1124     /// various ways you can do this, but a De Bruijn index is one of the
1125     /// more convenient and has some nice properties. The basic idea is to
1126     /// count the number of binders, inside out. Some examples should help
1127     /// clarify what I mean.
1128     ///
1129     /// Let's start with the reference type `&'b isize` that is the first
1130     /// argument to the inner function. This region `'b` is assigned a De
1131     /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
1132     /// fn). The region `'a` that appears in the second argument type (`&'a
1133     /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
1134     /// second-innermost binder". (These indices are written on the arrays
1135     /// in the diagram).
1136     ///
1137     /// What is interesting is that De Bruijn index attached to a particular
1138     /// variable will vary depending on where it appears. For example,
1139     /// the final type `&'a char` also refers to the region `'a` declared on
1140     /// the outermost fn. But this time, this reference is not nested within
1141     /// any other binders (i.e., it is not an argument to the inner fn, but
1142     /// rather the outer one). Therefore, in this case, it is assigned a
1143     /// De Bruijn index of 0, because the innermost binder in that location
1144     /// is the outer fn.
1145     ///
1146     /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1147     pub struct DebruijnIndex {
1148         DEBUG_FORMAT = "DebruijnIndex({})",
1149         const INNERMOST = 0,
1150     }
1151 }
1152
1153 pub type Region<'tcx> = &'tcx RegionKind;
1154
1155 /// Representation of regions.
1156 ///
1157 /// Unlike types, most region variants are "fictitious", not concrete,
1158 /// regions. Among these, `ReStatic`, `ReEmpty` and `ReScope` are the only
1159 /// ones representing concrete regions.
1160 ///
1161 /// ## Bound Regions
1162 ///
1163 /// These are regions that are stored behind a binder and must be substituted
1164 /// with some concrete region before being used. There are two kind of
1165 /// bound regions: early-bound, which are bound in an item's `Generics`,
1166 /// and are substituted by a `InternalSubsts`, and late-bound, which are part of
1167 /// higher-ranked types (e.g., `for<'a> fn(&'a ())`), and are substituted by
1168 /// the likes of `liberate_late_bound_regions`. The distinction exists
1169 /// because higher-ranked lifetimes aren't supported in all places. See [1][2].
1170 ///
1171 /// Unlike `Param`s, bound regions are not supposed to exist "in the wild"
1172 /// outside their binder, e.g., in types passed to type inference, and
1173 /// should first be substituted (by placeholder regions, free regions,
1174 /// or region variables).
1175 ///
1176 /// ## Placeholder and Free Regions
1177 ///
1178 /// One often wants to work with bound regions without knowing their precise
1179 /// identity. For example, when checking a function, the lifetime of a borrow
1180 /// can end up being assigned to some region parameter. In these cases,
1181 /// it must be ensured that bounds on the region can't be accidentally
1182 /// assumed without being checked.
1183 ///
1184 /// To do this, we replace the bound regions with placeholder markers,
1185 /// which don't satisfy any relation not explicitly provided.
1186 ///
1187 /// There are two kinds of placeholder regions in rustc: `ReFree` and
1188 /// `RePlaceholder`. When checking an item's body, `ReFree` is supposed
1189 /// to be used. These also support explicit bounds: both the internally-stored
1190 /// *scope*, which the region is assumed to outlive, as well as other
1191 /// relations stored in the `FreeRegionMap`. Note that these relations
1192 /// aren't checked when you `make_subregion` (or `eq_types`), only by
1193 /// `resolve_regions_and_report_errors`.
1194 ///
1195 /// When working with higher-ranked types, some region relations aren't
1196 /// yet known, so you can't just call `resolve_regions_and_report_errors`.
1197 /// `RePlaceholder` is designed for this purpose. In these contexts,
1198 /// there's also the risk that some inference variable laying around will
1199 /// get unified with your placeholder region: if you want to check whether
1200 /// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
1201 /// with a placeholder region `'%a`, the variable `'_` would just be
1202 /// instantiated to the placeholder region `'%a`, which is wrong because
1203 /// the inference variable is supposed to satisfy the relation
1204 /// *for every value of the placeholder region*. To ensure that doesn't
1205 /// happen, you can use `leak_check`. This is more clearly explained
1206 /// by the [rustc guide].
1207 ///
1208 /// [1]: http://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/
1209 /// [2]: http://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/
1210 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/hrtb.html
1211 #[derive(Clone, PartialEq, Eq, Hash, Copy, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1212 pub enum RegionKind {
1213     /// Region bound in a type or fn declaration which will be
1214     /// substituted 'early' -- that is, at the same time when type
1215     /// parameters are substituted.
1216     ReEarlyBound(EarlyBoundRegion),
1217
1218     /// Region bound in a function scope, which will be substituted when the
1219     /// function is called.
1220     ReLateBound(DebruijnIndex, BoundRegion),
1221
1222     /// When checking a function body, the types of all arguments and so forth
1223     /// that refer to bound region parameters are modified to refer to free
1224     /// region parameters.
1225     ReFree(FreeRegion),
1226
1227     /// A concrete region naming some statically determined scope
1228     /// (e.g., an expression or sequence of statements) within the
1229     /// current function.
1230     ReScope(region::Scope),
1231
1232     /// Static data that has an "infinite" lifetime. Top in the region lattice.
1233     ReStatic,
1234
1235     /// A region variable. Should not exist after typeck.
1236     ReVar(RegionVid),
1237
1238     /// A placeholder region - basically the higher-ranked version of ReFree.
1239     /// Should not exist after typeck.
1240     RePlaceholder(ty::PlaceholderRegion),
1241
1242     /// Empty lifetime is for data that is never accessed.
1243     /// Bottom in the region lattice. We treat ReEmpty somewhat
1244     /// specially; at least right now, we do not generate instances of
1245     /// it during the GLB computations, but rather
1246     /// generate an error instead. This is to improve error messages.
1247     /// The only way to get an instance of ReEmpty is to have a region
1248     /// variable with no constraints.
1249     ReEmpty,
1250
1251     /// Erased region, used by trait selection, in MIR and during codegen.
1252     ReErased,
1253
1254     /// These are regions bound in the "defining type" for a
1255     /// closure. They are used ONLY as part of the
1256     /// `ClosureRegionRequirements` that are produced by MIR borrowck.
1257     /// See `ClosureRegionRequirements` for more details.
1258     ReClosureBound(RegionVid),
1259 }
1260
1261 impl<'tcx> serialize::UseSpecializedDecodable for Region<'tcx> {}
1262
1263 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, PartialOrd, Ord)]
1264 pub struct EarlyBoundRegion {
1265     pub def_id: DefId,
1266     pub index: u32,
1267     pub name: InternedString,
1268 }
1269
1270 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1271 pub struct TyVid {
1272     pub index: u32,
1273 }
1274
1275 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1276 pub struct ConstVid<'tcx> {
1277     pub index: u32,
1278     pub phantom: PhantomData<&'tcx ()>,
1279 }
1280
1281 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1282 pub struct IntVid {
1283     pub index: u32,
1284 }
1285
1286 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1287 pub struct FloatVid {
1288     pub index: u32,
1289 }
1290
1291 newtype_index! {
1292     pub struct RegionVid {
1293         DEBUG_FORMAT = custom,
1294     }
1295 }
1296
1297 impl Atom for RegionVid {
1298     fn index(self) -> usize {
1299         Idx::index(self)
1300     }
1301 }
1302
1303 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
1304          Hash, RustcEncodable, RustcDecodable, HashStable)]
1305 pub enum InferTy {
1306     TyVar(TyVid),
1307     IntVar(IntVid),
1308     FloatVar(FloatVid),
1309
1310     /// A `FreshTy` is one that is generated as a replacement for an
1311     /// unbound type variable. This is convenient for caching etc. See
1312     /// `infer::freshen` for more details.
1313     FreshTy(u32),
1314     FreshIntTy(u32),
1315     FreshFloatTy(u32),
1316 }
1317
1318 newtype_index! {
1319     pub struct BoundVar { .. }
1320 }
1321
1322 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1323 pub struct BoundTy {
1324     pub var: BoundVar,
1325     pub kind: BoundTyKind,
1326 }
1327
1328 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1329 pub enum BoundTyKind {
1330     Anon,
1331     Param(InternedString),
1332 }
1333
1334 impl_stable_hash_for!(struct BoundTy { var, kind });
1335 impl_stable_hash_for!(enum self::BoundTyKind { Anon, Param(a) });
1336
1337 impl From<BoundVar> for BoundTy {
1338     fn from(var: BoundVar) -> Self {
1339         BoundTy {
1340             var,
1341             kind: BoundTyKind::Anon,
1342         }
1343     }
1344 }
1345
1346 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1347 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash,
1348          Debug, RustcEncodable, RustcDecodable, HashStable)]
1349 pub struct ExistentialProjection<'tcx> {
1350     pub item_def_id: DefId,
1351     pub substs: SubstsRef<'tcx>,
1352     pub ty: Ty<'tcx>,
1353 }
1354
1355 pub type PolyExistentialProjection<'tcx> = Binder<ExistentialProjection<'tcx>>;
1356
1357 impl<'a, 'tcx, 'gcx> ExistentialProjection<'tcx> {
1358     /// Extracts the underlying existential trait reference from this projection.
1359     /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1360     /// then this function would return a `exists T. T: Iterator` existential trait
1361     /// reference.
1362     pub fn trait_ref(&self, tcx: TyCtxt<'_, '_, '_>) -> ty::ExistentialTraitRef<'tcx> {
1363         let def_id = tcx.associated_item(self.item_def_id).container.id();
1364         ty::ExistentialTraitRef{
1365             def_id,
1366             substs: self.substs,
1367         }
1368     }
1369
1370     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
1371                         self_ty: Ty<'tcx>)
1372                         -> ty::ProjectionPredicate<'tcx>
1373     {
1374         // otherwise the escaping regions would be captured by the binders
1375         debug_assert!(!self_ty.has_escaping_bound_vars());
1376
1377         ty::ProjectionPredicate {
1378             projection_ty: ty::ProjectionTy {
1379                 item_def_id: self.item_def_id,
1380                 substs: tcx.mk_substs_trait(self_ty, self.substs),
1381             },
1382             ty: self.ty,
1383         }
1384     }
1385 }
1386
1387 impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> {
1388     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
1389         -> ty::PolyProjectionPredicate<'tcx> {
1390         self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1391     }
1392
1393     pub fn item_def_id(&self) -> DefId {
1394         return self.skip_binder().item_def_id;
1395     }
1396 }
1397
1398 impl DebruijnIndex {
1399     /// Returns the resulting index when this value is moved into
1400     /// `amount` number of new binders. So, e.g., if you had
1401     ///
1402     ///    for<'a> fn(&'a x)
1403     ///
1404     /// and you wanted to change it to
1405     ///
1406     ///    for<'a> fn(for<'b> fn(&'a x))
1407     ///
1408     /// you would need to shift the index for `'a` into a new binder.
1409     #[must_use]
1410     pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
1411         DebruijnIndex::from_u32(self.as_u32() + amount)
1412     }
1413
1414     /// Update this index in place by shifting it "in" through
1415     /// `amount` number of binders.
1416     pub fn shift_in(&mut self, amount: u32) {
1417         *self = self.shifted_in(amount);
1418     }
1419
1420     /// Returns the resulting index when this value is moved out from
1421     /// `amount` number of new binders.
1422     #[must_use]
1423     pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
1424         DebruijnIndex::from_u32(self.as_u32() - amount)
1425     }
1426
1427     /// Update in place by shifting out from `amount` binders.
1428     pub fn shift_out(&mut self, amount: u32) {
1429         *self = self.shifted_out(amount);
1430     }
1431
1432     /// Adjusts any De Bruijn indices so as to make `to_binder` the
1433     /// innermost binder. That is, if we have something bound at `to_binder`,
1434     /// it will now be bound at INNERMOST. This is an appropriate thing to do
1435     /// when moving a region out from inside binders:
1436     ///
1437     /// ```
1438     ///             for<'a>   fn(for<'b>   for<'c>   fn(&'a u32), _)
1439     /// // Binder:  D3           D2        D1            ^^
1440     /// ```
1441     ///
1442     /// Here, the region `'a` would have the De Bruijn index D3,
1443     /// because it is the bound 3 binders out. However, if we wanted
1444     /// to refer to that region `'a` in the second argument (the `_`),
1445     /// those two binders would not be in scope. In that case, we
1446     /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1447     /// De Bruijn index of `'a` to D1 (the innermost binder).
1448     ///
1449     /// If we invoke `shift_out_to_binder` and the region is in fact
1450     /// bound by one of the binders we are shifting out of, that is an
1451     /// error (and should fail an assertion failure).
1452     pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
1453         self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
1454     }
1455 }
1456
1457 impl_stable_hash_for!(struct DebruijnIndex { private });
1458
1459 /// Region utilities
1460 impl RegionKind {
1461     /// Is this region named by the user?
1462     pub fn has_name(&self) -> bool {
1463         match *self {
1464             RegionKind::ReEarlyBound(ebr) => ebr.has_name(),
1465             RegionKind::ReLateBound(_, br) => br.is_named(),
1466             RegionKind::ReFree(fr) => fr.bound_region.is_named(),
1467             RegionKind::ReScope(..) => false,
1468             RegionKind::ReStatic => true,
1469             RegionKind::ReVar(..) => false,
1470             RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(),
1471             RegionKind::ReEmpty => false,
1472             RegionKind::ReErased => false,
1473             RegionKind::ReClosureBound(..) => false,
1474         }
1475     }
1476
1477     pub fn is_late_bound(&self) -> bool {
1478         match *self {
1479             ty::ReLateBound(..) => true,
1480             _ => false,
1481         }
1482     }
1483
1484     pub fn is_placeholder(&self) -> bool {
1485         match *self {
1486             ty::RePlaceholder(..) => true,
1487             _ => false,
1488         }
1489     }
1490
1491     pub fn bound_at_or_above_binder(&self, index: DebruijnIndex) -> bool {
1492         match *self {
1493             ty::ReLateBound(debruijn, _) => debruijn >= index,
1494             _ => false,
1495         }
1496     }
1497
1498     /// Adjusts any De Bruijn indices so as to make `to_binder` the
1499     /// innermost binder. That is, if we have something bound at `to_binder`,
1500     /// it will now be bound at INNERMOST. This is an appropriate thing to do
1501     /// when moving a region out from inside binders:
1502     ///
1503     /// ```
1504     ///             for<'a>   fn(for<'b>   for<'c>   fn(&'a u32), _)
1505     /// // Binder:  D3           D2        D1            ^^
1506     /// ```
1507     ///
1508     /// Here, the region `'a` would have the De Bruijn index D3,
1509     /// because it is the bound 3 binders out. However, if we wanted
1510     /// to refer to that region `'a` in the second argument (the `_`),
1511     /// those two binders would not be in scope. In that case, we
1512     /// might invoke `shift_out_to_binder(D3)`. This would adjust the
1513     /// De Bruijn index of `'a` to D1 (the innermost binder).
1514     ///
1515     /// If we invoke `shift_out_to_binder` and the region is in fact
1516     /// bound by one of the binders we are shifting out of, that is an
1517     /// error (and should fail an assertion failure).
1518     pub fn shifted_out_to_binder(&self, to_binder: ty::DebruijnIndex) -> RegionKind {
1519         match *self {
1520             ty::ReLateBound(debruijn, r) => ty::ReLateBound(
1521                 debruijn.shifted_out_to_binder(to_binder),
1522                 r,
1523             ),
1524             r => r
1525         }
1526     }
1527
1528     pub fn keep_in_local_tcx(&self) -> bool {
1529         if let ty::ReVar(..) = self {
1530             true
1531         } else {
1532             false
1533         }
1534     }
1535
1536     pub fn type_flags(&self) -> TypeFlags {
1537         let mut flags = TypeFlags::empty();
1538
1539         if self.keep_in_local_tcx() {
1540             flags = flags | TypeFlags::KEEP_IN_LOCAL_TCX;
1541         }
1542
1543         match *self {
1544             ty::ReVar(..) => {
1545                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1546                 flags = flags | TypeFlags::HAS_RE_INFER;
1547             }
1548             ty::RePlaceholder(..) => {
1549                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1550                 flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
1551             }
1552             ty::ReLateBound(..) => {
1553                 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1554             }
1555             ty::ReEarlyBound(..) => {
1556                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1557                 flags = flags | TypeFlags::HAS_RE_EARLY_BOUND;
1558             }
1559             ty::ReEmpty |
1560             ty::ReStatic |
1561             ty::ReFree { .. } |
1562             ty::ReScope { .. } => {
1563                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1564             }
1565             ty::ReErased => {
1566             }
1567             ty::ReClosureBound(..) => {
1568                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1569             }
1570         }
1571
1572         match *self {
1573             ty::ReStatic | ty::ReEmpty | ty::ReErased | ty::ReLateBound(..) => (),
1574             _ => flags = flags | TypeFlags::HAS_FREE_LOCAL_NAMES,
1575         }
1576
1577         debug!("type_flags({:?}) = {:?}", self, flags);
1578
1579         flags
1580     }
1581
1582     /// Given an early-bound or free region, returns the `DefId` where it was bound.
1583     /// For example, consider the regions in this snippet of code:
1584     ///
1585     /// ```
1586     /// impl<'a> Foo {
1587     ///      ^^ -- early bound, declared on an impl
1588     ///
1589     ///     fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1590     ///            ^^  ^^     ^ anonymous, late-bound
1591     ///            |   early-bound, appears in where-clauses
1592     ///            late-bound, appears only in fn args
1593     ///     {..}
1594     /// }
1595     /// ```
1596     ///
1597     /// Here, `free_region_binding_scope('a)` would return the `DefId`
1598     /// of the impl, and for all the other highlighted regions, it
1599     /// would return the `DefId` of the function. In other cases (not shown), this
1600     /// function might return the `DefId` of a closure.
1601     pub fn free_region_binding_scope(&self, tcx: TyCtxt<'_, '_, '_>) -> DefId {
1602         match self {
1603             ty::ReEarlyBound(br) => {
1604                 tcx.parent(br.def_id).unwrap()
1605             }
1606             ty::ReFree(fr) => fr.scope,
1607             _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1608         }
1609     }
1610 }
1611
1612 /// Type utilities
1613 impl<'a, 'gcx, 'tcx> TyS<'tcx> {
1614     pub fn is_unit(&self) -> bool {
1615         match self.sty {
1616             Tuple(ref tys) => tys.is_empty(),
1617             _ => false,
1618         }
1619     }
1620
1621     pub fn is_never(&self) -> bool {
1622         match self.sty {
1623             Never => true,
1624             _ => false,
1625         }
1626     }
1627
1628     /// Checks whether a type is definitely uninhabited. This is
1629     /// conservative: for some types that are uninhabited we return `false`,
1630     /// but we only return `true` for types that are definitely uninhabited.
1631     /// `ty.conservative_is_privately_uninhabited` implies that any value of type `ty`
1632     /// will be `Abi::Uninhabited`. (Note that uninhabited types may have nonzero
1633     /// size, to account for partial initialisation. See #49298 for details.)
1634     pub fn conservative_is_privately_uninhabited(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1635         // FIXME(varkor): we can make this less conversative by substituting concrete
1636         // type arguments.
1637         match self.sty {
1638             ty::Never => true,
1639             ty::Adt(def, _) if def.is_union() => {
1640                 // For now, `union`s are never considered uninhabited.
1641                 false
1642             }
1643             ty::Adt(def, _) => {
1644                 // Any ADT is uninhabited if either:
1645                 // (a) It has no variants (i.e. an empty `enum`);
1646                 // (b) Each of its variants (a single one in the case of a `struct`) has at least
1647                 //     one uninhabited field.
1648                 def.variants.iter().all(|var| {
1649                     var.fields.iter().any(|field| {
1650                         tcx.type_of(field.did).conservative_is_privately_uninhabited(tcx)
1651                     })
1652                 })
1653             }
1654             ty::Tuple(tys) => tys.iter().any(|ty| {
1655                 ty.expect_ty().conservative_is_privately_uninhabited(tcx)
1656             }),
1657             ty::Array(ty, len) => {
1658                 match len.assert_usize(tcx) {
1659                     // If the array is definitely non-empty, it's uninhabited if
1660                     // the type of its elements is uninhabited.
1661                     Some(n) if n != 0 => ty.conservative_is_privately_uninhabited(tcx),
1662                     _ => false
1663                 }
1664             }
1665             ty::Ref(..) => {
1666                 // References to uninitialised memory is valid for any type, including
1667                 // uninhabited types, in unsafe code, so we treat all references as
1668                 // inhabited.
1669                 false
1670             }
1671             _ => false,
1672         }
1673     }
1674
1675     pub fn is_primitive(&self) -> bool {
1676         match self.sty {
1677             Bool | Char | Int(_) | Uint(_) | Float(_) => true,
1678             _ => false,
1679         }
1680     }
1681
1682     #[inline]
1683     pub fn is_ty_var(&self) -> bool {
1684         match self.sty {
1685             Infer(TyVar(_)) => true,
1686             _ => false,
1687         }
1688     }
1689
1690     pub fn is_ty_infer(&self) -> bool {
1691         match self.sty {
1692             Infer(_) => true,
1693             _ => false,
1694         }
1695     }
1696
1697     pub fn is_phantom_data(&self) -> bool {
1698         if let Adt(def, _) = self.sty {
1699             def.is_phantom_data()
1700         } else {
1701             false
1702         }
1703     }
1704
1705     pub fn is_bool(&self) -> bool { self.sty == Bool }
1706
1707     pub fn is_param(&self, index: u32) -> bool {
1708         match self.sty {
1709             ty::Param(ref data) => data.idx == index,
1710             _ => false,
1711         }
1712     }
1713
1714     pub fn is_self(&self) -> bool {
1715         match self.sty {
1716             Param(ref p) => p.is_self(),
1717             _ => false,
1718         }
1719     }
1720
1721     pub fn is_slice(&self) -> bool {
1722         match self.sty {
1723             RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => match ty.sty {
1724                 Slice(_) | Str => true,
1725                 _ => false,
1726             },
1727             _ => false
1728         }
1729     }
1730
1731     #[inline]
1732     pub fn is_simd(&self) -> bool {
1733         match self.sty {
1734             Adt(def, _) => def.repr.simd(),
1735             _ => false,
1736         }
1737     }
1738
1739     pub fn sequence_element_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1740         match self.sty {
1741             Array(ty, _) | Slice(ty) => ty,
1742             Str => tcx.mk_mach_uint(ast::UintTy::U8),
1743             _ => bug!("sequence_element_type called on non-sequence value: {}", self),
1744         }
1745     }
1746
1747     pub fn simd_type(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1748         match self.sty {
1749             Adt(def, substs) => {
1750                 def.non_enum_variant().fields[0].ty(tcx, substs)
1751             }
1752             _ => bug!("simd_type called on invalid type")
1753         }
1754     }
1755
1756     pub fn simd_size(&self, _cx: TyCtxt<'_, '_, '_>) -> usize {
1757         match self.sty {
1758             Adt(def, _) => def.non_enum_variant().fields.len(),
1759             _ => bug!("simd_size called on invalid type")
1760         }
1761     }
1762
1763     pub fn is_region_ptr(&self) -> bool {
1764         match self.sty {
1765             Ref(..) => true,
1766             _ => false,
1767         }
1768     }
1769
1770     pub fn is_mutable_pointer(&self) -> bool {
1771         match self.sty {
1772             RawPtr(TypeAndMut { mutbl: hir::Mutability::MutMutable, .. }) |
1773             Ref(_, _, hir::Mutability::MutMutable) => true,
1774             _ => false
1775         }
1776     }
1777
1778     pub fn is_unsafe_ptr(&self) -> bool {
1779         match self.sty {
1780             RawPtr(_) => return true,
1781             _ => return false,
1782         }
1783     }
1784
1785     /// Returns `true` if this type is an `Arc<T>`.
1786     pub fn is_arc(&self) -> bool {
1787         match self.sty {
1788             Adt(def, _) => def.is_arc(),
1789             _ => false,
1790         }
1791     }
1792
1793     /// Returns `true` if this type is an `Rc<T>`.
1794     pub fn is_rc(&self) -> bool {
1795         match self.sty {
1796             Adt(def, _) => def.is_rc(),
1797             _ => false,
1798         }
1799     }
1800
1801     pub fn is_box(&self) -> bool {
1802         match self.sty {
1803             Adt(def, _) => def.is_box(),
1804             _ => false,
1805         }
1806     }
1807
1808     /// panics if called on any type other than `Box<T>`
1809     pub fn boxed_ty(&self) -> Ty<'tcx> {
1810         match self.sty {
1811             Adt(def, substs) if def.is_box() => substs.type_at(0),
1812             _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1813         }
1814     }
1815
1816     /// A scalar type is one that denotes an atomic datum, with no sub-components.
1817     /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1818     /// contents are abstract to rustc.)
1819     pub fn is_scalar(&self) -> bool {
1820         match self.sty {
1821             Bool | Char | Int(_) | Float(_) | Uint(_) |
1822             Infer(IntVar(_)) | Infer(FloatVar(_)) |
1823             FnDef(..) | FnPtr(_) | RawPtr(_) => true,
1824             _ => false
1825         }
1826     }
1827
1828     /// Returns `true` if this type is a floating point type.
1829     pub fn is_floating_point(&self) -> bool {
1830         match self.sty {
1831             Float(_) |
1832             Infer(FloatVar(_)) => true,
1833             _ => false,
1834         }
1835     }
1836
1837     pub fn is_trait(&self) -> bool {
1838         match self.sty {
1839             Dynamic(..) => true,
1840             _ => false,
1841         }
1842     }
1843
1844     pub fn is_enum(&self) -> bool {
1845         match self.sty {
1846             Adt(adt_def, _) => {
1847                 adt_def.is_enum()
1848             }
1849             _ => false,
1850         }
1851     }
1852
1853     pub fn is_closure(&self) -> bool {
1854         match self.sty {
1855             Closure(..) => true,
1856             _ => false,
1857         }
1858     }
1859
1860     pub fn is_generator(&self) -> bool {
1861         match self.sty {
1862             Generator(..) => true,
1863             _ => false,
1864         }
1865     }
1866
1867     #[inline]
1868     pub fn is_integral(&self) -> bool {
1869         match self.sty {
1870             Infer(IntVar(_)) | Int(_) | Uint(_) => true,
1871             _ => false
1872         }
1873     }
1874
1875     pub fn is_fresh_ty(&self) -> bool {
1876         match self.sty {
1877             Infer(FreshTy(_)) => true,
1878             _ => false,
1879         }
1880     }
1881
1882     pub fn is_fresh(&self) -> bool {
1883         match self.sty {
1884             Infer(FreshTy(_)) => true,
1885             Infer(FreshIntTy(_)) => true,
1886             Infer(FreshFloatTy(_)) => true,
1887             _ => false,
1888         }
1889     }
1890
1891     pub fn is_char(&self) -> bool {
1892         match self.sty {
1893             Char => true,
1894             _ => false,
1895         }
1896     }
1897
1898     #[inline]
1899     pub fn is_fp(&self) -> bool {
1900         match self.sty {
1901             Infer(FloatVar(_)) | Float(_) => true,
1902             _ => false
1903         }
1904     }
1905
1906     pub fn is_numeric(&self) -> bool {
1907         self.is_integral() || self.is_fp()
1908     }
1909
1910     pub fn is_signed(&self) -> bool {
1911         match self.sty {
1912             Int(_) => true,
1913             _ => false,
1914         }
1915     }
1916
1917     pub fn is_pointer_sized(&self) -> bool {
1918         match self.sty {
1919             Int(ast::IntTy::Isize) | Uint(ast::UintTy::Usize) => true,
1920             _ => false,
1921         }
1922     }
1923
1924     pub fn is_machine(&self) -> bool {
1925         match self.sty {
1926             Int(..) | Uint(..) | Float(..) => true,
1927             _ => false,
1928         }
1929     }
1930
1931     pub fn has_concrete_skeleton(&self) -> bool {
1932         match self.sty {
1933             Param(_) | Infer(_) | Error => false,
1934             _ => true,
1935         }
1936     }
1937
1938     /// Returns the type and mutability of `*ty`.
1939     ///
1940     /// The parameter `explicit` indicates if this is an *explicit* dereference.
1941     /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
1942     pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1943         match self.sty {
1944             Adt(def, _) if def.is_box() => {
1945                 Some(TypeAndMut {
1946                     ty: self.boxed_ty(),
1947                     mutbl: hir::MutImmutable,
1948                 })
1949             },
1950             Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl }),
1951             RawPtr(mt) if explicit => Some(mt),
1952             _ => None,
1953         }
1954     }
1955
1956     /// Returns the type of `ty[i]`.
1957     pub fn builtin_index(&self) -> Option<Ty<'tcx>> {
1958         match self.sty {
1959             Array(ty, _) | Slice(ty) => Some(ty),
1960             _ => None,
1961         }
1962     }
1963
1964     pub fn fn_sig(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PolyFnSig<'tcx> {
1965         match self.sty {
1966             FnDef(def_id, substs) => {
1967                 tcx.fn_sig(def_id).subst(tcx, substs)
1968             }
1969             FnPtr(f) => f,
1970             Error => {  // ignore errors (#54954)
1971                 ty::Binder::dummy(FnSig::fake())
1972             }
1973             _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
1974         }
1975     }
1976
1977     pub fn is_fn(&self) -> bool {
1978         match self.sty {
1979             FnDef(..) | FnPtr(_) => true,
1980             _ => false,
1981         }
1982     }
1983
1984     pub fn is_impl_trait(&self) -> bool {
1985         match self.sty {
1986             Opaque(..) => true,
1987             _ => false,
1988         }
1989     }
1990
1991     #[inline]
1992     pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> {
1993         match self.sty {
1994             Adt(adt, _) => Some(adt),
1995             _ => None,
1996         }
1997     }
1998
1999     /// Push onto `out` the regions directly referenced from this type (but not
2000     /// types reachable from this type via `walk_tys`). This ignores late-bound
2001     /// regions binders.
2002     pub fn push_regions(&self, out: &mut SmallVec<[ty::Region<'tcx>; 4]>) {
2003         match self.sty {
2004             Ref(region, _, _) => {
2005                 out.push(region);
2006             }
2007             Dynamic(ref obj, region) => {
2008                 out.push(region);
2009                 if let Some(principal) = obj.principal() {
2010                     out.extend(principal.skip_binder().substs.regions());
2011                 }
2012             }
2013             Adt(_, substs) | Opaque(_, substs) => {
2014                 out.extend(substs.regions())
2015             }
2016             Closure(_, ClosureSubsts { ref substs }) |
2017             Generator(_, GeneratorSubsts { ref substs }, _) => {
2018                 out.extend(substs.regions())
2019             }
2020             Projection(ref data) | UnnormalizedProjection(ref data) => {
2021                 out.extend(data.substs.regions())
2022             }
2023             FnDef(..) |
2024             FnPtr(_) |
2025             GeneratorWitness(..) |
2026             Bool |
2027             Char |
2028             Int(_) |
2029             Uint(_) |
2030             Float(_) |
2031             Str |
2032             Array(..) |
2033             Slice(_) |
2034             RawPtr(_) |
2035             Never |
2036             Tuple(..) |
2037             Foreign(..) |
2038             Param(_) |
2039             Bound(..) |
2040             Placeholder(..) |
2041             Infer(_) |
2042             Error => {}
2043         }
2044     }
2045
2046     /// When we create a closure, we record its kind (i.e., what trait
2047     /// it implements) into its `ClosureSubsts` using a type
2048     /// parameter. This is kind of a phantom type, except that the
2049     /// most convenient thing for us to are the integral types. This
2050     /// function converts such a special type into the closure
2051     /// kind. To go the other way, use
2052     /// `tcx.closure_kind_ty(closure_kind)`.
2053     ///
2054     /// Note that during type checking, we use an inference variable
2055     /// to represent the closure kind, because it has not yet been
2056     /// inferred. Once upvar inference (in `src/librustc_typeck/check/upvar.rs`)
2057     /// is complete, that type variable will be unified.
2058     pub fn to_opt_closure_kind(&self) -> Option<ty::ClosureKind> {
2059         match self.sty {
2060             Int(int_ty) => match int_ty {
2061                 ast::IntTy::I8 => Some(ty::ClosureKind::Fn),
2062                 ast::IntTy::I16 => Some(ty::ClosureKind::FnMut),
2063                 ast::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
2064                 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2065             },
2066
2067             Infer(_) => None,
2068
2069             Error => Some(ty::ClosureKind::Fn),
2070
2071             _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2072         }
2073     }
2074
2075     /// Fast path helper for testing if a type is `Sized`.
2076     ///
2077     /// Returning true means the type is known to be sized. Returning
2078     /// `false` means nothing -- could be sized, might not be.
2079     pub fn is_trivially_sized(&self, tcx: TyCtxt<'_, '_, 'tcx>) -> bool {
2080         match self.sty {
2081             ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
2082             ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
2083             ty::FnDef(..) | ty::FnPtr(_) | ty::RawPtr(..) |
2084             ty::Char | ty::Ref(..) | ty::Generator(..) |
2085             ty::GeneratorWitness(..) | ty::Array(..) | ty::Closure(..) |
2086             ty::Never | ty::Error =>
2087                 true,
2088
2089             ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) =>
2090                 false,
2091
2092             ty::Tuple(tys) => {
2093                 tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx))
2094             }
2095
2096             ty::Adt(def, _substs) =>
2097                 def.sized_constraint(tcx).is_empty(),
2098
2099             ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
2100
2101             ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
2102
2103             ty::Infer(ty::TyVar(_)) => false,
2104
2105             ty::Bound(..) |
2106             ty::Placeholder(..) |
2107             ty::Infer(ty::FreshTy(_)) |
2108             ty::Infer(ty::FreshIntTy(_)) |
2109             ty::Infer(ty::FreshFloatTy(_)) =>
2110                 bug!("is_trivially_sized applied to unexpected type: {:?}", self),
2111         }
2112     }
2113 }
2114
2115 /// Typed constant value.
2116 #[derive(Copy, Clone, Debug, Hash, RustcEncodable, RustcDecodable,
2117          Eq, PartialEq, Ord, PartialOrd, HashStable)]
2118 pub struct Const<'tcx> {
2119     pub ty: Ty<'tcx>,
2120
2121     pub val: ConstValue<'tcx>,
2122 }
2123
2124 #[cfg(target_arch = "x86_64")]
2125 static_assert!(CONST_SIZE: ::std::mem::size_of::<Const<'static>>() == 48);
2126
2127 impl<'tcx> Const<'tcx> {
2128     #[inline]
2129     pub fn from_scalar(
2130         val: Scalar,
2131         ty: Ty<'tcx>,
2132     ) -> Self {
2133         Self {
2134             val: ConstValue::Scalar(val),
2135             ty,
2136         }
2137     }
2138
2139     #[inline]
2140     pub fn from_bits(
2141         tcx: TyCtxt<'_, '_, 'tcx>,
2142         bits: u128,
2143         ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2144     ) -> Self {
2145         let ty = tcx.lift_to_global(&ty).unwrap();
2146         let size = tcx.layout_of(ty).unwrap_or_else(|e| {
2147             panic!("could not compute layout for {:?}: {:?}", ty, e)
2148         }).size;
2149         let truncated = truncate(bits, size);
2150         assert_eq!(truncated, bits, "from_bits called with untruncated value");
2151         Self::from_scalar(Scalar::Bits { bits, size: size.bytes() as u8 }, ty.value)
2152     }
2153
2154     #[inline]
2155     pub fn zero_sized(ty: Ty<'tcx>) -> Self {
2156         Self::from_scalar(Scalar::Bits { bits: 0, size: 0 }, ty)
2157     }
2158
2159     #[inline]
2160     pub fn from_bool(tcx: TyCtxt<'_, '_, 'tcx>, v: bool) -> Self {
2161         Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
2162     }
2163
2164     #[inline]
2165     pub fn from_usize(tcx: TyCtxt<'_, '_, 'tcx>, n: u64) -> Self {
2166         Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
2167     }
2168
2169     #[inline]
2170     pub fn to_bits(
2171         &self,
2172         tcx: TyCtxt<'_, '_, 'tcx>,
2173         ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2174     ) -> Option<u128> {
2175         if self.ty != ty.value {
2176             return None;
2177         }
2178         let ty = tcx.lift_to_global(&ty).unwrap();
2179         let size = tcx.layout_of(ty).ok()?.size;
2180         self.val.try_to_bits(size)
2181     }
2182
2183     #[inline]
2184     pub fn to_ptr(&self) -> Option<Pointer> {
2185         self.val.try_to_ptr()
2186     }
2187
2188     #[inline]
2189     pub fn assert_bits(
2190         &self,
2191         tcx: TyCtxt<'_, '_, '_>,
2192         ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2193     ) -> Option<u128> {
2194         assert_eq!(self.ty, ty.value);
2195         let ty = tcx.lift_to_global(&ty).unwrap();
2196         let size = tcx.layout_of(ty).ok()?.size;
2197         self.val.try_to_bits(size)
2198     }
2199
2200     #[inline]
2201     pub fn assert_bool(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<bool> {
2202         self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.bool)).and_then(|v| match v {
2203             0 => Some(false),
2204             1 => Some(true),
2205             _ => None,
2206         })
2207     }
2208
2209     #[inline]
2210     pub fn assert_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<u64> {
2211         self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.usize)).map(|v| v as u64)
2212     }
2213
2214     #[inline]
2215     pub fn unwrap_bits(
2216         &self,
2217         tcx: TyCtxt<'_, '_, '_>,
2218         ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
2219     ) -> u128 {
2220         self.assert_bits(tcx, ty).unwrap_or_else(||
2221             bug!("expected bits of {}, got {:#?}", ty.value, self))
2222     }
2223
2224     #[inline]
2225     pub fn unwrap_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> u64 {
2226         self.assert_usize(tcx).unwrap_or_else(||
2227             bug!("expected constant usize, got {:#?}", self))
2228     }
2229 }
2230
2231 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {}
2232
2233 /// An inference variable for a const, for use in const generics.
2234 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd,
2235          Ord, RustcEncodable, RustcDecodable, Hash, HashStable)]
2236 pub enum InferConst<'tcx> {
2237     /// Infer the value of the const.
2238     Var(ConstVid<'tcx>),
2239     /// A fresh const variable. See `infer::freshen` for more details.
2240     Fresh(u32),
2241     /// Canonicalized const variable, used only when preparing a trait query.
2242     Canonical(DebruijnIndex, BoundVar),
2243 }