]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/sty.rs
Auto merge of #106399 - estebank:type-err-span-label, r=nagisa
[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.iter().map(move |field| {
575                 ty::EarlyBinder(layout.field_tys[*field].ty).subst(tcx, self.substs)
576             })
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 `AliasTy` 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 kind(self, tcx: TyCtxt<'tcx>) -> ty::AliasKind {
1255         match tcx.def_kind(self.def_id) {
1256             DefKind::AssocTy | DefKind::ImplTraitPlaceholder => ty::Projection,
1257             DefKind::OpaqueTy => ty::Opaque,
1258             kind => bug!("unexpected DefKind in AliasTy: {kind:?}"),
1259         }
1260     }
1261
1262     pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1263         tcx.mk_ty(ty::Alias(self.kind(tcx), self))
1264     }
1265 }
1266
1267 /// The following methods work only with associated type projections.
1268 impl<'tcx> AliasTy<'tcx> {
1269     pub fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId {
1270         match tcx.def_kind(self.def_id) {
1271             DefKind::AssocTy | DefKind::AssocConst => tcx.parent(self.def_id),
1272             DefKind::ImplTraitPlaceholder => {
1273                 tcx.parent(tcx.impl_trait_in_trait_parent(self.def_id))
1274             }
1275             kind => bug!("expected a projection AliasTy; found {kind:?}"),
1276         }
1277     }
1278
1279     /// Extracts the underlying trait reference and own substs from this projection.
1280     /// For example, if this is a projection of `<T as StreamingIterator>::Item<'a>`,
1281     /// then this function would return a `T: Iterator` trait reference and `['a]` as the own substs
1282     pub fn trait_ref_and_own_substs(
1283         self,
1284         tcx: TyCtxt<'tcx>,
1285     ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) {
1286         debug_assert!(matches!(tcx.def_kind(self.def_id), DefKind::AssocTy | DefKind::AssocConst));
1287         let trait_def_id = self.trait_def_id(tcx);
1288         let trait_generics = tcx.generics_of(trait_def_id);
1289         (
1290             tcx.mk_trait_ref(trait_def_id, self.substs.truncate_to(tcx, trait_generics)),
1291             &self.substs[trait_generics.count()..],
1292         )
1293     }
1294
1295     /// Extracts the underlying trait reference from this projection.
1296     /// For example, if this is a projection of `<T as Iterator>::Item`,
1297     /// then this function would return a `T: Iterator` trait reference.
1298     ///
1299     /// WARNING: This will drop the substs for generic associated types
1300     /// consider calling [Self::trait_ref_and_own_substs] to get those
1301     /// as well.
1302     pub fn trait_ref(self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> {
1303         let def_id = self.trait_def_id(tcx);
1304         tcx.mk_trait_ref(def_id, self.substs.truncate_to(tcx, tcx.generics_of(def_id)))
1305     }
1306
1307     pub fn self_ty(self) -> Ty<'tcx> {
1308         self.substs.type_at(0)
1309     }
1310
1311     pub fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
1312         tcx.mk_alias_ty(self.def_id, [self_ty.into()].into_iter().chain(self.substs.iter().skip(1)))
1313     }
1314 }
1315
1316 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
1317 pub struct GenSig<'tcx> {
1318     pub resume_ty: Ty<'tcx>,
1319     pub yield_ty: Ty<'tcx>,
1320     pub return_ty: Ty<'tcx>,
1321 }
1322
1323 pub type PolyGenSig<'tcx> = Binder<'tcx, GenSig<'tcx>>;
1324
1325 /// Signature of a function type, which we have arbitrarily
1326 /// decided to use to refer to the input/output types.
1327 ///
1328 /// - `inputs`: is the list of arguments and their modes.
1329 /// - `output`: is the return type.
1330 /// - `c_variadic`: indicates whether this is a C-variadic function.
1331 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
1332 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
1333 pub struct FnSig<'tcx> {
1334     pub inputs_and_output: &'tcx List<Ty<'tcx>>,
1335     pub c_variadic: bool,
1336     pub unsafety: hir::Unsafety,
1337     pub abi: abi::Abi,
1338 }
1339
1340 impl<'tcx> FnSig<'tcx> {
1341     pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
1342         &self.inputs_and_output[..self.inputs_and_output.len() - 1]
1343     }
1344
1345     pub fn output(&self) -> Ty<'tcx> {
1346         self.inputs_and_output[self.inputs_and_output.len() - 1]
1347     }
1348
1349     // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible
1350     // method.
1351     fn fake() -> FnSig<'tcx> {
1352         FnSig {
1353             inputs_and_output: List::empty(),
1354             c_variadic: false,
1355             unsafety: hir::Unsafety::Normal,
1356             abi: abi::Abi::Rust,
1357         }
1358     }
1359 }
1360
1361 pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
1362
1363 impl<'tcx> PolyFnSig<'tcx> {
1364     #[inline]
1365     pub fn inputs(&self) -> Binder<'tcx, &'tcx [Ty<'tcx>]> {
1366         self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs())
1367     }
1368     #[inline]
1369     pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> {
1370         self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
1371     }
1372     pub fn inputs_and_output(&self) -> ty::Binder<'tcx, &'tcx List<Ty<'tcx>>> {
1373         self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
1374     }
1375     #[inline]
1376     pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> {
1377         self.map_bound_ref(|fn_sig| fn_sig.output())
1378     }
1379     pub fn c_variadic(&self) -> bool {
1380         self.skip_binder().c_variadic
1381     }
1382     pub fn unsafety(&self) -> hir::Unsafety {
1383         self.skip_binder().unsafety
1384     }
1385     pub fn abi(&self) -> abi::Abi {
1386         self.skip_binder().abi
1387     }
1388 }
1389
1390 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
1391
1392 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
1393 #[derive(HashStable)]
1394 pub struct ParamTy {
1395     pub index: u32,
1396     pub name: Symbol,
1397 }
1398
1399 impl<'tcx> ParamTy {
1400     pub fn new(index: u32, name: Symbol) -> ParamTy {
1401         ParamTy { index, name }
1402     }
1403
1404     pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1405         ParamTy::new(def.index, def.name)
1406     }
1407
1408     #[inline]
1409     pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1410         tcx.mk_ty_param(self.index, self.name)
1411     }
1412
1413     pub fn span_from_generics(&self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
1414         let generics = tcx.generics_of(item_with_generics);
1415         let type_param = generics.type_param(self, tcx);
1416         tcx.def_span(type_param.def_id)
1417     }
1418 }
1419
1420 #[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)]
1421 #[derive(HashStable)]
1422 pub struct ParamConst {
1423     pub index: u32,
1424     pub name: Symbol,
1425 }
1426
1427 impl ParamConst {
1428     pub fn new(index: u32, name: Symbol) -> ParamConst {
1429         ParamConst { index, name }
1430     }
1431
1432     pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
1433         ParamConst::new(def.index, def.name)
1434     }
1435 }
1436
1437 /// Use this rather than `RegionKind`, whenever possible.
1438 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
1439 #[rustc_pass_by_value]
1440 pub struct Region<'tcx>(pub Interned<'tcx, RegionKind<'tcx>>);
1441
1442 impl<'tcx> Deref for Region<'tcx> {
1443     type Target = RegionKind<'tcx>;
1444
1445     #[inline]
1446     fn deref(&self) -> &RegionKind<'tcx> {
1447         &self.0.0
1448     }
1449 }
1450
1451 impl<'tcx> fmt::Debug for Region<'tcx> {
1452     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1453         write!(f, "{:?}", self.kind())
1454     }
1455 }
1456
1457 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1458 #[derive(HashStable)]
1459 pub struct EarlyBoundRegion {
1460     pub def_id: DefId,
1461     pub index: u32,
1462     pub name: Symbol,
1463 }
1464
1465 impl fmt::Debug for EarlyBoundRegion {
1466     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1467         write!(f, "{}, {}", self.index, self.name)
1468     }
1469 }
1470
1471 /// A **`const`** **v**ariable **ID**.
1472 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1473 #[derive(HashStable, TyEncodable, TyDecodable)]
1474 pub struct ConstVid<'tcx> {
1475     pub index: u32,
1476     pub phantom: PhantomData<&'tcx ()>,
1477 }
1478
1479 rustc_index::newtype_index! {
1480     /// A **region** (lifetime) **v**ariable **ID**.
1481     #[derive(HashStable)]
1482     #[debug_format = "'_#{}r"]
1483     pub struct RegionVid {}
1484 }
1485
1486 impl Atom for RegionVid {
1487     fn index(self) -> usize {
1488         Idx::index(self)
1489     }
1490 }
1491
1492 rustc_index::newtype_index! {
1493     #[derive(HashStable)]
1494     pub struct BoundVar {}
1495 }
1496
1497 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1498 #[derive(HashStable)]
1499 pub struct BoundTy {
1500     pub var: BoundVar,
1501     pub kind: BoundTyKind,
1502 }
1503
1504 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1505 #[derive(HashStable)]
1506 pub enum BoundTyKind {
1507     Anon,
1508     Param(Symbol),
1509 }
1510
1511 impl From<BoundVar> for BoundTy {
1512     fn from(var: BoundVar) -> Self {
1513         BoundTy { var, kind: BoundTyKind::Anon }
1514     }
1515 }
1516
1517 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1518 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1519 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
1520 pub struct ExistentialProjection<'tcx> {
1521     pub def_id: DefId,
1522     pub substs: SubstsRef<'tcx>,
1523     pub term: Term<'tcx>,
1524 }
1525
1526 pub type PolyExistentialProjection<'tcx> = Binder<'tcx, ExistentialProjection<'tcx>>;
1527
1528 impl<'tcx> ExistentialProjection<'tcx> {
1529     /// Extracts the underlying existential trait reference from this projection.
1530     /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1531     /// then this function would return an `exists T. T: Iterator` existential trait
1532     /// reference.
1533     pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::ExistentialTraitRef<'tcx> {
1534         let def_id = tcx.parent(self.def_id);
1535         let subst_count = tcx.generics_of(def_id).count() - 1;
1536         let substs = tcx.intern_substs(&self.substs[..subst_count]);
1537         ty::ExistentialTraitRef { def_id, substs }
1538     }
1539
1540     pub fn with_self_ty(
1541         &self,
1542         tcx: TyCtxt<'tcx>,
1543         self_ty: Ty<'tcx>,
1544     ) -> ty::ProjectionPredicate<'tcx> {
1545         // otherwise the escaping regions would be captured by the binders
1546         debug_assert!(!self_ty.has_escaping_bound_vars());
1547
1548         ty::ProjectionPredicate {
1549             projection_ty: tcx
1550                 .mk_alias_ty(self.def_id, [self_ty.into()].into_iter().chain(self.substs)),
1551             term: self.term,
1552         }
1553     }
1554
1555     pub fn erase_self_ty(
1556         tcx: TyCtxt<'tcx>,
1557         projection_predicate: ty::ProjectionPredicate<'tcx>,
1558     ) -> Self {
1559         // Assert there is a Self.
1560         projection_predicate.projection_ty.substs.type_at(0);
1561
1562         Self {
1563             def_id: projection_predicate.projection_ty.def_id,
1564             substs: tcx.intern_substs(&projection_predicate.projection_ty.substs[1..]),
1565             term: projection_predicate.term,
1566         }
1567     }
1568 }
1569
1570 impl<'tcx> PolyExistentialProjection<'tcx> {
1571     pub fn with_self_ty(
1572         &self,
1573         tcx: TyCtxt<'tcx>,
1574         self_ty: Ty<'tcx>,
1575     ) -> ty::PolyProjectionPredicate<'tcx> {
1576         self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1577     }
1578
1579     pub fn item_def_id(&self) -> DefId {
1580         self.skip_binder().def_id
1581     }
1582 }
1583
1584 /// Region utilities
1585 impl<'tcx> Region<'tcx> {
1586     pub fn kind(self) -> RegionKind<'tcx> {
1587         *self.0.0
1588     }
1589
1590     pub fn get_name(self) -> Option<Symbol> {
1591         if self.has_name() {
1592             let name = match *self {
1593                 ty::ReEarlyBound(ebr) => Some(ebr.name),
1594                 ty::ReLateBound(_, br) => br.kind.get_name(),
1595                 ty::ReFree(fr) => fr.bound_region.get_name(),
1596                 ty::ReStatic => Some(kw::StaticLifetime),
1597                 ty::RePlaceholder(placeholder) => placeholder.name.get_name(),
1598                 _ => None,
1599             };
1600
1601             return name;
1602         }
1603
1604         None
1605     }
1606
1607     /// Is this region named by the user?
1608     pub fn has_name(self) -> bool {
1609         match *self {
1610             ty::ReEarlyBound(ebr) => ebr.has_name(),
1611             ty::ReLateBound(_, br) => br.kind.is_named(),
1612             ty::ReFree(fr) => fr.bound_region.is_named(),
1613             ty::ReStatic => true,
1614             ty::ReVar(..) => false,
1615             ty::RePlaceholder(placeholder) => placeholder.name.is_named(),
1616             ty::ReErased => false,
1617         }
1618     }
1619
1620     #[inline]
1621     pub fn is_static(self) -> bool {
1622         matches!(*self, ty::ReStatic)
1623     }
1624
1625     #[inline]
1626     pub fn is_erased(self) -> bool {
1627         matches!(*self, ty::ReErased)
1628     }
1629
1630     #[inline]
1631     pub fn is_late_bound(self) -> bool {
1632         matches!(*self, ty::ReLateBound(..))
1633     }
1634
1635     #[inline]
1636     pub fn is_placeholder(self) -> bool {
1637         matches!(*self, ty::RePlaceholder(..))
1638     }
1639
1640     #[inline]
1641     pub fn bound_at_or_above_binder(self, index: ty::DebruijnIndex) -> bool {
1642         match *self {
1643             ty::ReLateBound(debruijn, _) => debruijn >= index,
1644             _ => false,
1645         }
1646     }
1647
1648     pub fn type_flags(self) -> TypeFlags {
1649         let mut flags = TypeFlags::empty();
1650
1651         match *self {
1652             ty::ReVar(..) => {
1653                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1654                 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1655                 flags = flags | TypeFlags::HAS_RE_INFER;
1656             }
1657             ty::RePlaceholder(..) => {
1658                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1659                 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1660                 flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
1661             }
1662             ty::ReEarlyBound(..) => {
1663                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1664                 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1665                 flags = flags | TypeFlags::HAS_RE_PARAM;
1666             }
1667             ty::ReFree { .. } => {
1668                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1669                 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1670             }
1671             ty::ReStatic => {
1672                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1673             }
1674             ty::ReLateBound(..) => {
1675                 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1676             }
1677             ty::ReErased => {
1678                 flags = flags | TypeFlags::HAS_RE_ERASED;
1679             }
1680         }
1681
1682         debug!("type_flags({:?}) = {:?}", self, flags);
1683
1684         flags
1685     }
1686
1687     /// Given an early-bound or free region, returns the `DefId` where it was bound.
1688     /// For example, consider the regions in this snippet of code:
1689     ///
1690     /// ```ignore (illustrative)
1691     /// impl<'a> Foo {
1692     /// //   ^^ -- early bound, declared on an impl
1693     ///
1694     ///     fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1695     /// //         ^^  ^^     ^ anonymous, late-bound
1696     /// //         |   early-bound, appears in where-clauses
1697     /// //         late-bound, appears only in fn args
1698     ///     {..}
1699     /// }
1700     /// ```
1701     ///
1702     /// Here, `free_region_binding_scope('a)` would return the `DefId`
1703     /// of the impl, and for all the other highlighted regions, it
1704     /// would return the `DefId` of the function. In other cases (not shown), this
1705     /// function might return the `DefId` of a closure.
1706     pub fn free_region_binding_scope(self, tcx: TyCtxt<'_>) -> DefId {
1707         match *self {
1708             ty::ReEarlyBound(br) => tcx.parent(br.def_id),
1709             ty::ReFree(fr) => fr.scope,
1710             _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1711         }
1712     }
1713
1714     /// True for free regions other than `'static`.
1715     pub fn is_free(self) -> bool {
1716         matches!(*self, ty::ReEarlyBound(_) | ty::ReFree(_))
1717     }
1718
1719     /// True if `self` is a free region or static.
1720     pub fn is_free_or_static(self) -> bool {
1721         match *self {
1722             ty::ReStatic => true,
1723             _ => self.is_free(),
1724         }
1725     }
1726
1727     pub fn is_var(self) -> bool {
1728         matches!(self.kind(), ty::ReVar(_))
1729     }
1730 }
1731
1732 /// Type utilities
1733 impl<'tcx> Ty<'tcx> {
1734     #[inline(always)]
1735     pub fn kind(self) -> &'tcx TyKind<'tcx> {
1736         &self.0.0
1737     }
1738
1739     #[inline(always)]
1740     pub fn flags(self) -> TypeFlags {
1741         self.0.0.flags
1742     }
1743
1744     #[inline]
1745     pub fn is_unit(self) -> bool {
1746         match self.kind() {
1747             Tuple(ref tys) => tys.is_empty(),
1748             _ => false,
1749         }
1750     }
1751
1752     #[inline]
1753     pub fn is_never(self) -> bool {
1754         matches!(self.kind(), Never)
1755     }
1756
1757     #[inline]
1758     pub fn is_primitive(self) -> bool {
1759         self.kind().is_primitive()
1760     }
1761
1762     #[inline]
1763     pub fn is_adt(self) -> bool {
1764         matches!(self.kind(), Adt(..))
1765     }
1766
1767     #[inline]
1768     pub fn is_ref(self) -> bool {
1769         matches!(self.kind(), Ref(..))
1770     }
1771
1772     #[inline]
1773     pub fn is_ty_var(self) -> bool {
1774         matches!(self.kind(), Infer(TyVar(_)))
1775     }
1776
1777     #[inline]
1778     pub fn ty_vid(self) -> Option<ty::TyVid> {
1779         match self.kind() {
1780             &Infer(TyVar(vid)) => Some(vid),
1781             _ => None,
1782         }
1783     }
1784
1785     #[inline]
1786     pub fn is_ty_or_numeric_infer(self) -> bool {
1787         matches!(self.kind(), Infer(_))
1788     }
1789
1790     #[inline]
1791     pub fn is_phantom_data(self) -> bool {
1792         if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1793     }
1794
1795     #[inline]
1796     pub fn is_bool(self) -> bool {
1797         *self.kind() == Bool
1798     }
1799
1800     /// Returns `true` if this type is a `str`.
1801     #[inline]
1802     pub fn is_str(self) -> bool {
1803         *self.kind() == Str
1804     }
1805
1806     #[inline]
1807     pub fn is_param(self, index: u32) -> bool {
1808         match self.kind() {
1809             ty::Param(ref data) => data.index == index,
1810             _ => false,
1811         }
1812     }
1813
1814     #[inline]
1815     pub fn is_slice(self) -> bool {
1816         matches!(self.kind(), Slice(_))
1817     }
1818
1819     #[inline]
1820     pub fn is_array_slice(self) -> bool {
1821         match self.kind() {
1822             Slice(_) => true,
1823             RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_)),
1824             _ => false,
1825         }
1826     }
1827
1828     #[inline]
1829     pub fn is_array(self) -> bool {
1830         matches!(self.kind(), Array(..))
1831     }
1832
1833     #[inline]
1834     pub fn is_simd(self) -> bool {
1835         match self.kind() {
1836             Adt(def, _) => def.repr().simd(),
1837             _ => false,
1838         }
1839     }
1840
1841     pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1842         match self.kind() {
1843             Array(ty, _) | Slice(ty) => *ty,
1844             Str => tcx.types.u8,
1845             _ => bug!("`sequence_element_type` called on non-sequence value: {}", self),
1846         }
1847     }
1848
1849     pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1850         match self.kind() {
1851             Adt(def, substs) => {
1852                 assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type");
1853                 let variant = def.non_enum_variant();
1854                 let f0_ty = variant.fields[0].ty(tcx, substs);
1855
1856                 match f0_ty.kind() {
1857                     // If the first field is an array, we assume it is the only field and its
1858                     // elements are the SIMD components.
1859                     Array(f0_elem_ty, f0_len) => {
1860                         // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112
1861                         // The way we evaluate the `N` in `[T; N]` here only works since we use
1862                         // `simd_size_and_type` post-monomorphization. It will probably start to ICE
1863                         // if we use it in generic code. See the `simd-array-trait` ui test.
1864                         (f0_len.eval_usize(tcx, ParamEnv::empty()) as u64, *f0_elem_ty)
1865                     }
1866                     // Otherwise, the fields of this Adt are the SIMD components (and we assume they
1867                     // all have the same type).
1868                     _ => (variant.fields.len() as u64, f0_ty),
1869                 }
1870             }
1871             _ => bug!("`simd_size_and_type` called on invalid type"),
1872         }
1873     }
1874
1875     #[inline]
1876     pub fn is_region_ptr(self) -> bool {
1877         matches!(self.kind(), Ref(..))
1878     }
1879
1880     #[inline]
1881     pub fn is_mutable_ptr(self) -> bool {
1882         matches!(
1883             self.kind(),
1884             RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. })
1885                 | Ref(_, _, hir::Mutability::Mut)
1886         )
1887     }
1888
1889     /// Get the mutability of the reference or `None` when not a reference
1890     #[inline]
1891     pub fn ref_mutability(self) -> Option<hir::Mutability> {
1892         match self.kind() {
1893             Ref(_, _, mutability) => Some(*mutability),
1894             _ => None,
1895         }
1896     }
1897
1898     #[inline]
1899     pub fn is_unsafe_ptr(self) -> bool {
1900         matches!(self.kind(), RawPtr(_))
1901     }
1902
1903     /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1904     #[inline]
1905     pub fn is_any_ptr(self) -> bool {
1906         self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr()
1907     }
1908
1909     #[inline]
1910     pub fn is_box(self) -> bool {
1911         match self.kind() {
1912             Adt(def, _) => def.is_box(),
1913             _ => false,
1914         }
1915     }
1916
1917     /// Panics if called on any type other than `Box<T>`.
1918     pub fn boxed_ty(self) -> Ty<'tcx> {
1919         match self.kind() {
1920             Adt(def, substs) if def.is_box() => substs.type_at(0),
1921             _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1922         }
1923     }
1924
1925     /// A scalar type is one that denotes an atomic datum, with no sub-components.
1926     /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1927     /// contents are abstract to rustc.)
1928     #[inline]
1929     pub fn is_scalar(self) -> bool {
1930         matches!(
1931             self.kind(),
1932             Bool | Char
1933                 | Int(_)
1934                 | Float(_)
1935                 | Uint(_)
1936                 | FnDef(..)
1937                 | FnPtr(_)
1938                 | RawPtr(_)
1939                 | Infer(IntVar(_) | FloatVar(_))
1940         )
1941     }
1942
1943     /// Returns `true` if this type is a floating point type.
1944     #[inline]
1945     pub fn is_floating_point(self) -> bool {
1946         matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1947     }
1948
1949     #[inline]
1950     pub fn is_trait(self) -> bool {
1951         matches!(self.kind(), Dynamic(_, _, ty::Dyn))
1952     }
1953
1954     #[inline]
1955     pub fn is_dyn_star(self) -> bool {
1956         matches!(self.kind(), Dynamic(_, _, ty::DynStar))
1957     }
1958
1959     #[inline]
1960     pub fn is_enum(self) -> bool {
1961         matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1962     }
1963
1964     #[inline]
1965     pub fn is_union(self) -> bool {
1966         matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1967     }
1968
1969     #[inline]
1970     pub fn is_closure(self) -> bool {
1971         matches!(self.kind(), Closure(..))
1972     }
1973
1974     #[inline]
1975     pub fn is_generator(self) -> bool {
1976         matches!(self.kind(), Generator(..))
1977     }
1978
1979     #[inline]
1980     pub fn is_integral(self) -> bool {
1981         matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1982     }
1983
1984     #[inline]
1985     pub fn is_fresh_ty(self) -> bool {
1986         matches!(self.kind(), Infer(FreshTy(_)))
1987     }
1988
1989     #[inline]
1990     pub fn is_fresh(self) -> bool {
1991         matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1992     }
1993
1994     #[inline]
1995     pub fn is_char(self) -> bool {
1996         matches!(self.kind(), Char)
1997     }
1998
1999     #[inline]
2000     pub fn is_numeric(self) -> bool {
2001         self.is_integral() || self.is_floating_point()
2002     }
2003
2004     #[inline]
2005     pub fn is_signed(self) -> bool {
2006         matches!(self.kind(), Int(_))
2007     }
2008
2009     #[inline]
2010     pub fn is_ptr_sized_integral(self) -> bool {
2011         matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
2012     }
2013
2014     #[inline]
2015     pub fn has_concrete_skeleton(self) -> bool {
2016         !matches!(self.kind(), Param(_) | Infer(_) | Error(_))
2017     }
2018
2019     /// Checks whether a type recursively contains another type
2020     ///
2021     /// Example: `Option<()>` contains `()`
2022     pub fn contains(self, other: Ty<'tcx>) -> bool {
2023         struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
2024
2025         impl<'tcx> TypeVisitor<'tcx> for ContainsTyVisitor<'tcx> {
2026             type BreakTy = ();
2027
2028             fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2029                 if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
2030             }
2031         }
2032
2033         let cf = self.visit_with(&mut ContainsTyVisitor(other));
2034         cf.is_break()
2035     }
2036
2037     /// Returns the type and mutability of `*ty`.
2038     ///
2039     /// The parameter `explicit` indicates if this is an *explicit* dereference.
2040     /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
2041     pub fn builtin_deref(self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
2042         match self.kind() {
2043             Adt(def, _) if def.is_box() => {
2044                 Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not })
2045             }
2046             Ref(_, ty, mutbl) => Some(TypeAndMut { ty: *ty, mutbl: *mutbl }),
2047             RawPtr(mt) if explicit => Some(*mt),
2048             _ => None,
2049         }
2050     }
2051
2052     /// Returns the type of `ty[i]`.
2053     pub fn builtin_index(self) -> Option<Ty<'tcx>> {
2054         match self.kind() {
2055             Array(ty, _) | Slice(ty) => Some(*ty),
2056             _ => None,
2057         }
2058     }
2059
2060     pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
2061         match self.kind() {
2062             FnDef(def_id, substs) => tcx.fn_sig(*def_id).subst(tcx, substs),
2063             FnPtr(f) => *f,
2064             Error(_) => {
2065                 // ignore errors (#54954)
2066                 ty::Binder::dummy(FnSig::fake())
2067             }
2068             Closure(..) => bug!(
2069                 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
2070             ),
2071             _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self),
2072         }
2073     }
2074
2075     #[inline]
2076     pub fn is_fn(self) -> bool {
2077         matches!(self.kind(), FnDef(..) | FnPtr(_))
2078     }
2079
2080     #[inline]
2081     pub fn is_fn_ptr(self) -> bool {
2082         matches!(self.kind(), FnPtr(_))
2083     }
2084
2085     #[inline]
2086     pub fn is_impl_trait(self) -> bool {
2087         matches!(self.kind(), Alias(ty::Opaque, ..))
2088     }
2089
2090     #[inline]
2091     pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
2092         match self.kind() {
2093             Adt(adt, _) => Some(*adt),
2094             _ => None,
2095         }
2096     }
2097
2098     /// Iterates over tuple fields.
2099     /// Panics when called on anything but a tuple.
2100     #[inline]
2101     pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
2102         match self.kind() {
2103             Tuple(substs) => substs,
2104             _ => bug!("tuple_fields called on non-tuple"),
2105         }
2106     }
2107
2108     /// If the type contains variants, returns the valid range of variant indices.
2109     //
2110     // FIXME: This requires the optimized MIR in the case of generators.
2111     #[inline]
2112     pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
2113         match self.kind() {
2114             TyKind::Adt(adt, _) => Some(adt.variant_range()),
2115             TyKind::Generator(def_id, substs, _) => {
2116                 Some(substs.as_generator().variant_range(*def_id, tcx))
2117             }
2118             _ => None,
2119         }
2120     }
2121
2122     /// If the type contains variants, returns the variant for `variant_index`.
2123     /// Panics if `variant_index` is out of range.
2124     //
2125     // FIXME: This requires the optimized MIR in the case of generators.
2126     #[inline]
2127     pub fn discriminant_for_variant(
2128         self,
2129         tcx: TyCtxt<'tcx>,
2130         variant_index: VariantIdx,
2131     ) -> Option<Discr<'tcx>> {
2132         match self.kind() {
2133             TyKind::Adt(adt, _) if adt.variants().is_empty() => {
2134                 // This can actually happen during CTFE, see
2135                 // https://github.com/rust-lang/rust/issues/89765.
2136                 None
2137             }
2138             TyKind::Adt(adt, _) if adt.is_enum() => {
2139                 Some(adt.discriminant_for_variant(tcx, variant_index))
2140             }
2141             TyKind::Generator(def_id, substs, _) => {
2142                 Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index))
2143             }
2144             _ => None,
2145         }
2146     }
2147
2148     /// Returns the type of the discriminant of this type.
2149     pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2150         match self.kind() {
2151             ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
2152             ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx),
2153
2154             ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
2155                 let assoc_items = tcx.associated_item_def_ids(
2156                     tcx.require_lang_item(hir::LangItem::DiscriminantKind, None),
2157                 );
2158                 tcx.mk_projection(assoc_items[0], tcx.intern_substs(&[self.into()]))
2159             }
2160
2161             ty::Bool
2162             | ty::Char
2163             | ty::Int(_)
2164             | ty::Uint(_)
2165             | ty::Float(_)
2166             | ty::Adt(..)
2167             | ty::Foreign(_)
2168             | ty::Str
2169             | ty::Array(..)
2170             | ty::Slice(_)
2171             | ty::RawPtr(_)
2172             | ty::Ref(..)
2173             | ty::FnDef(..)
2174             | ty::FnPtr(..)
2175             | ty::Dynamic(..)
2176             | ty::Closure(..)
2177             | ty::GeneratorWitness(..)
2178             | ty::GeneratorWitnessMIR(..)
2179             | ty::Never
2180             | ty::Tuple(_)
2181             | ty::Error(_)
2182             | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
2183
2184             ty::Bound(..)
2185             | ty::Placeholder(_)
2186             | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2187                 bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
2188             }
2189         }
2190     }
2191
2192     /// Returns the type of metadata for (potentially fat) pointers to this type,
2193     /// and a boolean signifying if this is conditional on this type being `Sized`.
2194     pub fn ptr_metadata_ty(
2195         self,
2196         tcx: TyCtxt<'tcx>,
2197         normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
2198     ) -> (Ty<'tcx>, bool) {
2199         let tail = tcx.struct_tail_with_normalize(self, normalize, || {});
2200         match tail.kind() {
2201             // Sized types
2202             ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2203             | ty::Uint(_)
2204             | ty::Int(_)
2205             | ty::Bool
2206             | ty::Float(_)
2207             | ty::FnDef(..)
2208             | ty::FnPtr(_)
2209             | ty::RawPtr(..)
2210             | ty::Char
2211             | ty::Ref(..)
2212             | ty::Generator(..)
2213             | ty::GeneratorWitness(..)
2214             | ty::GeneratorWitnessMIR(..)
2215             | ty::Array(..)
2216             | ty::Closure(..)
2217             | ty::Never
2218             | ty::Error(_)
2219             // Extern types have metadata = ().
2220             | ty::Foreign(..)
2221             // If returned by `struct_tail_without_normalization` this is a unit struct
2222             // without any fields, or not a struct, and therefore is Sized.
2223             | ty::Adt(..)
2224             // If returned by `struct_tail_without_normalization` this is the empty tuple,
2225             // a.k.a. unit type, which is Sized
2226             | ty::Tuple(..) => (tcx.types.unit, false),
2227
2228             ty::Str | ty::Slice(_) => (tcx.types.usize, false),
2229             ty::Dynamic(..) => {
2230                 let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, None);
2231                 (tcx.bound_type_of(dyn_metadata).subst(tcx, &[tail.into()]), false)
2232             },
2233
2234             // type parameters only have unit metadata if they're sized, so return true
2235             // to make sure we double check this during confirmation
2236             ty::Param(_) |  ty::Alias(..) => (tcx.types.unit, true),
2237
2238             ty::Infer(ty::TyVar(_))
2239             | ty::Bound(..)
2240             | ty::Placeholder(..)
2241             | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2242                 bug!("`ptr_metadata_ty` applied to unexpected type: {:?} (tail = {:?})", self, tail)
2243             }
2244         }
2245     }
2246
2247     /// When we create a closure, we record its kind (i.e., what trait
2248     /// it implements) into its `ClosureSubsts` using a type
2249     /// parameter. This is kind of a phantom type, except that the
2250     /// most convenient thing for us to are the integral types. This
2251     /// function converts such a special type into the closure
2252     /// kind. To go the other way, use `closure_kind.to_ty(tcx)`.
2253     ///
2254     /// Note that during type checking, we use an inference variable
2255     /// to represent the closure kind, because it has not yet been
2256     /// inferred. Once upvar inference (in `rustc_hir_analysis/src/check/upvar.rs`)
2257     /// is complete, that type variable will be unified.
2258     pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
2259         match self.kind() {
2260             Int(int_ty) => match int_ty {
2261                 ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
2262                 ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
2263                 ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
2264                 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2265             },
2266
2267             // "Bound" types appear in canonical queries when the
2268             // closure type is not yet known
2269             Bound(..) | Infer(_) => None,
2270
2271             Error(_) => Some(ty::ClosureKind::Fn),
2272
2273             _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2274         }
2275     }
2276
2277     /// Fast path helper for testing if a type is `Sized`.
2278     ///
2279     /// Returning true means the type is known to be sized. Returning
2280     /// `false` means nothing -- could be sized, might not be.
2281     ///
2282     /// Note that we could never rely on the fact that a type such as `[_]` is
2283     /// trivially `!Sized` because we could be in a type environment with a
2284     /// bound such as `[_]: Copy`. A function with such a bound obviously never
2285     /// can be called, but that doesn't mean it shouldn't typecheck. This is why
2286     /// this method doesn't return `Option<bool>`.
2287     pub fn is_trivially_sized(self, tcx: TyCtxt<'tcx>) -> bool {
2288         match self.kind() {
2289             ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2290             | ty::Uint(_)
2291             | ty::Int(_)
2292             | ty::Bool
2293             | ty::Float(_)
2294             | ty::FnDef(..)
2295             | ty::FnPtr(_)
2296             | ty::RawPtr(..)
2297             | ty::Char
2298             | ty::Ref(..)
2299             | ty::Generator(..)
2300             | ty::GeneratorWitness(..)
2301             | ty::GeneratorWitnessMIR(..)
2302             | ty::Array(..)
2303             | ty::Closure(..)
2304             | ty::Never
2305             | ty::Error(_) => true,
2306
2307             ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => false,
2308
2309             ty::Tuple(tys) => tys.iter().all(|ty| ty.is_trivially_sized(tcx)),
2310
2311             ty::Adt(def, _substs) => def.sized_constraint(tcx).0.is_empty(),
2312
2313             ty::Alias(..) | ty::Param(_) => false,
2314
2315             ty::Infer(ty::TyVar(_)) => false,
2316
2317             ty::Bound(..)
2318             | ty::Placeholder(..)
2319             | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2320                 bug!("`is_trivially_sized` applied to unexpected type: {:?}", self)
2321             }
2322         }
2323     }
2324
2325     /// Fast path helper for primitives which are always `Copy` and which
2326     /// have a side-effect-free `Clone` impl.
2327     ///
2328     /// Returning true means the type is known to be pure and `Copy+Clone`.
2329     /// Returning `false` means nothing -- could be `Copy`, might not be.
2330     ///
2331     /// This is mostly useful for optimizations, as there are the types
2332     /// on which we can replace cloning with dereferencing.
2333     pub fn is_trivially_pure_clone_copy(self) -> bool {
2334         match self.kind() {
2335             ty::Bool | ty::Char | ty::Never => true,
2336
2337             // These aren't even `Clone`
2338             ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
2339
2340             ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
2341             | ty::Int(..)
2342             | ty::Uint(..)
2343             | ty::Float(..) => true,
2344
2345             // The voldemort ZSTs are fine.
2346             ty::FnDef(..) => true,
2347
2348             ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
2349
2350             // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
2351             ty::Tuple(field_tys) => {
2352                 field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
2353             }
2354
2355             // Sometimes traits aren't implemented for every ABI or arity,
2356             // because we can't be generic over everything yet.
2357             ty::FnPtr(..) => false,
2358
2359             // Definitely absolutely not copy.
2360             ty::Ref(_, _, hir::Mutability::Mut) => false,
2361
2362             // Thin pointers & thin shared references are pure-clone-copy, but for
2363             // anything with custom metadata it might be more complicated.
2364             ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => false,
2365
2366             ty::Generator(..) | ty::GeneratorWitness(..) | ty::GeneratorWitnessMIR(..) => false,
2367
2368             // Might be, but not "trivial" so just giving the safe answer.
2369             ty::Adt(..) | ty::Closure(..) => false,
2370
2371             // Needs normalization or revealing to determine, so no is the safe answer.
2372             ty::Alias(..) => false,
2373
2374             ty::Param(..) | ty::Infer(..) | ty::Error(..) => false,
2375
2376             ty::Bound(..) | ty::Placeholder(..) => {
2377                 bug!("`is_trivially_pure_clone_copy` applied to unexpected type: {:?}", self);
2378             }
2379         }
2380     }
2381
2382     /// If `self` is a primitive, return its [`Symbol`].
2383     pub fn primitive_symbol(self) -> Option<Symbol> {
2384         match self.kind() {
2385             ty::Bool => Some(sym::bool),
2386             ty::Char => Some(sym::char),
2387             ty::Float(f) => match f {
2388                 ty::FloatTy::F32 => Some(sym::f32),
2389                 ty::FloatTy::F64 => Some(sym::f64),
2390             },
2391             ty::Int(f) => match f {
2392                 ty::IntTy::Isize => Some(sym::isize),
2393                 ty::IntTy::I8 => Some(sym::i8),
2394                 ty::IntTy::I16 => Some(sym::i16),
2395                 ty::IntTy::I32 => Some(sym::i32),
2396                 ty::IntTy::I64 => Some(sym::i64),
2397                 ty::IntTy::I128 => Some(sym::i128),
2398             },
2399             ty::Uint(f) => match f {
2400                 ty::UintTy::Usize => Some(sym::usize),
2401                 ty::UintTy::U8 => Some(sym::u8),
2402                 ty::UintTy::U16 => Some(sym::u16),
2403                 ty::UintTy::U32 => Some(sym::u32),
2404                 ty::UintTy::U64 => Some(sym::u64),
2405                 ty::UintTy::U128 => Some(sym::u128),
2406             },
2407             _ => None,
2408         }
2409     }
2410 }
2411
2412 /// Extra information about why we ended up with a particular variance.
2413 /// This is only used to add more information to error messages, and
2414 /// has no effect on soundness. While choosing the 'wrong' `VarianceDiagInfo`
2415 /// may lead to confusing notes in error messages, it will never cause
2416 /// a miscompilation or unsoundness.
2417 ///
2418 /// When in doubt, use `VarianceDiagInfo::default()`
2419 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
2420 pub enum VarianceDiagInfo<'tcx> {
2421     /// No additional information - this is the default.
2422     /// We will not add any additional information to error messages.
2423     #[default]
2424     None,
2425     /// We switched our variance because a generic argument occurs inside
2426     /// the invariant generic argument of another type.
2427     Invariant {
2428         /// The generic type containing the generic parameter
2429         /// that changes the variance (e.g. `*mut T`, `MyStruct<T>`)
2430         ty: Ty<'tcx>,
2431         /// The index of the generic parameter being used
2432         /// (e.g. `0` for `*mut T`, `1` for `MyStruct<'CovariantParam, 'InvariantParam>`)
2433         param_index: u32,
2434     },
2435 }
2436
2437 impl<'tcx> VarianceDiagInfo<'tcx> {
2438     /// Mirrors `Variance::xform` - used to 'combine' the existing
2439     /// and new `VarianceDiagInfo`s when our variance changes.
2440     pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> {
2441         // For now, just use the first `VarianceDiagInfo::Invariant` that we see
2442         match self {
2443             VarianceDiagInfo::None => other,
2444             VarianceDiagInfo::Invariant { .. } => self,
2445         }
2446     }
2447 }