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