]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/sty.rs
db18558e947a3f7e1b61d32d34d522a1ddc72b60
[rust.git] / compiler / rustc_middle / src / ty / sty.rs
1 //! This module contains `TyKind` and its major components.
2
3 #![allow(rustc::usage_of_ty_tykind)]
4
5 use crate::infer::canonical::Canonical;
6 use crate::ty::subst::{GenericArg, InternalSubsts, SubstsRef};
7 use crate::ty::visit::ValidateBoundVars;
8 use crate::ty::InferTy::*;
9 use crate::ty::{
10     self, AdtDef, DefIdTree, Discr, Term, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable,
11     TypeVisitor,
12 };
13 use crate::ty::{List, ParamEnv};
14 use hir::def::DefKind;
15 use polonius_engine::Atom;
16 use rustc_data_structures::captures::Captures;
17 use rustc_data_structures::intern::Interned;
18 use rustc_hir as hir;
19 use rustc_hir::def_id::DefId;
20 use rustc_index::vec::Idx;
21 use rustc_macros::HashStable;
22 use rustc_span::symbol::{kw, sym, Symbol};
23 use rustc_span::Span;
24 use rustc_target::abi::VariantIdx;
25 use rustc_target::spec::abi;
26 use std::borrow::Cow;
27 use std::cmp::Ordering;
28 use std::fmt;
29 use std::marker::PhantomData;
30 use std::ops::{ControlFlow, Deref, Range};
31 use ty::util::IntTypeExt;
32
33 use rustc_type_ir::sty::TyKind::*;
34 use rustc_type_ir::RegionKind as IrRegionKind;
35 use rustc_type_ir::TyKind as IrTyKind;
36
37 // Re-export the `TyKind` from `rustc_type_ir` here for convenience
38 #[rustc_diagnostic_item = "TyKind"]
39 pub type TyKind<'tcx> = IrTyKind<TyCtxt<'tcx>>;
40 pub type RegionKind<'tcx> = IrRegionKind<TyCtxt<'tcx>>;
41
42 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
43 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
44 pub struct TypeAndMut<'tcx> {
45     pub ty: Ty<'tcx>,
46     pub mutbl: hir::Mutability,
47 }
48
49 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)]
50 #[derive(HashStable)]
51 /// A "free" region `fr` can be interpreted as "some region
52 /// at least as big as the scope `fr.scope`".
53 pub struct FreeRegion {
54     pub scope: DefId,
55     pub bound_region: BoundRegionKind,
56 }
57
58 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)]
59 #[derive(HashStable)]
60 pub enum BoundRegionKind {
61     /// An anonymous region parameter for a given fn (&T)
62     BrAnon(u32, Option<Span>),
63
64     /// Named region parameters for functions (a in &'a T)
65     ///
66     /// The `DefId` is needed to distinguish free regions in
67     /// the event of shadowing.
68     BrNamed(DefId, Symbol),
69
70     /// Anonymous region for the implicit env pointer parameter
71     /// to a closure
72     BrEnv,
73 }
74
75 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)]
76 #[derive(HashStable)]
77 pub struct BoundRegion {
78     pub var: BoundVar,
79     pub kind: BoundRegionKind,
80 }
81
82 impl BoundRegionKind {
83     pub fn is_named(&self) -> bool {
84         match *self {
85             BoundRegionKind::BrNamed(_, name) => name != kw::UnderscoreLifetime,
86             _ => false,
87         }
88     }
89
90     pub fn get_name(&self) -> Option<Symbol> {
91         if self.is_named() {
92             match *self {
93                 BoundRegionKind::BrNamed(_, name) => return Some(name),
94                 _ => unreachable!(),
95             }
96         }
97
98         None
99     }
100 }
101
102 pub trait Article {
103     fn article(&self) -> &'static str;
104 }
105
106 impl<'tcx> Article for TyKind<'tcx> {
107     /// Get the article ("a" or "an") to use with this type.
108     fn article(&self) -> &'static str {
109         match self {
110             Int(_) | Float(_) | Array(_, _) => "an",
111             Adt(def, _) if def.is_enum() => "an",
112             // This should never happen, but ICEing and causing the user's code
113             // to not compile felt too harsh.
114             Error(_) => "a",
115             _ => "a",
116         }
117     }
118 }
119
120 // `TyKind` is used a lot. Make sure it doesn't unintentionally get bigger.
121 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
122 static_assert_size!(TyKind<'_>, 32);
123
124 /// A closure can be modeled as a struct that looks like:
125 /// ```ignore (illustrative)
126 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U>(...U);
127 /// ```
128 /// where:
129 ///
130 /// - 'l0...'li and T0...Tj are the generic parameters
131 ///   in scope on the function that defined the closure,
132 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
133 ///   is rather hackily encoded via a scalar type. See
134 ///   `Ty::to_opt_closure_kind` for details.
135 /// - CS represents the *closure signature*, representing as a `fn()`
136 ///   type. For example, `fn(u32, u32) -> u32` would mean that the closure
137 ///   implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
138 ///   specified above.
139 /// - U is a type parameter representing the types of its upvars, tupled up
140 ///   (borrowed, if appropriate; that is, if a U field represents a by-ref upvar,
141 ///    and the up-var has the type `Foo`, then that field of U will be `&Foo`).
142 ///
143 /// So, for example, given this function:
144 /// ```ignore (illustrative)
145 /// fn foo<'a, T>(data: &'a mut T) {
146 ///      do(|| data.count += 1)
147 /// }
148 /// ```
149 /// the type of the closure would be something like:
150 /// ```ignore (illustrative)
151 /// struct Closure<'a, T, U>(...U);
152 /// ```
153 /// Note that the type of the upvar is not specified in the struct.
154 /// You may wonder how the impl would then be able to use the upvar,
155 /// if it doesn't know it's type? The answer is that the impl is
156 /// (conceptually) not fully generic over Closure but rather tied to
157 /// instances with the expected upvar types:
158 /// ```ignore (illustrative)
159 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, (&'b mut &'a mut T,)> {
160 ///     ...
161 /// }
162 /// ```
163 /// You can see that the *impl* fully specified the type of the upvar
164 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
165 /// (Here, I am assuming that `data` is mut-borrowed.)
166 ///
167 /// Now, the last question you may ask is: Why include the upvar types
168 /// in an extra type parameter? The reason for this design is that the
169 /// upvar types can reference lifetimes that are internal to the
170 /// creating function. In my example above, for example, the lifetime
171 /// `'b` represents the scope of the closure itself; this is some
172 /// subset of `foo`, probably just the scope of the call to the to
173 /// `do()`. If we just had the lifetime/type parameters from the
174 /// enclosing function, we couldn't name this lifetime `'b`. Note that
175 /// there can also be lifetimes in the types of the upvars themselves,
176 /// if one of them happens to be a reference to something that the
177 /// creating fn owns.
178 ///
179 /// OK, you say, so why not create a more minimal set of parameters
180 /// that just includes the extra lifetime parameters? The answer is
181 /// primarily that it would be hard --- we don't know at the time when
182 /// we create the closure type what the full types of the upvars are,
183 /// nor do we know which are borrowed and which are not. In this
184 /// design, we can just supply a fresh type parameter and figure that
185 /// out later.
186 ///
187 /// All right, you say, but why include the type parameters from the
188 /// original function then? The answer is that codegen may need them
189 /// when monomorphizing, and they may not appear in the upvars. A
190 /// closure could capture no variables but still make use of some
191 /// in-scope type parameter with a bound (e.g., if our example above
192 /// had an extra `U: Default`, and the closure called `U::default()`).
193 ///
194 /// There is another reason. This design (implicitly) prohibits
195 /// closures from capturing themselves (except via a trait
196 /// object). This simplifies closure inference considerably, since it
197 /// means that when we infer the kind of a closure or its upvars, we
198 /// don't have to handle cycles where the decisions we make for
199 /// closure C wind up influencing the decisions we ought to make for
200 /// closure C (which would then require fixed point iteration to
201 /// handle). Plus it fixes an ICE. :P
202 ///
203 /// ## Generators
204 ///
205 /// Generators are handled similarly in `GeneratorSubsts`.  The set of
206 /// type parameters is similar, but `CK` and `CS` are replaced by the
207 /// following type parameters:
208 ///
209 /// * `GS`: The generator's "resume type", which is the type of the
210 ///   argument passed to `resume`, and the type of `yield` expressions
211 ///   inside the generator.
212 /// * `GY`: The "yield type", which is the type of values passed to
213 ///   `yield` inside the generator.
214 /// * `GR`: The "return type", which is the type of value returned upon
215 ///   completion of the generator.
216 /// * `GW`: The "generator witness".
217 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
218 pub struct ClosureSubsts<'tcx> {
219     /// Lifetime and type parameters from the enclosing function,
220     /// concatenated with a tuple containing the types of the upvars.
221     ///
222     /// These are separated out because codegen wants to pass them around
223     /// when monomorphizing.
224     pub substs: SubstsRef<'tcx>,
225 }
226
227 /// Struct returned by `split()`.
228 pub struct ClosureSubstsParts<'tcx, T> {
229     pub parent_substs: &'tcx [GenericArg<'tcx>],
230     pub closure_kind_ty: T,
231     pub closure_sig_as_fn_ptr_ty: T,
232     pub tupled_upvars_ty: T,
233 }
234
235 impl<'tcx> ClosureSubsts<'tcx> {
236     /// Construct `ClosureSubsts` from `ClosureSubstsParts`, containing `Substs`
237     /// for the closure parent, alongside additional closure-specific components.
238     pub fn new(
239         tcx: TyCtxt<'tcx>,
240         parts: ClosureSubstsParts<'tcx, Ty<'tcx>>,
241     ) -> ClosureSubsts<'tcx> {
242         ClosureSubsts {
243             substs: tcx.mk_substs(
244                 parts.parent_substs.iter().copied().chain(
245                     [parts.closure_kind_ty, parts.closure_sig_as_fn_ptr_ty, parts.tupled_upvars_ty]
246                         .iter()
247                         .map(|&ty| ty.into()),
248                 ),
249             ),
250         }
251     }
252
253     /// Divides the closure substs into their respective components.
254     /// The ordering assumed here must match that used by `ClosureSubsts::new` above.
255     fn split(self) -> ClosureSubstsParts<'tcx, GenericArg<'tcx>> {
256         match self.substs[..] {
257             [
258                 ref parent_substs @ ..,
259                 closure_kind_ty,
260                 closure_sig_as_fn_ptr_ty,
261                 tupled_upvars_ty,
262             ] => ClosureSubstsParts {
263                 parent_substs,
264                 closure_kind_ty,
265                 closure_sig_as_fn_ptr_ty,
266                 tupled_upvars_ty,
267             },
268             _ => bug!("closure substs missing synthetics"),
269         }
270     }
271
272     /// Returns `true` only if enough of the synthetic types are known to
273     /// allow using all of the methods on `ClosureSubsts` without panicking.
274     ///
275     /// Used primarily by `ty::print::pretty` to be able to handle closure
276     /// types that haven't had their synthetic types substituted in.
277     pub fn is_valid(self) -> bool {
278         self.substs.len() >= 3
279             && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_))
280     }
281
282     /// Returns the substitutions of the closure's parent.
283     pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] {
284         self.split().parent_substs
285     }
286
287     /// Returns an iterator over the list of types of captured paths by the closure.
288     /// In case there was a type error in figuring out the types of the captured path, an
289     /// empty iterator is returned.
290     #[inline]
291     pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
292         match self.tupled_upvars_ty().kind() {
293             TyKind::Error(_) => None,
294             TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()),
295             TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
296             ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
297         }
298         .into_iter()
299         .flatten()
300     }
301
302     /// Returns the tuple type representing the upvars for this closure.
303     #[inline]
304     pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
305         self.split().tupled_upvars_ty.expect_ty()
306     }
307
308     /// Returns the closure kind for this closure; may return a type
309     /// variable during inference. To get the closure kind during
310     /// inference, use `infcx.closure_kind(substs)`.
311     pub fn kind_ty(self) -> Ty<'tcx> {
312         self.split().closure_kind_ty.expect_ty()
313     }
314
315     /// Returns the `fn` pointer type representing the closure signature for this
316     /// closure.
317     // FIXME(eddyb) this should be unnecessary, as the shallowly resolved
318     // type is known at the time of the creation of `ClosureSubsts`,
319     // see `rustc_hir_analysis::check::closure`.
320     pub fn sig_as_fn_ptr_ty(self) -> Ty<'tcx> {
321         self.split().closure_sig_as_fn_ptr_ty.expect_ty()
322     }
323
324     /// Returns the closure kind for this closure; only usable outside
325     /// of an inference context, because in that context we know that
326     /// there are no type variables.
327     ///
328     /// If you have an inference context, use `infcx.closure_kind()`.
329     pub fn kind(self) -> ty::ClosureKind {
330         self.kind_ty().to_opt_closure_kind().unwrap()
331     }
332
333     /// Extracts the signature from the closure.
334     pub fn sig(self) -> ty::PolyFnSig<'tcx> {
335         let ty = self.sig_as_fn_ptr_ty();
336         match ty.kind() {
337             ty::FnPtr(sig) => *sig,
338             _ => bug!("closure_sig_as_fn_ptr_ty is not a fn-ptr: {:?}", ty.kind()),
339         }
340     }
341
342     pub fn print_as_impl_trait(self) -> ty::print::PrintClosureAsImpl<'tcx> {
343         ty::print::PrintClosureAsImpl { closure: self }
344     }
345 }
346
347 /// Similar to `ClosureSubsts`; see the above documentation for more.
348 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
349 pub struct GeneratorSubsts<'tcx> {
350     pub substs: SubstsRef<'tcx>,
351 }
352
353 pub struct GeneratorSubstsParts<'tcx, T> {
354     pub parent_substs: &'tcx [GenericArg<'tcx>],
355     pub resume_ty: T,
356     pub yield_ty: T,
357     pub return_ty: T,
358     pub witness: T,
359     pub tupled_upvars_ty: T,
360 }
361
362 impl<'tcx> GeneratorSubsts<'tcx> {
363     /// Construct `GeneratorSubsts` from `GeneratorSubstsParts`, containing `Substs`
364     /// for the generator parent, alongside additional generator-specific components.
365     pub fn new(
366         tcx: TyCtxt<'tcx>,
367         parts: GeneratorSubstsParts<'tcx, Ty<'tcx>>,
368     ) -> GeneratorSubsts<'tcx> {
369         GeneratorSubsts {
370             substs: tcx.mk_substs(
371                 parts.parent_substs.iter().copied().chain(
372                     [
373                         parts.resume_ty,
374                         parts.yield_ty,
375                         parts.return_ty,
376                         parts.witness,
377                         parts.tupled_upvars_ty,
378                     ]
379                     .iter()
380                     .map(|&ty| ty.into()),
381                 ),
382             ),
383         }
384     }
385
386     /// Divides the generator substs into their respective components.
387     /// The ordering assumed here must match that used by `GeneratorSubsts::new` above.
388     fn split(self) -> GeneratorSubstsParts<'tcx, GenericArg<'tcx>> {
389         match self.substs[..] {
390             [ref parent_substs @ .., resume_ty, yield_ty, return_ty, witness, tupled_upvars_ty] => {
391                 GeneratorSubstsParts {
392                     parent_substs,
393                     resume_ty,
394                     yield_ty,
395                     return_ty,
396                     witness,
397                     tupled_upvars_ty,
398                 }
399             }
400             _ => bug!("generator substs missing synthetics"),
401         }
402     }
403
404     /// Returns `true` only if enough of the synthetic types are known to
405     /// allow using all of the methods on `GeneratorSubsts` without panicking.
406     ///
407     /// Used primarily by `ty::print::pretty` to be able to handle generator
408     /// types that haven't had their synthetic types substituted in.
409     pub fn is_valid(self) -> bool {
410         self.substs.len() >= 5
411             && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_))
412     }
413
414     /// Returns the substitutions of the generator's parent.
415     pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] {
416         self.split().parent_substs
417     }
418
419     /// This describes the types that can be contained in a generator.
420     /// It will be a type variable initially and unified in the last stages of typeck of a body.
421     /// It contains a tuple of all the types that could end up on a generator frame.
422     /// The state transformation MIR pass may only produce layouts which mention types
423     /// in this tuple. Upvars are not counted here.
424     pub fn witness(self) -> Ty<'tcx> {
425         self.split().witness.expect_ty()
426     }
427
428     /// Returns an iterator over the list of types of captured paths by the generator.
429     /// In case there was a type error in figuring out the types of the captured path, an
430     /// empty iterator is returned.
431     #[inline]
432     pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
433         match self.tupled_upvars_ty().kind() {
434             TyKind::Error(_) => None,
435             TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()),
436             TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
437             ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
438         }
439         .into_iter()
440         .flatten()
441     }
442
443     /// Returns the tuple type representing the upvars for this generator.
444     #[inline]
445     pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
446         self.split().tupled_upvars_ty.expect_ty()
447     }
448
449     /// Returns the type representing the resume type of the generator.
450     pub fn resume_ty(self) -> Ty<'tcx> {
451         self.split().resume_ty.expect_ty()
452     }
453
454     /// Returns the type representing the yield type of the generator.
455     pub fn yield_ty(self) -> Ty<'tcx> {
456         self.split().yield_ty.expect_ty()
457     }
458
459     /// Returns the type representing the return type of the generator.
460     pub fn return_ty(self) -> Ty<'tcx> {
461         self.split().return_ty.expect_ty()
462     }
463
464     /// Returns the "generator signature", which consists of its yield
465     /// and return types.
466     ///
467     /// N.B., some bits of the code prefers to see this wrapped in a
468     /// binder, but it never contains bound regions. Probably this
469     /// function should be removed.
470     pub fn poly_sig(self) -> PolyGenSig<'tcx> {
471         ty::Binder::dummy(self.sig())
472     }
473
474     /// Returns the "generator signature", which consists of its resume, yield
475     /// and return types.
476     pub fn sig(self) -> GenSig<'tcx> {
477         ty::GenSig {
478             resume_ty: self.resume_ty(),
479             yield_ty: self.yield_ty(),
480             return_ty: self.return_ty(),
481         }
482     }
483 }
484
485 impl<'tcx> GeneratorSubsts<'tcx> {
486     /// Generator has not been resumed yet.
487     pub const UNRESUMED: usize = 0;
488     /// Generator has returned or is completed.
489     pub const RETURNED: usize = 1;
490     /// Generator has been poisoned.
491     pub const POISONED: usize = 2;
492
493     const UNRESUMED_NAME: &'static str = "Unresumed";
494     const RETURNED_NAME: &'static str = "Returned";
495     const POISONED_NAME: &'static str = "Panicked";
496
497     /// The valid variant indices of this generator.
498     #[inline]
499     pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
500         // FIXME requires optimized MIR
501         let num_variants = tcx.generator_layout(def_id).unwrap().variant_fields.len();
502         VariantIdx::new(0)..VariantIdx::new(num_variants)
503     }
504
505     /// The discriminant for the given variant. Panics if the `variant_index` is
506     /// out of range.
507     #[inline]
508     pub fn discriminant_for_variant(
509         &self,
510         def_id: DefId,
511         tcx: TyCtxt<'tcx>,
512         variant_index: VariantIdx,
513     ) -> Discr<'tcx> {
514         // Generators don't support explicit discriminant values, so they are
515         // the same as the variant index.
516         assert!(self.variant_range(def_id, tcx).contains(&variant_index));
517         Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
518     }
519
520     /// The set of all discriminants for the generator, enumerated with their
521     /// variant indices.
522     #[inline]
523     pub fn discriminants(
524         self,
525         def_id: DefId,
526         tcx: TyCtxt<'tcx>,
527     ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
528         self.variant_range(def_id, tcx).map(move |index| {
529             (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
530         })
531     }
532
533     /// Calls `f` with a reference to the name of the enumerator for the given
534     /// variant `v`.
535     pub fn variant_name(v: VariantIdx) -> Cow<'static, str> {
536         match v.as_usize() {
537             Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
538             Self::RETURNED => Cow::from(Self::RETURNED_NAME),
539             Self::POISONED => Cow::from(Self::POISONED_NAME),
540             _ => Cow::from(format!("Suspend{}", v.as_usize() - 3)),
541         }
542     }
543
544     /// The type of the state discriminant used in the generator type.
545     #[inline]
546     pub fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
547         tcx.types.u32
548     }
549
550     /// This returns the types of the MIR locals which had to be stored across suspension points.
551     /// It is calculated in rustc_mir_transform::generator::StateTransform.
552     /// All the types here must be in the tuple in GeneratorInterior.
553     ///
554     /// The locals are grouped by their variant number. Note that some locals may
555     /// be repeated in multiple variants.
556     #[inline]
557     pub fn state_tys(
558         self,
559         def_id: DefId,
560         tcx: TyCtxt<'tcx>,
561     ) -> impl Iterator<Item = impl Iterator<Item = Ty<'tcx>> + Captures<'tcx>> {
562         let layout = tcx.generator_layout(def_id).unwrap();
563         layout.variant_fields.iter().map(move |variant| {
564             variant
565                 .iter()
566                 .map(move |field| ty::EarlyBinder(layout.field_tys[*field]).subst(tcx, self.substs))
567         })
568     }
569
570     /// This is the types of the fields of a generator which are not stored in a
571     /// variant.
572     #[inline]
573     pub fn prefix_tys(self) -> impl Iterator<Item = Ty<'tcx>> {
574         self.upvar_tys()
575     }
576 }
577
578 #[derive(Debug, Copy, Clone, HashStable)]
579 pub enum UpvarSubsts<'tcx> {
580     Closure(SubstsRef<'tcx>),
581     Generator(SubstsRef<'tcx>),
582 }
583
584 impl<'tcx> UpvarSubsts<'tcx> {
585     /// Returns an iterator over the list of types of captured paths by the closure/generator.
586     /// In case there was a type error in figuring out the types of the captured path, an
587     /// empty iterator is returned.
588     #[inline]
589     pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
590         let tupled_tys = match self {
591             UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(),
592             UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(),
593         };
594
595         match tupled_tys.kind() {
596             TyKind::Error(_) => None,
597             TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()),
598             TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
599             ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
600         }
601         .into_iter()
602         .flatten()
603     }
604
605     #[inline]
606     pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
607         match self {
608             UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(),
609             UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(),
610         }
611     }
612 }
613
614 /// An inline const is modeled like
615 /// ```ignore (illustrative)
616 /// const InlineConst<'l0...'li, T0...Tj, R>: R;
617 /// ```
618 /// where:
619 ///
620 /// - 'l0...'li and T0...Tj are the generic parameters
621 ///   inherited from the item that defined the inline const,
622 /// - R represents the type of the constant.
623 ///
624 /// When the inline const is instantiated, `R` is substituted as the actual inferred
625 /// type of the constant. The reason that `R` is represented as an extra type parameter
626 /// is the same reason that [`ClosureSubsts`] have `CS` and `U` as type parameters:
627 /// inline const can reference lifetimes that are internal to the creating function.
628 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
629 pub struct InlineConstSubsts<'tcx> {
630     /// Generic parameters from the enclosing item,
631     /// concatenated with the inferred type of the constant.
632     pub substs: SubstsRef<'tcx>,
633 }
634
635 /// Struct returned by `split()`.
636 pub struct InlineConstSubstsParts<'tcx, T> {
637     pub parent_substs: &'tcx [GenericArg<'tcx>],
638     pub ty: T,
639 }
640
641 impl<'tcx> InlineConstSubsts<'tcx> {
642     /// Construct `InlineConstSubsts` from `InlineConstSubstsParts`.
643     pub fn new(
644         tcx: TyCtxt<'tcx>,
645         parts: InlineConstSubstsParts<'tcx, Ty<'tcx>>,
646     ) -> InlineConstSubsts<'tcx> {
647         InlineConstSubsts {
648             substs: tcx.mk_substs(
649                 parts.parent_substs.iter().copied().chain(std::iter::once(parts.ty.into())),
650             ),
651         }
652     }
653
654     /// Divides the inline const substs into their respective components.
655     /// The ordering assumed here must match that used by `InlineConstSubsts::new` above.
656     fn split(self) -> InlineConstSubstsParts<'tcx, GenericArg<'tcx>> {
657         match self.substs[..] {
658             [ref parent_substs @ .., ty] => InlineConstSubstsParts { parent_substs, ty },
659             _ => bug!("inline const substs missing synthetics"),
660         }
661     }
662
663     /// Returns the substitutions of the inline const's parent.
664     pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] {
665         self.split().parent_substs
666     }
667
668     /// Returns the type of this inline const.
669     pub fn ty(self) -> Ty<'tcx> {
670         self.split().ty.expect_ty()
671     }
672 }
673
674 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, TyEncodable, TyDecodable)]
675 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
676 pub enum ExistentialPredicate<'tcx> {
677     /// E.g., `Iterator`.
678     Trait(ExistentialTraitRef<'tcx>),
679     /// E.g., `Iterator::Item = T`.
680     Projection(ExistentialProjection<'tcx>),
681     /// E.g., `Send`.
682     AutoTrait(DefId),
683 }
684
685 impl<'tcx> ExistentialPredicate<'tcx> {
686     /// Compares via an ordering that will not change if modules are reordered or other changes are
687     /// made to the tree. In particular, this ordering is preserved across incremental compilations.
688     pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering {
689         use self::ExistentialPredicate::*;
690         match (*self, *other) {
691             (Trait(_), Trait(_)) => Ordering::Equal,
692             (Projection(ref a), Projection(ref b)) => {
693                 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id))
694             }
695             (AutoTrait(ref a), AutoTrait(ref b)) => {
696                 tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b))
697             }
698             (Trait(_), _) => Ordering::Less,
699             (Projection(_), Trait(_)) => Ordering::Greater,
700             (Projection(_), _) => Ordering::Less,
701             (AutoTrait(_), _) => Ordering::Greater,
702         }
703     }
704 }
705
706 pub type PolyExistentialPredicate<'tcx> = Binder<'tcx, ExistentialPredicate<'tcx>>;
707
708 impl<'tcx> PolyExistentialPredicate<'tcx> {
709     /// Given an existential predicate like `?Self: PartialEq<u32>` (e.g., derived from `dyn PartialEq<u32>`),
710     /// and a concrete type `self_ty`, returns a full predicate where the existentially quantified variable `?Self`
711     /// has been replaced with `self_ty` (e.g., `self_ty: PartialEq<u32>`, in our example).
712     pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> {
713         use crate::ty::ToPredicate;
714         match self.skip_binder() {
715             ExistentialPredicate::Trait(tr) => {
716                 self.rebind(tr).with_self_ty(tcx, self_ty).without_const().to_predicate(tcx)
717             }
718             ExistentialPredicate::Projection(p) => {
719                 self.rebind(p.with_self_ty(tcx, self_ty)).to_predicate(tcx)
720             }
721             ExistentialPredicate::AutoTrait(did) => {
722                 let trait_ref = self.rebind(tcx.mk_trait_ref(did, [self_ty]));
723                 trait_ref.without_const().to_predicate(tcx)
724             }
725         }
726     }
727 }
728
729 impl<'tcx> List<ty::PolyExistentialPredicate<'tcx>> {
730     /// Returns the "principal `DefId`" of this set of existential predicates.
731     ///
732     /// A Rust trait object type consists (in addition to a lifetime bound)
733     /// of a set of trait bounds, which are separated into any number
734     /// of auto-trait bounds, and at most one non-auto-trait bound. The
735     /// non-auto-trait bound is called the "principal" of the trait
736     /// object.
737     ///
738     /// Only the principal can have methods or type parameters (because
739     /// auto traits can have neither of them). This is important, because
740     /// it means the auto traits can be treated as an unordered set (methods
741     /// would force an order for the vtable, while relating traits with
742     /// type parameters without knowing the order to relate them in is
743     /// a rather non-trivial task).
744     ///
745     /// For example, in the trait object `dyn fmt::Debug + Sync`, the
746     /// principal bound is `Some(fmt::Debug)`, while the auto-trait bounds
747     /// are the set `{Sync}`.
748     ///
749     /// It is also possible to have a "trivial" trait object that
750     /// consists only of auto traits, with no principal - for example,
751     /// `dyn Send + Sync`. In that case, the set of auto-trait bounds
752     /// is `{Send, Sync}`, while there is no principal. These trait objects
753     /// have a "trivial" vtable consisting of just the size, alignment,
754     /// and destructor.
755     pub fn principal(&self) -> Option<ty::Binder<'tcx, ExistentialTraitRef<'tcx>>> {
756         self[0]
757             .map_bound(|this| match this {
758                 ExistentialPredicate::Trait(tr) => Some(tr),
759                 _ => None,
760             })
761             .transpose()
762     }
763
764     pub fn principal_def_id(&self) -> Option<DefId> {
765         self.principal().map(|trait_ref| trait_ref.skip_binder().def_id)
766     }
767
768     #[inline]
769     pub fn projection_bounds<'a>(
770         &'a self,
771     ) -> impl Iterator<Item = ty::Binder<'tcx, ExistentialProjection<'tcx>>> + 'a {
772         self.iter().filter_map(|predicate| {
773             predicate
774                 .map_bound(|pred| match pred {
775                     ExistentialPredicate::Projection(projection) => Some(projection),
776                     _ => None,
777                 })
778                 .transpose()
779         })
780     }
781
782     #[inline]
783     pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'a {
784         self.iter().filter_map(|predicate| match predicate.skip_binder() {
785             ExistentialPredicate::AutoTrait(did) => Some(did),
786             _ => None,
787         })
788     }
789 }
790
791 /// A complete reference to a trait. These take numerous guises in syntax,
792 /// but perhaps the most recognizable form is in a where-clause:
793 /// ```ignore (illustrative)
794 /// T: Foo<U>
795 /// ```
796 /// This would be represented by a trait-reference where the `DefId` is the
797 /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0,
798 /// and `U` as parameter 1.
799 ///
800 /// Trait references also appear in object types like `Foo<U>`, but in
801 /// that case the `Self` parameter is absent from the substitutions.
802 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
803 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
804 pub struct TraitRef<'tcx> {
805     pub def_id: DefId,
806     pub substs: SubstsRef<'tcx>,
807 }
808
809 impl<'tcx> TraitRef<'tcx> {
810     pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> {
811         TraitRef { def_id, substs }
812     }
813
814     pub fn with_self_type(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
815         tcx.mk_trait_ref(
816             self.def_id,
817             [self_ty.into()].into_iter().chain(self.substs.iter().skip(1)),
818         )
819     }
820
821     /// Returns a `TraitRef` of the form `P0: Foo<P1..Pn>` where `Pi`
822     /// are the parameters defined on trait.
823     pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> Binder<'tcx, TraitRef<'tcx>> {
824         ty::Binder::dummy(TraitRef {
825             def_id,
826             substs: InternalSubsts::identity_for_item(tcx, def_id),
827         })
828     }
829
830     #[inline]
831     pub fn self_ty(&self) -> Ty<'tcx> {
832         self.substs.type_at(0)
833     }
834
835     pub fn from_method(
836         tcx: TyCtxt<'tcx>,
837         trait_id: DefId,
838         substs: SubstsRef<'tcx>,
839     ) -> ty::TraitRef<'tcx> {
840         let defs = tcx.generics_of(trait_id);
841         ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) }
842     }
843 }
844
845 pub type PolyTraitRef<'tcx> = Binder<'tcx, TraitRef<'tcx>>;
846
847 impl<'tcx> PolyTraitRef<'tcx> {
848     pub fn self_ty(&self) -> Binder<'tcx, Ty<'tcx>> {
849         self.map_bound_ref(|tr| tr.self_ty())
850     }
851
852     pub fn def_id(&self) -> DefId {
853         self.skip_binder().def_id
854     }
855
856     pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
857         self.map_bound(|trait_ref| ty::TraitPredicate {
858             trait_ref,
859             constness: ty::BoundConstness::NotConst,
860             polarity: ty::ImplPolarity::Positive,
861         })
862     }
863
864     /// Same as [`PolyTraitRef::to_poly_trait_predicate`] but sets a negative polarity instead.
865     pub fn to_poly_trait_predicate_negative_polarity(&self) -> ty::PolyTraitPredicate<'tcx> {
866         self.map_bound(|trait_ref| ty::TraitPredicate {
867             trait_ref,
868             constness: ty::BoundConstness::NotConst,
869             polarity: ty::ImplPolarity::Negative,
870         })
871     }
872 }
873
874 impl rustc_errors::IntoDiagnosticArg for PolyTraitRef<'_> {
875     fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
876         self.to_string().into_diagnostic_arg()
877     }
878 }
879
880 /// An existential reference to a trait, where `Self` is erased.
881 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
882 /// ```ignore (illustrative)
883 /// exists T. T: Trait<'a, 'b, X, Y>
884 /// ```
885 /// The substitutions don't include the erased `Self`, only trait
886 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
887 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
888 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
889 pub struct ExistentialTraitRef<'tcx> {
890     pub def_id: DefId,
891     pub substs: SubstsRef<'tcx>,
892 }
893
894 impl<'tcx> ExistentialTraitRef<'tcx> {
895     pub fn erase_self_ty(
896         tcx: TyCtxt<'tcx>,
897         trait_ref: ty::TraitRef<'tcx>,
898     ) -> ty::ExistentialTraitRef<'tcx> {
899         // Assert there is a Self.
900         trait_ref.substs.type_at(0);
901
902         ty::ExistentialTraitRef {
903             def_id: trait_ref.def_id,
904             substs: tcx.intern_substs(&trait_ref.substs[1..]),
905         }
906     }
907
908     /// Object types don't have a self type specified. Therefore, when
909     /// we convert the principal trait-ref into a normal trait-ref,
910     /// you must give *some* self type. A common choice is `mk_err()`
911     /// or some placeholder type.
912     pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> {
913         // otherwise the escaping vars would be captured by the binder
914         // debug_assert!(!self_ty.has_escaping_bound_vars());
915
916         tcx.mk_trait_ref(self.def_id, [self_ty.into()].into_iter().chain(self.substs.iter()))
917     }
918 }
919
920 pub type PolyExistentialTraitRef<'tcx> = Binder<'tcx, ExistentialTraitRef<'tcx>>;
921
922 impl<'tcx> PolyExistentialTraitRef<'tcx> {
923     pub fn def_id(&self) -> DefId {
924         self.skip_binder().def_id
925     }
926
927     /// Object types don't have a self type specified. Therefore, when
928     /// we convert the principal trait-ref into a normal trait-ref,
929     /// you must give *some* self type. A common choice is `mk_err()`
930     /// or some placeholder type.
931     pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> {
932         self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
933     }
934 }
935
936 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
937 #[derive(HashStable)]
938 pub enum BoundVariableKind {
939     Ty(BoundTyKind),
940     Region(BoundRegionKind),
941     Const,
942 }
943
944 impl BoundVariableKind {
945     pub fn expect_region(self) -> BoundRegionKind {
946         match self {
947             BoundVariableKind::Region(lt) => lt,
948             _ => bug!("expected a region, but found another kind"),
949         }
950     }
951
952     pub fn expect_ty(self) -> BoundTyKind {
953         match self {
954             BoundVariableKind::Ty(ty) => ty,
955             _ => bug!("expected a type, but found another kind"),
956         }
957     }
958
959     pub fn expect_const(self) {
960         match self {
961             BoundVariableKind::Const => (),
962             _ => bug!("expected a const, but found another kind"),
963         }
964     }
965 }
966
967 /// Binder is a binder for higher-ranked lifetimes or types. It is part of the
968 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
969 /// (which would be represented by the type `PolyTraitRef ==
970 /// Binder<'tcx, TraitRef>`). Note that when we instantiate,
971 /// erase, or otherwise "discharge" these bound vars, we change the
972 /// type from `Binder<'tcx, T>` to just `T` (see
973 /// e.g., `liberate_late_bound_regions`).
974 ///
975 /// `Decodable` and `Encodable` are implemented for `Binder<T>` using the `impl_binder_encode_decode!` macro.
976 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
977 #[derive(HashStable, Lift)]
978 pub struct Binder<'tcx, T>(T, &'tcx List<BoundVariableKind>);
979
980 impl<'tcx, T> Binder<'tcx, T>
981 where
982     T: TypeVisitable<'tcx>,
983 {
984     /// Wraps `value` in a binder, asserting that `value` does not
985     /// contain any bound vars that would be bound by the
986     /// binder. This is commonly used to 'inject' a value T into a
987     /// different binding level.
988     pub fn dummy(value: T) -> Binder<'tcx, T> {
989         assert!(!value.has_escaping_bound_vars());
990         Binder(value, ty::List::empty())
991     }
992
993     pub fn bind_with_vars(value: T, vars: &'tcx List<BoundVariableKind>) -> Binder<'tcx, T> {
994         if cfg!(debug_assertions) {
995             let mut validator = ValidateBoundVars::new(vars);
996             value.visit_with(&mut validator);
997         }
998         Binder(value, vars)
999     }
1000 }
1001
1002 impl<'tcx, T> Binder<'tcx, T> {
1003     /// Skips the binder and returns the "bound" value. This is a
1004     /// risky thing to do because it's easy to get confused about
1005     /// De Bruijn indices and the like. It is usually better to
1006     /// discharge the binder using `no_bound_vars` or
1007     /// `replace_late_bound_regions` or something like
1008     /// that. `skip_binder` is only valid when you are either
1009     /// extracting data that has nothing to do with bound vars, you
1010     /// are doing some sort of test that does not involve bound
1011     /// regions, or you are being very careful about your depth
1012     /// accounting.
1013     ///
1014     /// Some examples where `skip_binder` is reasonable:
1015     ///
1016     /// - extracting the `DefId` from a PolyTraitRef;
1017     /// - comparing the self type of a PolyTraitRef to see if it is equal to
1018     ///   a type parameter `X`, since the type `X` does not reference any regions
1019     pub fn skip_binder(self) -> T {
1020         self.0
1021     }
1022
1023     pub fn bound_vars(&self) -> &'tcx List<BoundVariableKind> {
1024         self.1
1025     }
1026
1027     pub fn as_ref(&self) -> Binder<'tcx, &T> {
1028         Binder(&self.0, self.1)
1029     }
1030
1031     pub fn as_deref(&self) -> Binder<'tcx, &T::Target>
1032     where
1033         T: Deref,
1034     {
1035         Binder(&self.0, self.1)
1036     }
1037
1038     pub fn map_bound_ref_unchecked<F, U>(&self, f: F) -> Binder<'tcx, U>
1039     where
1040         F: FnOnce(&T) -> U,
1041     {
1042         let value = f(&self.0);
1043         Binder(value, self.1)
1044     }
1045
1046     pub fn map_bound_ref<F, U: TypeVisitable<'tcx>>(&self, f: F) -> Binder<'tcx, U>
1047     where
1048         F: FnOnce(&T) -> U,
1049     {
1050         self.as_ref().map_bound(f)
1051     }
1052
1053     pub fn map_bound<F, U: TypeVisitable<'tcx>>(self, f: F) -> Binder<'tcx, U>
1054     where
1055         F: FnOnce(T) -> U,
1056     {
1057         let value = f(self.0);
1058         if cfg!(debug_assertions) {
1059             let mut validator = ValidateBoundVars::new(self.1);
1060             value.visit_with(&mut validator);
1061         }
1062         Binder(value, self.1)
1063     }
1064
1065     pub fn try_map_bound<F, U: TypeVisitable<'tcx>, E>(self, f: F) -> Result<Binder<'tcx, U>, E>
1066     where
1067         F: FnOnce(T) -> Result<U, E>,
1068     {
1069         let value = f(self.0)?;
1070         if cfg!(debug_assertions) {
1071             let mut validator = ValidateBoundVars::new(self.1);
1072             value.visit_with(&mut validator);
1073         }
1074         Ok(Binder(value, self.1))
1075     }
1076
1077     /// Wraps a `value` in a binder, using the same bound variables as the
1078     /// current `Binder`. This should not be used if the new value *changes*
1079     /// the bound variables. Note: the (old or new) value itself does not
1080     /// necessarily need to *name* all the bound variables.
1081     ///
1082     /// This currently doesn't do anything different than `bind`, because we
1083     /// don't actually track bound vars. However, semantically, it is different
1084     /// because bound vars aren't allowed to change here, whereas they are
1085     /// in `bind`. This may be (debug) asserted in the future.
1086     pub fn rebind<U>(&self, value: U) -> Binder<'tcx, U>
1087     where
1088         U: TypeVisitable<'tcx>,
1089     {
1090         if cfg!(debug_assertions) {
1091             let mut validator = ValidateBoundVars::new(self.bound_vars());
1092             value.visit_with(&mut validator);
1093         }
1094         Binder(value, self.1)
1095     }
1096
1097     /// Unwraps and returns the value within, but only if it contains
1098     /// no bound vars at all. (In other words, if this binder --
1099     /// and indeed any enclosing binder -- doesn't bind anything at
1100     /// all.) Otherwise, returns `None`.
1101     ///
1102     /// (One could imagine having a method that just unwraps a single
1103     /// binder, but permits late-bound vars bound by enclosing
1104     /// binders, but that would require adjusting the debruijn
1105     /// indices, and given the shallow binding structure we often use,
1106     /// would not be that useful.)
1107     pub fn no_bound_vars(self) -> Option<T>
1108     where
1109         T: TypeVisitable<'tcx>,
1110     {
1111         if self.0.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) }
1112     }
1113
1114     /// Splits the contents into two things that share the same binder
1115     /// level as the original, returning two distinct binders.
1116     ///
1117     /// `f` should consider bound regions at depth 1 to be free, and
1118     /// anything it produces with bound regions at depth 1 will be
1119     /// bound in the resulting return values.
1120     pub fn split<U, V, F>(self, f: F) -> (Binder<'tcx, U>, Binder<'tcx, V>)
1121     where
1122         F: FnOnce(T) -> (U, V),
1123     {
1124         let (u, v) = f(self.0);
1125         (Binder(u, self.1), Binder(v, self.1))
1126     }
1127 }
1128
1129 impl<'tcx, T> Binder<'tcx, Option<T>> {
1130     pub fn transpose(self) -> Option<Binder<'tcx, T>> {
1131         let bound_vars = self.1;
1132         self.0.map(|v| Binder(v, bound_vars))
1133     }
1134 }
1135
1136 /// Represents the projection of an associated type. In explicit UFCS
1137 /// form this would be written `<T as Trait<..>>::N`.
1138 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1139 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
1140 pub struct ProjectionTy<'tcx> {
1141     /// The parameters of the associated item.
1142     pub substs: SubstsRef<'tcx>,
1143
1144     /// The `DefId` of the `TraitItem` for the associated type `N`.
1145     ///
1146     /// Note that this is not the `DefId` of the `TraitRef` containing this
1147     /// associated type, which is in `tcx.associated_item(item_def_id).container`,
1148     /// aka. `tcx.parent(item_def_id).unwrap()`.
1149     pub item_def_id: DefId,
1150 }
1151
1152 impl<'tcx> ProjectionTy<'tcx> {
1153     pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
1154         match tcx.def_kind(self.item_def_id) {
1155             DefKind::AssocTy | DefKind::AssocConst => tcx.parent(self.item_def_id),
1156             DefKind::ImplTraitPlaceholder => {
1157                 tcx.parent(tcx.impl_trait_in_trait_parent(self.item_def_id))
1158             }
1159             kind => bug!("unexpected DefKind in ProjectionTy: {kind:?}"),
1160         }
1161     }
1162
1163     /// Extracts the underlying trait reference and own substs from this projection.
1164     /// For example, if this is a projection of `<T as StreamingIterator>::Item<'a>`,
1165     /// then this function would return a `T: Iterator` trait reference and `['a]` as the own substs
1166     pub fn trait_ref_and_own_substs(
1167         &self,
1168         tcx: TyCtxt<'tcx>,
1169     ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) {
1170         let def_id = tcx.parent(self.item_def_id);
1171         assert_eq!(tcx.def_kind(def_id), DefKind::Trait);
1172         let trait_generics = tcx.generics_of(def_id);
1173         (
1174             ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, trait_generics) },
1175             &self.substs[trait_generics.count()..],
1176         )
1177     }
1178
1179     /// Extracts the underlying trait reference from this projection.
1180     /// For example, if this is a projection of `<T as Iterator>::Item`,
1181     /// then this function would return a `T: Iterator` trait reference.
1182     ///
1183     /// WARNING: This will drop the substs for generic associated types
1184     /// consider calling [Self::trait_ref_and_own_substs] to get those
1185     /// as well.
1186     pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> {
1187         let def_id = self.trait_def_id(tcx);
1188         ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, tcx.generics_of(def_id)) }
1189     }
1190
1191     pub fn self_ty(&self) -> Ty<'tcx> {
1192         self.substs.type_at(0)
1193     }
1194 }
1195
1196 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
1197 pub struct GenSig<'tcx> {
1198     pub resume_ty: Ty<'tcx>,
1199     pub yield_ty: Ty<'tcx>,
1200     pub return_ty: Ty<'tcx>,
1201 }
1202
1203 pub type PolyGenSig<'tcx> = Binder<'tcx, GenSig<'tcx>>;
1204
1205 /// Signature of a function type, which we have arbitrarily
1206 /// decided to use to refer to the input/output types.
1207 ///
1208 /// - `inputs`: is the list of arguments and their modes.
1209 /// - `output`: is the return type.
1210 /// - `c_variadic`: indicates whether this is a C-variadic function.
1211 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
1212 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
1213 pub struct FnSig<'tcx> {
1214     pub inputs_and_output: &'tcx List<Ty<'tcx>>,
1215     pub c_variadic: bool,
1216     pub unsafety: hir::Unsafety,
1217     pub abi: abi::Abi,
1218 }
1219
1220 impl<'tcx> FnSig<'tcx> {
1221     pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
1222         &self.inputs_and_output[..self.inputs_and_output.len() - 1]
1223     }
1224
1225     pub fn output(&self) -> Ty<'tcx> {
1226         self.inputs_and_output[self.inputs_and_output.len() - 1]
1227     }
1228
1229     // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible
1230     // method.
1231     fn fake() -> FnSig<'tcx> {
1232         FnSig {
1233             inputs_and_output: List::empty(),
1234             c_variadic: false,
1235             unsafety: hir::Unsafety::Normal,
1236             abi: abi::Abi::Rust,
1237         }
1238     }
1239 }
1240
1241 pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
1242
1243 impl<'tcx> PolyFnSig<'tcx> {
1244     #[inline]
1245     pub fn inputs(&self) -> Binder<'tcx, &'tcx [Ty<'tcx>]> {
1246         self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs())
1247     }
1248     #[inline]
1249     pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> {
1250         self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
1251     }
1252     pub fn inputs_and_output(&self) -> ty::Binder<'tcx, &'tcx List<Ty<'tcx>>> {
1253         self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
1254     }
1255     #[inline]
1256     pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> {
1257         self.map_bound_ref(|fn_sig| fn_sig.output())
1258     }
1259     pub fn c_variadic(&self) -> bool {
1260         self.skip_binder().c_variadic
1261     }
1262     pub fn unsafety(&self) -> hir::Unsafety {
1263         self.skip_binder().unsafety
1264     }
1265     pub fn abi(&self) -> abi::Abi {
1266         self.skip_binder().abi
1267     }
1268 }
1269
1270 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
1271
1272 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
1273 #[derive(HashStable)]
1274 pub struct ParamTy {
1275     pub index: u32,
1276     pub name: Symbol,
1277 }
1278
1279 impl<'tcx> ParamTy {
1280     pub fn new(index: u32, name: Symbol) -> ParamTy {
1281         ParamTy { index, name }
1282     }
1283
1284     pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1285         ParamTy::new(def.index, def.name)
1286     }
1287
1288     #[inline]
1289     pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1290         tcx.mk_ty_param(self.index, self.name)
1291     }
1292
1293     pub fn span_from_generics(&self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
1294         let generics = tcx.generics_of(item_with_generics);
1295         let type_param = generics.type_param(self, tcx);
1296         tcx.def_span(type_param.def_id)
1297     }
1298 }
1299
1300 #[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)]
1301 #[derive(HashStable)]
1302 pub struct ParamConst {
1303     pub index: u32,
1304     pub name: Symbol,
1305 }
1306
1307 impl ParamConst {
1308     pub fn new(index: u32, name: Symbol) -> ParamConst {
1309         ParamConst { index, name }
1310     }
1311
1312     pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
1313         ParamConst::new(def.index, def.name)
1314     }
1315 }
1316
1317 /// Use this rather than `RegionKind`, whenever possible.
1318 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
1319 #[rustc_pass_by_value]
1320 pub struct Region<'tcx>(pub Interned<'tcx, RegionKind<'tcx>>);
1321
1322 impl<'tcx> Deref for Region<'tcx> {
1323     type Target = RegionKind<'tcx>;
1324
1325     #[inline]
1326     fn deref(&self) -> &RegionKind<'tcx> {
1327         &self.0.0
1328     }
1329 }
1330
1331 impl<'tcx> fmt::Debug for Region<'tcx> {
1332     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1333         write!(f, "{:?}", self.kind())
1334     }
1335 }
1336
1337 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1338 #[derive(HashStable)]
1339 pub struct EarlyBoundRegion {
1340     pub def_id: DefId,
1341     pub index: u32,
1342     pub name: Symbol,
1343 }
1344
1345 impl fmt::Debug for EarlyBoundRegion {
1346     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1347         write!(f, "{}, {}", self.index, self.name)
1348     }
1349 }
1350
1351 /// A **`const`** **v**ariable **ID**.
1352 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1353 #[derive(HashStable, TyEncodable, TyDecodable)]
1354 pub struct ConstVid<'tcx> {
1355     pub index: u32,
1356     pub phantom: PhantomData<&'tcx ()>,
1357 }
1358
1359 rustc_index::newtype_index! {
1360     /// A **region** (lifetime) **v**ariable **ID**.
1361     #[derive(HashStable)]
1362     pub struct RegionVid {
1363         DEBUG_FORMAT = custom,
1364     }
1365 }
1366
1367 impl Atom for RegionVid {
1368     fn index(self) -> usize {
1369         Idx::index(self)
1370     }
1371 }
1372
1373 rustc_index::newtype_index! {
1374     #[derive(HashStable)]
1375     pub struct BoundVar { .. }
1376 }
1377
1378 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1379 #[derive(HashStable)]
1380 pub struct BoundTy {
1381     pub var: BoundVar,
1382     pub kind: BoundTyKind,
1383 }
1384
1385 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1386 #[derive(HashStable)]
1387 pub enum BoundTyKind {
1388     Anon,
1389     Param(Symbol),
1390 }
1391
1392 impl From<BoundVar> for BoundTy {
1393     fn from(var: BoundVar) -> Self {
1394         BoundTy { var, kind: BoundTyKind::Anon }
1395     }
1396 }
1397
1398 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1399 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1400 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
1401 pub struct ExistentialProjection<'tcx> {
1402     pub item_def_id: DefId,
1403     pub substs: SubstsRef<'tcx>,
1404     pub term: Term<'tcx>,
1405 }
1406
1407 pub type PolyExistentialProjection<'tcx> = Binder<'tcx, ExistentialProjection<'tcx>>;
1408
1409 impl<'tcx> ExistentialProjection<'tcx> {
1410     /// Extracts the underlying existential trait reference from this projection.
1411     /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1412     /// then this function would return an `exists T. T: Iterator` existential trait
1413     /// reference.
1414     pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::ExistentialTraitRef<'tcx> {
1415         let def_id = tcx.parent(self.item_def_id);
1416         let subst_count = tcx.generics_of(def_id).count() - 1;
1417         let substs = tcx.intern_substs(&self.substs[..subst_count]);
1418         ty::ExistentialTraitRef { def_id, substs }
1419     }
1420
1421     pub fn with_self_ty(
1422         &self,
1423         tcx: TyCtxt<'tcx>,
1424         self_ty: Ty<'tcx>,
1425     ) -> ty::ProjectionPredicate<'tcx> {
1426         // otherwise the escaping regions would be captured by the binders
1427         debug_assert!(!self_ty.has_escaping_bound_vars());
1428
1429         ty::ProjectionPredicate {
1430             projection_ty: ty::ProjectionTy {
1431                 item_def_id: self.item_def_id,
1432                 substs: tcx.mk_substs_trait(self_ty, self.substs),
1433             },
1434             term: self.term,
1435         }
1436     }
1437
1438     pub fn erase_self_ty(
1439         tcx: TyCtxt<'tcx>,
1440         projection_predicate: ty::ProjectionPredicate<'tcx>,
1441     ) -> Self {
1442         // Assert there is a Self.
1443         projection_predicate.projection_ty.substs.type_at(0);
1444
1445         Self {
1446             item_def_id: projection_predicate.projection_ty.item_def_id,
1447             substs: tcx.intern_substs(&projection_predicate.projection_ty.substs[1..]),
1448             term: projection_predicate.term,
1449         }
1450     }
1451 }
1452
1453 impl<'tcx> PolyExistentialProjection<'tcx> {
1454     pub fn with_self_ty(
1455         &self,
1456         tcx: TyCtxt<'tcx>,
1457         self_ty: Ty<'tcx>,
1458     ) -> ty::PolyProjectionPredicate<'tcx> {
1459         self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1460     }
1461
1462     pub fn item_def_id(&self) -> DefId {
1463         self.skip_binder().item_def_id
1464     }
1465 }
1466
1467 /// Region utilities
1468 impl<'tcx> Region<'tcx> {
1469     pub fn kind(self) -> RegionKind<'tcx> {
1470         *self.0.0
1471     }
1472
1473     pub fn get_name(self) -> Option<Symbol> {
1474         if self.has_name() {
1475             let name = match *self {
1476                 ty::ReEarlyBound(ebr) => Some(ebr.name),
1477                 ty::ReLateBound(_, br) => br.kind.get_name(),
1478                 ty::ReFree(fr) => fr.bound_region.get_name(),
1479                 ty::ReStatic => Some(kw::StaticLifetime),
1480                 ty::RePlaceholder(placeholder) => placeholder.name.get_name(),
1481                 _ => None,
1482             };
1483
1484             return name;
1485         }
1486
1487         None
1488     }
1489
1490     /// Is this region named by the user?
1491     pub fn has_name(self) -> bool {
1492         match *self {
1493             ty::ReEarlyBound(ebr) => ebr.has_name(),
1494             ty::ReLateBound(_, br) => br.kind.is_named(),
1495             ty::ReFree(fr) => fr.bound_region.is_named(),
1496             ty::ReStatic => true,
1497             ty::ReVar(..) => false,
1498             ty::RePlaceholder(placeholder) => placeholder.name.is_named(),
1499             ty::ReErased => false,
1500         }
1501     }
1502
1503     #[inline]
1504     pub fn is_static(self) -> bool {
1505         matches!(*self, ty::ReStatic)
1506     }
1507
1508     #[inline]
1509     pub fn is_erased(self) -> bool {
1510         matches!(*self, ty::ReErased)
1511     }
1512
1513     #[inline]
1514     pub fn is_late_bound(self) -> bool {
1515         matches!(*self, ty::ReLateBound(..))
1516     }
1517
1518     #[inline]
1519     pub fn is_placeholder(self) -> bool {
1520         matches!(*self, ty::RePlaceholder(..))
1521     }
1522
1523     #[inline]
1524     pub fn bound_at_or_above_binder(self, index: ty::DebruijnIndex) -> bool {
1525         match *self {
1526             ty::ReLateBound(debruijn, _) => debruijn >= index,
1527             _ => false,
1528         }
1529     }
1530
1531     pub fn type_flags(self) -> TypeFlags {
1532         let mut flags = TypeFlags::empty();
1533
1534         match *self {
1535             ty::ReVar(..) => {
1536                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1537                 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1538                 flags = flags | TypeFlags::HAS_RE_INFER;
1539             }
1540             ty::RePlaceholder(..) => {
1541                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1542                 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1543                 flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
1544             }
1545             ty::ReEarlyBound(..) => {
1546                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1547                 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1548                 flags = flags | TypeFlags::HAS_RE_PARAM;
1549             }
1550             ty::ReFree { .. } => {
1551                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1552                 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1553             }
1554             ty::ReStatic => {
1555                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1556             }
1557             ty::ReLateBound(..) => {
1558                 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1559             }
1560             ty::ReErased => {
1561                 flags = flags | TypeFlags::HAS_RE_ERASED;
1562             }
1563         }
1564
1565         debug!("type_flags({:?}) = {:?}", self, flags);
1566
1567         flags
1568     }
1569
1570     /// Given an early-bound or free region, returns the `DefId` where it was bound.
1571     /// For example, consider the regions in this snippet of code:
1572     ///
1573     /// ```ignore (illustrative)
1574     /// impl<'a> Foo {
1575     /// //   ^^ -- early bound, declared on an impl
1576     ///
1577     ///     fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1578     /// //         ^^  ^^     ^ anonymous, late-bound
1579     /// //         |   early-bound, appears in where-clauses
1580     /// //         late-bound, appears only in fn args
1581     ///     {..}
1582     /// }
1583     /// ```
1584     ///
1585     /// Here, `free_region_binding_scope('a)` would return the `DefId`
1586     /// of the impl, and for all the other highlighted regions, it
1587     /// would return the `DefId` of the function. In other cases (not shown), this
1588     /// function might return the `DefId` of a closure.
1589     pub fn free_region_binding_scope(self, tcx: TyCtxt<'_>) -> DefId {
1590         match *self {
1591             ty::ReEarlyBound(br) => tcx.parent(br.def_id),
1592             ty::ReFree(fr) => fr.scope,
1593             _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1594         }
1595     }
1596
1597     /// True for free regions other than `'static`.
1598     pub fn is_free(self) -> bool {
1599         matches!(*self, ty::ReEarlyBound(_) | ty::ReFree(_))
1600     }
1601
1602     /// True if `self` is a free region or static.
1603     pub fn is_free_or_static(self) -> bool {
1604         match *self {
1605             ty::ReStatic => true,
1606             _ => self.is_free(),
1607         }
1608     }
1609
1610     pub fn is_var(self) -> bool {
1611         matches!(self.kind(), ty::ReVar(_))
1612     }
1613 }
1614
1615 /// Type utilities
1616 impl<'tcx> Ty<'tcx> {
1617     #[inline(always)]
1618     pub fn kind(self) -> &'tcx TyKind<'tcx> {
1619         &self.0.0.kind
1620     }
1621
1622     #[inline(always)]
1623     pub fn flags(self) -> TypeFlags {
1624         self.0.0.flags
1625     }
1626
1627     #[inline]
1628     pub fn is_unit(self) -> bool {
1629         match self.kind() {
1630             Tuple(ref tys) => tys.is_empty(),
1631             _ => false,
1632         }
1633     }
1634
1635     #[inline]
1636     pub fn is_never(self) -> bool {
1637         matches!(self.kind(), Never)
1638     }
1639
1640     #[inline]
1641     pub fn is_primitive(self) -> bool {
1642         self.kind().is_primitive()
1643     }
1644
1645     #[inline]
1646     pub fn is_adt(self) -> bool {
1647         matches!(self.kind(), Adt(..))
1648     }
1649
1650     #[inline]
1651     pub fn is_ref(self) -> bool {
1652         matches!(self.kind(), Ref(..))
1653     }
1654
1655     #[inline]
1656     pub fn is_ty_var(self) -> bool {
1657         matches!(self.kind(), Infer(TyVar(_)))
1658     }
1659
1660     #[inline]
1661     pub fn ty_vid(self) -> Option<ty::TyVid> {
1662         match self.kind() {
1663             &Infer(TyVar(vid)) => Some(vid),
1664             _ => None,
1665         }
1666     }
1667
1668     #[inline]
1669     pub fn is_ty_infer(self) -> bool {
1670         matches!(self.kind(), Infer(_))
1671     }
1672
1673     #[inline]
1674     pub fn is_phantom_data(self) -> bool {
1675         if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1676     }
1677
1678     #[inline]
1679     pub fn is_bool(self) -> bool {
1680         *self.kind() == Bool
1681     }
1682
1683     /// Returns `true` if this type is a `str`.
1684     #[inline]
1685     pub fn is_str(self) -> bool {
1686         *self.kind() == Str
1687     }
1688
1689     #[inline]
1690     pub fn is_param(self, index: u32) -> bool {
1691         match self.kind() {
1692             ty::Param(ref data) => data.index == index,
1693             _ => false,
1694         }
1695     }
1696
1697     #[inline]
1698     pub fn is_slice(self) -> bool {
1699         matches!(self.kind(), Slice(_))
1700     }
1701
1702     #[inline]
1703     pub fn is_array_slice(self) -> bool {
1704         match self.kind() {
1705             Slice(_) => true,
1706             RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_)),
1707             _ => false,
1708         }
1709     }
1710
1711     #[inline]
1712     pub fn is_array(self) -> bool {
1713         matches!(self.kind(), Array(..))
1714     }
1715
1716     #[inline]
1717     pub fn is_simd(self) -> bool {
1718         match self.kind() {
1719             Adt(def, _) => def.repr().simd(),
1720             _ => false,
1721         }
1722     }
1723
1724     pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1725         match self.kind() {
1726             Array(ty, _) | Slice(ty) => *ty,
1727             Str => tcx.types.u8,
1728             _ => bug!("`sequence_element_type` called on non-sequence value: {}", self),
1729         }
1730     }
1731
1732     pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1733         match self.kind() {
1734             Adt(def, substs) => {
1735                 assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type");
1736                 let variant = def.non_enum_variant();
1737                 let f0_ty = variant.fields[0].ty(tcx, substs);
1738
1739                 match f0_ty.kind() {
1740                     // If the first field is an array, we assume it is the only field and its
1741                     // elements are the SIMD components.
1742                     Array(f0_elem_ty, f0_len) => {
1743                         // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112
1744                         // The way we evaluate the `N` in `[T; N]` here only works since we use
1745                         // `simd_size_and_type` post-monomorphization. It will probably start to ICE
1746                         // if we use it in generic code. See the `simd-array-trait` ui test.
1747                         (f0_len.eval_usize(tcx, ParamEnv::empty()) as u64, *f0_elem_ty)
1748                     }
1749                     // Otherwise, the fields of this Adt are the SIMD components (and we assume they
1750                     // all have the same type).
1751                     _ => (variant.fields.len() as u64, f0_ty),
1752                 }
1753             }
1754             _ => bug!("`simd_size_and_type` called on invalid type"),
1755         }
1756     }
1757
1758     #[inline]
1759     pub fn is_region_ptr(self) -> bool {
1760         matches!(self.kind(), Ref(..))
1761     }
1762
1763     #[inline]
1764     pub fn is_mutable_ptr(self) -> bool {
1765         matches!(
1766             self.kind(),
1767             RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. })
1768                 | Ref(_, _, hir::Mutability::Mut)
1769         )
1770     }
1771
1772     /// Get the mutability of the reference or `None` when not a reference
1773     #[inline]
1774     pub fn ref_mutability(self) -> Option<hir::Mutability> {
1775         match self.kind() {
1776             Ref(_, _, mutability) => Some(*mutability),
1777             _ => None,
1778         }
1779     }
1780
1781     #[inline]
1782     pub fn is_unsafe_ptr(self) -> bool {
1783         matches!(self.kind(), RawPtr(_))
1784     }
1785
1786     /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1787     #[inline]
1788     pub fn is_any_ptr(self) -> bool {
1789         self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr()
1790     }
1791
1792     #[inline]
1793     pub fn is_box(self) -> bool {
1794         match self.kind() {
1795             Adt(def, _) => def.is_box(),
1796             _ => false,
1797         }
1798     }
1799
1800     /// Panics if called on any type other than `Box<T>`.
1801     pub fn boxed_ty(self) -> Ty<'tcx> {
1802         match self.kind() {
1803             Adt(def, substs) if def.is_box() => substs.type_at(0),
1804             _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1805         }
1806     }
1807
1808     /// A scalar type is one that denotes an atomic datum, with no sub-components.
1809     /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1810     /// contents are abstract to rustc.)
1811     #[inline]
1812     pub fn is_scalar(self) -> bool {
1813         matches!(
1814             self.kind(),
1815             Bool | Char
1816                 | Int(_)
1817                 | Float(_)
1818                 | Uint(_)
1819                 | FnDef(..)
1820                 | FnPtr(_)
1821                 | RawPtr(_)
1822                 | Infer(IntVar(_) | FloatVar(_))
1823         )
1824     }
1825
1826     /// Returns `true` if this type is a floating point type.
1827     #[inline]
1828     pub fn is_floating_point(self) -> bool {
1829         matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1830     }
1831
1832     #[inline]
1833     pub fn is_trait(self) -> bool {
1834         matches!(self.kind(), Dynamic(_, _, ty::Dyn))
1835     }
1836
1837     #[inline]
1838     pub fn is_dyn_star(self) -> bool {
1839         matches!(self.kind(), Dynamic(_, _, ty::DynStar))
1840     }
1841
1842     #[inline]
1843     pub fn is_enum(self) -> bool {
1844         matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1845     }
1846
1847     #[inline]
1848     pub fn is_union(self) -> bool {
1849         matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1850     }
1851
1852     #[inline]
1853     pub fn is_closure(self) -> bool {
1854         matches!(self.kind(), Closure(..))
1855     }
1856
1857     #[inline]
1858     pub fn is_generator(self) -> bool {
1859         matches!(self.kind(), Generator(..))
1860     }
1861
1862     #[inline]
1863     pub fn is_integral(self) -> bool {
1864         matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1865     }
1866
1867     #[inline]
1868     pub fn is_fresh_ty(self) -> bool {
1869         matches!(self.kind(), Infer(FreshTy(_)))
1870     }
1871
1872     #[inline]
1873     pub fn is_fresh(self) -> bool {
1874         matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1875     }
1876
1877     #[inline]
1878     pub fn is_char(self) -> bool {
1879         matches!(self.kind(), Char)
1880     }
1881
1882     #[inline]
1883     pub fn is_numeric(self) -> bool {
1884         self.is_integral() || self.is_floating_point()
1885     }
1886
1887     #[inline]
1888     pub fn is_signed(self) -> bool {
1889         matches!(self.kind(), Int(_))
1890     }
1891
1892     #[inline]
1893     pub fn is_ptr_sized_integral(self) -> bool {
1894         matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
1895     }
1896
1897     #[inline]
1898     pub fn has_concrete_skeleton(self) -> bool {
1899         !matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1900     }
1901
1902     /// Checks whether a type recursively contains another type
1903     ///
1904     /// Example: `Option<()>` contains `()`
1905     pub fn contains(self, other: Ty<'tcx>) -> bool {
1906         struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1907
1908         impl<'tcx> TypeVisitor<'tcx> for ContainsTyVisitor<'tcx> {
1909             type BreakTy = ();
1910
1911             fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1912                 if self.0 == t { ControlFlow::BREAK } else { t.super_visit_with(self) }
1913             }
1914         }
1915
1916         let cf = self.visit_with(&mut ContainsTyVisitor(other));
1917         cf.is_break()
1918     }
1919
1920     /// Returns the type and mutability of `*ty`.
1921     ///
1922     /// The parameter `explicit` indicates if this is an *explicit* dereference.
1923     /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
1924     pub fn builtin_deref(self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1925         match self.kind() {
1926             Adt(def, _) if def.is_box() => {
1927                 Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not })
1928             }
1929             Ref(_, ty, mutbl) => Some(TypeAndMut { ty: *ty, mutbl: *mutbl }),
1930             RawPtr(mt) if explicit => Some(*mt),
1931             _ => None,
1932         }
1933     }
1934
1935     /// Returns the type of `ty[i]`.
1936     pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1937         match self.kind() {
1938             Array(ty, _) | Slice(ty) => Some(*ty),
1939             _ => None,
1940         }
1941     }
1942
1943     pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1944         match self.kind() {
1945             FnDef(def_id, substs) => tcx.bound_fn_sig(*def_id).subst(tcx, substs),
1946             FnPtr(f) => *f,
1947             Error(_) => {
1948                 // ignore errors (#54954)
1949                 ty::Binder::dummy(FnSig::fake())
1950             }
1951             Closure(..) => bug!(
1952                 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1953             ),
1954             _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self),
1955         }
1956     }
1957
1958     #[inline]
1959     pub fn is_fn(self) -> bool {
1960         matches!(self.kind(), FnDef(..) | FnPtr(_))
1961     }
1962
1963     #[inline]
1964     pub fn is_fn_ptr(self) -> bool {
1965         matches!(self.kind(), FnPtr(_))
1966     }
1967
1968     #[inline]
1969     pub fn is_impl_trait(self) -> bool {
1970         matches!(self.kind(), Opaque(..))
1971     }
1972
1973     #[inline]
1974     pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1975         match self.kind() {
1976             Adt(adt, _) => Some(*adt),
1977             _ => None,
1978         }
1979     }
1980
1981     /// Iterates over tuple fields.
1982     /// Panics when called on anything but a tuple.
1983     #[inline]
1984     pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1985         match self.kind() {
1986             Tuple(substs) => substs,
1987             _ => bug!("tuple_fields called on non-tuple"),
1988         }
1989     }
1990
1991     /// If the type contains variants, returns the valid range of variant indices.
1992     //
1993     // FIXME: This requires the optimized MIR in the case of generators.
1994     #[inline]
1995     pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1996         match self.kind() {
1997             TyKind::Adt(adt, _) => Some(adt.variant_range()),
1998             TyKind::Generator(def_id, substs, _) => {
1999                 Some(substs.as_generator().variant_range(*def_id, tcx))
2000             }
2001             _ => None,
2002         }
2003     }
2004
2005     /// If the type contains variants, returns the variant for `variant_index`.
2006     /// Panics if `variant_index` is out of range.
2007     //
2008     // FIXME: This requires the optimized MIR in the case of generators.
2009     #[inline]
2010     pub fn discriminant_for_variant(
2011         self,
2012         tcx: TyCtxt<'tcx>,
2013         variant_index: VariantIdx,
2014     ) -> Option<Discr<'tcx>> {
2015         match self.kind() {
2016             TyKind::Adt(adt, _) if adt.variants().is_empty() => {
2017                 // This can actually happen during CTFE, see
2018                 // https://github.com/rust-lang/rust/issues/89765.
2019                 None
2020             }
2021             TyKind::Adt(adt, _) if adt.is_enum() => {
2022                 Some(adt.discriminant_for_variant(tcx, variant_index))
2023             }
2024             TyKind::Generator(def_id, substs, _) => {
2025                 Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index))
2026             }
2027             _ => None,
2028         }
2029     }
2030
2031     /// Returns the type of the discriminant of this type.
2032     pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2033         match self.kind() {
2034             ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
2035             ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx),
2036
2037             ty::Param(_) | ty::Projection(_) | ty::Opaque(..) | ty::Infer(ty::TyVar(_)) => {
2038                 let assoc_items = tcx.associated_item_def_ids(
2039                     tcx.require_lang_item(hir::LangItem::DiscriminantKind, None),
2040                 );
2041                 tcx.mk_projection(assoc_items[0], tcx.intern_substs(&[self.into()]))
2042             }
2043
2044             ty::Bool
2045             | ty::Char
2046             | ty::Int(_)
2047             | ty::Uint(_)
2048             | ty::Float(_)
2049             | ty::Adt(..)
2050             | ty::Foreign(_)
2051             | ty::Str
2052             | ty::Array(..)
2053             | ty::Slice(_)
2054             | ty::RawPtr(_)
2055             | ty::Ref(..)
2056             | ty::FnDef(..)
2057             | ty::FnPtr(..)
2058             | ty::Dynamic(..)
2059             | ty::Closure(..)
2060             | ty::GeneratorWitness(..)
2061             | ty::Never
2062             | ty::Tuple(_)
2063             | ty::Error(_)
2064             | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
2065
2066             ty::Bound(..)
2067             | ty::Placeholder(_)
2068             | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2069                 bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
2070             }
2071         }
2072     }
2073
2074     /// Returns the type of metadata for (potentially fat) pointers to this type,
2075     /// and a boolean signifying if this is conditional on this type being `Sized`.
2076     pub fn ptr_metadata_ty(
2077         self,
2078         tcx: TyCtxt<'tcx>,
2079         normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
2080     ) -> (Ty<'tcx>, bool) {
2081         let tail = tcx.struct_tail_with_normalize(self, normalize, || {});
2082         match tail.kind() {
2083             // Sized types
2084             ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2085             | ty::Uint(_)
2086             | ty::Int(_)
2087             | ty::Bool
2088             | ty::Float(_)
2089             | ty::FnDef(..)
2090             | ty::FnPtr(_)
2091             | ty::RawPtr(..)
2092             | ty::Char
2093             | ty::Ref(..)
2094             | ty::Generator(..)
2095             | ty::GeneratorWitness(..)
2096             | ty::Array(..)
2097             | ty::Closure(..)
2098             | ty::Never
2099             | ty::Error(_)
2100             // Extern types have metadata = ().
2101             | ty::Foreign(..)
2102             // If returned by `struct_tail_without_normalization` this is a unit struct
2103             // without any fields, or not a struct, and therefore is Sized.
2104             | ty::Adt(..)
2105             // If returned by `struct_tail_without_normalization` this is the empty tuple,
2106             // a.k.a. unit type, which is Sized
2107             | ty::Tuple(..) => (tcx.types.unit, false),
2108
2109             ty::Str | ty::Slice(_) => (tcx.types.usize, false),
2110             ty::Dynamic(..) => {
2111                 let dyn_metadata = tcx.lang_items().dyn_metadata().unwrap();
2112                 (tcx.bound_type_of(dyn_metadata).subst(tcx, &[tail.into()]), false)
2113             },
2114
2115             // type parameters only have unit metadata if they're sized, so return true
2116             // to make sure we double check this during confirmation
2117             ty::Param(_) |  ty::Projection(_) | ty::Opaque(..) => (tcx.types.unit, true),
2118
2119             ty::Infer(ty::TyVar(_))
2120             | ty::Bound(..)
2121             | ty::Placeholder(..)
2122             | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2123                 bug!("`ptr_metadata_ty` applied to unexpected type: {:?} (tail = {:?})", self, tail)
2124             }
2125         }
2126     }
2127
2128     /// When we create a closure, we record its kind (i.e., what trait
2129     /// it implements) into its `ClosureSubsts` using a type
2130     /// parameter. This is kind of a phantom type, except that the
2131     /// most convenient thing for us to are the integral types. This
2132     /// function converts such a special type into the closure
2133     /// kind. To go the other way, use
2134     /// `tcx.closure_kind_ty(closure_kind)`.
2135     ///
2136     /// Note that during type checking, we use an inference variable
2137     /// to represent the closure kind, because it has not yet been
2138     /// inferred. Once upvar inference (in `rustc_hir_analysis/src/check/upvar.rs`)
2139     /// is complete, that type variable will be unified.
2140     pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
2141         match self.kind() {
2142             Int(int_ty) => match int_ty {
2143                 ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
2144                 ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
2145                 ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
2146                 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2147             },
2148
2149             // "Bound" types appear in canonical queries when the
2150             // closure type is not yet known
2151             Bound(..) | Infer(_) => None,
2152
2153             Error(_) => Some(ty::ClosureKind::Fn),
2154
2155             _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2156         }
2157     }
2158
2159     /// Fast path helper for testing if a type is `Sized`.
2160     ///
2161     /// Returning true means the type is known to be sized. Returning
2162     /// `false` means nothing -- could be sized, might not be.
2163     ///
2164     /// Note that we could never rely on the fact that a type such as `[_]` is
2165     /// trivially `!Sized` because we could be in a type environment with a
2166     /// bound such as `[_]: Copy`. A function with such a bound obviously never
2167     /// can be called, but that doesn't mean it shouldn't typecheck. This is why
2168     /// this method doesn't return `Option<bool>`.
2169     pub fn is_trivially_sized(self, tcx: TyCtxt<'tcx>) -> bool {
2170         match self.kind() {
2171             ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2172             | ty::Uint(_)
2173             | ty::Int(_)
2174             | ty::Bool
2175             | ty::Float(_)
2176             | ty::FnDef(..)
2177             | ty::FnPtr(_)
2178             | ty::RawPtr(..)
2179             | ty::Char
2180             | ty::Ref(..)
2181             | ty::Generator(..)
2182             | ty::GeneratorWitness(..)
2183             | ty::Array(..)
2184             | ty::Closure(..)
2185             | ty::Never
2186             | ty::Error(_) => true,
2187
2188             ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => false,
2189
2190             ty::Tuple(tys) => tys.iter().all(|ty| ty.is_trivially_sized(tcx)),
2191
2192             ty::Adt(def, _substs) => def.sized_constraint(tcx).0.is_empty(),
2193
2194             ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
2195
2196             ty::Infer(ty::TyVar(_)) => false,
2197
2198             ty::Bound(..)
2199             | ty::Placeholder(..)
2200             | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2201                 bug!("`is_trivially_sized` applied to unexpected type: {:?}", self)
2202             }
2203         }
2204     }
2205
2206     /// Fast path helper for primitives which are always `Copy` and which
2207     /// have a side-effect-free `Clone` impl.
2208     ///
2209     /// Returning true means the type is known to be pure and `Copy+Clone`.
2210     /// Returning `false` means nothing -- could be `Copy`, might not be.
2211     ///
2212     /// This is mostly useful for optimizations, as there are the types
2213     /// on which we can replace cloning with dereferencing.
2214     pub fn is_trivially_pure_clone_copy(self) -> bool {
2215         match self.kind() {
2216             ty::Bool | ty::Char | ty::Never => true,
2217
2218             // These aren't even `Clone`
2219             ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
2220
2221             ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
2222             | ty::Int(..)
2223             | ty::Uint(..)
2224             | ty::Float(..) => true,
2225
2226             // The voldemort ZSTs are fine.
2227             ty::FnDef(..) => true,
2228
2229             ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
2230
2231             // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
2232             ty::Tuple(field_tys) => {
2233                 field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
2234             }
2235
2236             // Sometimes traits aren't implemented for every ABI or arity,
2237             // because we can't be generic over everything yet.
2238             ty::FnPtr(..) => false,
2239
2240             // Definitely absolutely not copy.
2241             ty::Ref(_, _, hir::Mutability::Mut) => false,
2242
2243             // Thin pointers & thin shared references are pure-clone-copy, but for
2244             // anything with custom metadata it might be more complicated.
2245             ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => false,
2246
2247             ty::Generator(..) | ty::GeneratorWitness(..) => false,
2248
2249             // Might be, but not "trivial" so just giving the safe answer.
2250             ty::Adt(..) | ty::Closure(..) | ty::Opaque(..) => false,
2251
2252             ty::Projection(..) | ty::Param(..) | ty::Infer(..) | ty::Error(..) => false,
2253
2254             ty::Bound(..) | ty::Placeholder(..) => {
2255                 bug!("`is_trivially_pure_clone_copy` applied to unexpected type: {:?}", self);
2256             }
2257         }
2258     }
2259
2260     // If `self` is a primitive, return its [`Symbol`].
2261     pub fn primitive_symbol(self) -> Option<Symbol> {
2262         match self.kind() {
2263             ty::Bool => Some(sym::bool),
2264             ty::Char => Some(sym::char),
2265             ty::Float(f) => match f {
2266                 ty::FloatTy::F32 => Some(sym::f32),
2267                 ty::FloatTy::F64 => Some(sym::f64),
2268             },
2269             ty::Int(f) => match f {
2270                 ty::IntTy::Isize => Some(sym::isize),
2271                 ty::IntTy::I8 => Some(sym::i8),
2272                 ty::IntTy::I16 => Some(sym::i16),
2273                 ty::IntTy::I32 => Some(sym::i32),
2274                 ty::IntTy::I64 => Some(sym::i64),
2275                 ty::IntTy::I128 => Some(sym::i128),
2276             },
2277             ty::Uint(f) => match f {
2278                 ty::UintTy::Usize => Some(sym::usize),
2279                 ty::UintTy::U8 => Some(sym::u8),
2280                 ty::UintTy::U16 => Some(sym::u16),
2281                 ty::UintTy::U32 => Some(sym::u32),
2282                 ty::UintTy::U64 => Some(sym::u64),
2283                 ty::UintTy::U128 => Some(sym::u128),
2284             },
2285             _ => None,
2286         }
2287     }
2288 }
2289
2290 /// Extra information about why we ended up with a particular variance.
2291 /// This is only used to add more information to error messages, and
2292 /// has no effect on soundness. While choosing the 'wrong' `VarianceDiagInfo`
2293 /// may lead to confusing notes in error messages, it will never cause
2294 /// a miscompilation or unsoundness.
2295 ///
2296 /// When in doubt, use `VarianceDiagInfo::default()`
2297 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
2298 pub enum VarianceDiagInfo<'tcx> {
2299     /// No additional information - this is the default.
2300     /// We will not add any additional information to error messages.
2301     #[default]
2302     None,
2303     /// We switched our variance because a generic argument occurs inside
2304     /// the invariant generic argument of another type.
2305     Invariant {
2306         /// The generic type containing the generic parameter
2307         /// that changes the variance (e.g. `*mut T`, `MyStruct<T>`)
2308         ty: Ty<'tcx>,
2309         /// The index of the generic parameter being used
2310         /// (e.g. `0` for `*mut T`, `1` for `MyStruct<'CovariantParam, 'InvariantParam>`)
2311         param_index: u32,
2312     },
2313 }
2314
2315 impl<'tcx> VarianceDiagInfo<'tcx> {
2316     /// Mirrors `Variance::xform` - used to 'combine' the existing
2317     /// and new `VarianceDiagInfo`s when our variance changes.
2318     pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> {
2319         // For now, just use the first `VarianceDiagInfo::Invariant` that we see
2320         match self {
2321             VarianceDiagInfo::None => other,
2322             VarianceDiagInfo::Invariant { .. } => self,
2323         }
2324     }
2325 }