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