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