Skip to main content

rustc_middle/ty/
structural_impls.rs

1//! This module contains implementations of the `Lift`, `TypeFoldable` and
2//! `TypeVisitable` traits for various types in the Rust compiler. Most are
3//! written by hand, though we've recently added some macros and proc-macros
4//! to help with the tedium.
5
6use std::fmt::{self, Debug};
7use std::marker::PhantomData;
8
9use rustc_abi::TyAndLayout;
10use rustc_hir::def::Namespace;
11use rustc_hir::def_id::LocalDefId;
12use rustc_span::source_map::Spanned;
13use rustc_type_ir::{ConstKind, TypeFolder, VisitorResult, try_visit};
14
15use super::{GenericArg, GenericArgKind, Pattern, Region};
16use crate::mir::PlaceElem;
17use crate::ty::print::{FmtPrinter, Printer, with_no_trimmed_paths};
18use crate::ty::{
19    self, FallibleTypeFolder, Lift, Term, TermKind, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable,
20    TypeSuperVisitable, TypeVisitable, TypeVisitor,
21};
22
23impl fmt::Debug for ty::TraitDef {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        ty::tls::with(|tcx| {
26            {
    let _guard = NoTrimmedGuard::new();
    {
        let s =
            FmtPrinter::print_string(tcx, Namespace::TypeNS,
                    |p| { p.print_def_path(self.def_id, &[]) })?;
        f.write_str(&s)
    }
}with_no_trimmed_paths!({
27                let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |p| {
28                    p.print_def_path(self.def_id, &[])
29                })?;
30                f.write_str(&s)
31            })
32        })
33    }
34}
35
36impl<'tcx> fmt::Debug for ty::AdtDef<'tcx> {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        ty::tls::with(|tcx| {
39            {
    let _guard = NoTrimmedGuard::new();
    {
        let s =
            FmtPrinter::print_string(tcx, Namespace::TypeNS,
                    |p| { p.print_def_path(self.did(), &[]) })?;
        f.write_str(&s)
    }
}with_no_trimmed_paths!({
40                let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |p| {
41                    p.print_def_path(self.did(), &[])
42                })?;
43                f.write_str(&s)
44            })
45        })
46    }
47}
48
49impl fmt::Debug for ty::UpvarId {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        let name = ty::tls::with(|tcx| tcx.hir_name(self.var_path.hir_id));
52        f.write_fmt(format_args!("UpvarId({0:?};`{1}`;{2:?})", self.var_path.hir_id,
        name, self.closure_expr_id))write!(f, "UpvarId({:?};`{}`;{:?})", self.var_path.hir_id, name, self.closure_expr_id)
53    }
54}
55
56impl<'tcx> fmt::Debug for ty::adjustment::Adjustment<'tcx> {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        f.write_fmt(format_args!("{0:?} -> {1}", self.kind, self.target))write!(f, "{:?} -> {}", self.kind, self.target)
59    }
60}
61
62impl<'tcx> fmt::Debug for ty::adjustment::PatAdjustment<'tcx> {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.write_fmt(format_args!("{0} -> {1:?}", self.source, self.kind))write!(f, "{} -> {:?}", self.source, self.kind)
65    }
66}
67
68impl fmt::Debug for ty::LateParamRegion {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.write_fmt(format_args!("ReLateParam({0:?}, {1:?})", self.scope, self.kind))write!(f, "ReLateParam({:?}, {:?})", self.scope, self.kind)
71    }
72}
73
74impl fmt::Debug for ty::LateParamRegionKind {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        match *self {
77            ty::LateParamRegionKind::Anon(idx) => f.write_fmt(format_args!("LateAnon({0})", idx))write!(f, "LateAnon({idx})"),
78            ty::LateParamRegionKind::NamedAnon(idx, name) => {
79                f.write_fmt(format_args!("LateNamedAnon({0:?}, {1})", idx, name))write!(f, "LateNamedAnon({idx:?}, {name})")
80            }
81            ty::LateParamRegionKind::Named(did) => {
82                f.write_fmt(format_args!("LateNamed({0:?})", did))write!(f, "LateNamed({did:?})")
83            }
84            ty::LateParamRegionKind::ClosureEnv => f.write_fmt(format_args!("LateEnv"))write!(f, "LateEnv"),
85        }
86    }
87}
88
89impl<'tcx> fmt::Debug for Ty<'tcx> {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        { let _guard = NoTrimmedGuard::new(); fmt::Debug::fmt(self.kind(), f) }with_no_trimmed_paths!(fmt::Debug::fmt(self.kind(), f))
92    }
93}
94
95impl fmt::Debug for ty::ParamTy {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        f.write_fmt(format_args!("{0}/#{1}", self.name, self.index))write!(f, "{}/#{}", self.name, self.index)
98    }
99}
100
101impl fmt::Debug for ty::ParamConst {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.write_fmt(format_args!("{0}/#{1}", self.name, self.index))write!(f, "{}/#{}", self.name, self.index)
104    }
105}
106
107impl<'tcx> fmt::Debug for ty::Predicate<'tcx> {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        f.write_fmt(format_args!("{0:?}", self.kind()))write!(f, "{:?}", self.kind())
110    }
111}
112
113impl<'tcx> fmt::Debug for ty::Clause<'tcx> {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.write_fmt(format_args!("{0:?}", self.kind()))write!(f, "{:?}", self.kind())
116    }
117}
118
119impl<'tcx> fmt::Debug for ty::consts::Expr<'tcx> {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        match self.kind {
122            ty::ExprKind::Binop(op) => {
123                let (lhs_ty, rhs_ty, lhs, rhs) = self.binop_args();
124                f.write_fmt(format_args!("({4:?}: ({0:?}: {1:?}), ({2:?}: {3:?}))", lhs,
        lhs_ty, rhs, rhs_ty, op))write!(f, "({op:?}: ({:?}: {:?}), ({:?}: {:?}))", lhs, lhs_ty, rhs, rhs_ty,)
125            }
126            ty::ExprKind::UnOp(op) => {
127                let (rhs_ty, rhs) = self.unop_args();
128                f.write_fmt(format_args!("({2:?}: ({0:?}: {1:?}))", rhs, rhs_ty, op))write!(f, "({op:?}: ({:?}: {:?}))", rhs, rhs_ty)
129            }
130            ty::ExprKind::FunctionCall => {
131                let (func_ty, func, args) = self.call_args();
132                let args = args.collect::<Vec<_>>();
133                f.write_fmt(format_args!("({0:?}: {1:?})(", func, func_ty))write!(f, "({:?}: {:?})(", func, func_ty)?;
134                for arg in args.iter().rev().skip(1).rev() {
135                    f.write_fmt(format_args!("{0:?}, ", arg))write!(f, "{:?}, ", arg)?;
136                }
137                if let Some(arg) = args.last() {
138                    f.write_fmt(format_args!("{0:?}", arg))write!(f, "{:?}", arg)?;
139                }
140
141                f.write_fmt(format_args!(")"))write!(f, ")")
142            }
143            ty::ExprKind::Cast(kind) => {
144                let (value_ty, value, to_ty) = self.cast_args();
145                f.write_fmt(format_args!("({3:?}: ({0:?}: {1:?}), {2:?})", value, value_ty,
        to_ty, kind))write!(f, "({kind:?}: ({:?}: {:?}), {:?})", value, value_ty, to_ty)
146            }
147        }
148    }
149}
150
151impl<'tcx> fmt::Debug for ty::Const<'tcx> {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        // If this is a value, we spend some effort to make it look nice.
154        if let ConstKind::Value(cv) = self.kind() {
155            f.write_fmt(format_args!("{0}", cv))write!(f, "{}", cv)
156        } else {
157            // Fall back to something verbose.
158            f.write_fmt(format_args!("{0:?}", self.kind()))write!(f, "{:?}", self.kind())
159        }
160    }
161}
162
163impl<'tcx> fmt::Debug for GenericArg<'tcx> {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        match self.kind() {
166            GenericArgKind::Lifetime(lt) => lt.fmt(f),
167            GenericArgKind::Type(ty) => ty.fmt(f),
168            GenericArgKind::Const(ct) => ct.fmt(f),
169        }
170    }
171}
172
173impl<'tcx> fmt::Debug for Region<'tcx> {
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        f.write_fmt(format_args!("{0:?}", self.kind()))write!(f, "{:?}", self.kind())
176    }
177}
178
179///////////////////////////////////////////////////////////////////////////
180// Atomic structs
181//
182// For things that don't carry any arena-allocated data (and are
183// copy...), just add them to one of these lists as appropriate.
184
185// For things for which the type library provides traversal implementations
186// for all Interners, we only need to provide a Lift implementation.
187impl<'tcx> crate::ty::Lift<crate::ty::TyCtxt<'tcx>> for
    rustc_type_ir::PredicatePolarity {
    type Lifted = Self;
    fn lift_to_interner(self, _: crate::ty::TyCtxt<'tcx>) -> Option<Self> {
        Some(self)
    }
}TrivialLiftImpls! {
188    (),
189    bool,
190    usize,
191    u64,
192    // tidy-alphabetical-start
193    crate::mir::Promoted,
194    crate::mir::interpret::AllocId,
195    crate::mir::interpret::Scalar,
196    crate::ty::ParamConst,
197    rustc_abi::ExternAbi,
198    rustc_abi::Size,
199    rustc_hir::Safety,
200    rustc_middle::mir::ConstValue,
201    rustc_type_ir::BoundConstness,
202    rustc_type_ir::PredicatePolarity,
203    // tidy-alphabetical-end
204}
205
206// For some things about which the type library does not know, or does not
207// provide any traversal implementations, we need to provide a traversal
208// implementation (only for TyCtxt<'_> interners).
209impl<'tcx> crate::ty::TypeFoldable<crate::ty::TyCtxt<'tcx>> for
    rustc_target::asm::InlineAsmRegOrRegClass {
    fn try_fold_with<F: crate::ty::FallibleTypeFolder<crate::ty::TyCtxt<'tcx>>>(self,
        _: &mut F) -> ::std::result::Result<Self, F::Error> {
        Ok(self)
    }
    #[inline]
    fn fold_with<F: crate::ty::TypeFolder<crate::ty::TyCtxt<'tcx>>>(self,
        _: &mut F) -> Self {
        self
    }
}
impl<'tcx> crate::ty::TypeVisitable<crate::ty::TyCtxt<'tcx>> for
    rustc_target::asm::InlineAsmRegOrRegClass {
    #[inline]
    fn visit_with<F: crate::ty::TypeVisitor<crate::ty::TyCtxt<'tcx>>>(&self,
        _: &mut F) -> F::Result {
        <F::Result as ::rustc_middle::ty::VisitorResult>::output()
    }
}TrivialTypeTraversalImpls! {
210    // tidy-alphabetical-start
211    crate::infer::canonical::Certainty,
212    crate::mir::BasicBlock,
213    crate::mir::BindingForm<'tcx>,
214    crate::mir::BlockTailInfo,
215    crate::mir::BorrowKind,
216    crate::mir::CastKind,
217    crate::mir::ConstValue,
218    crate::mir::CoroutineSavedLocal,
219    crate::mir::FakeReadCause,
220    crate::mir::Local,
221    crate::mir::MirPhase,
222    crate::mir::Promoted,
223    crate::mir::RawPtrKind,
224    crate::mir::RetagKind,
225    crate::mir::SourceInfo,
226    crate::mir::SourceScope,
227    crate::mir::SourceScopeLocalData,
228    crate::mir::SwitchTargets,
229    crate::traits::IsConstable,
230    crate::traits::OverflowError,
231    crate::ty::AdtKind,
232    crate::ty::AssocItem,
233    crate::ty::AssocKind,
234    crate::ty::BoundRegion<'tcx>,
235    crate::ty::BoundTy<'tcx>,
236    crate::ty::ScalarInt,
237    crate::ty::UserTypeAnnotationIndex,
238    crate::ty::abstract_const::NotConstEvaluatable,
239    crate::ty::adjustment::AutoBorrowMutability,
240    crate::ty::adjustment::PointerCoercion,
241    rustc_abi::FieldIdx,
242    rustc_abi::VariantIdx,
243    rustc_ast::InlineAsmOptions,
244    rustc_ast::InlineAsmTemplatePiece,
245    rustc_hir::CoroutineKind,
246    rustc_hir::HirId,
247    rustc_hir::MatchSource,
248    rustc_hir::RangeEnd,
249    rustc_hir::def_id::LocalDefId,
250    rustc_span::Ident,
251    rustc_span::Span,
252    rustc_span::Symbol,
253    rustc_target::asm::InlineAsmRegOrRegClass,
254    // tidy-alphabetical-end
255}
256
257// For some things about which the type library does not know, or does not
258// provide any traversal implementations, we need to provide a traversal
259// implementation and a lift implementation (the former only for TyCtxt<'_>
260// interners).
261impl<'tcx> crate::ty::Lift<crate::ty::TyCtxt<'tcx>> for
    rustc_hir::def_id::DefId {
    type Lifted = Self;
    fn lift_to_interner(self, _: crate::ty::TyCtxt<'tcx>) -> Option<Self> {
        Some(self)
    }
}TrivialTypeTraversalAndLiftImpls! {
262    // tidy-alphabetical-start
263    crate::mir::RuntimeChecks,
264    crate::ty::ParamTy,
265    crate::ty::instance::ReifyReason,
266    rustc_hir::def_id::DefId,
267    // tidy-alphabetical-end
268}
269
270///////////////////////////////////////////////////////////////////////////
271// Lift implementations
272
273impl<'tcx> Lift<TyCtxt<'tcx>> for PhantomData<&()> {
274    type Lifted = PhantomData<&'tcx ()>;
275    fn lift_to_interner(self, _: TyCtxt<'tcx>) -> Option<Self::Lifted> {
276        Some(PhantomData)
277    }
278}
279
280impl<'tcx, T: Lift<TyCtxt<'tcx>>> Lift<TyCtxt<'tcx>> for Option<T> {
281    type Lifted = Option<T::Lifted>;
282    fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
283        Some(match self {
284            Some(x) => Some(tcx.lift(x)?),
285            None => None,
286        })
287    }
288}
289
290impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for Term<'a> {
291    type Lifted = ty::Term<'tcx>;
292    fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
293        match self.kind() {
294            TermKind::Ty(ty) => tcx.lift(ty).map(Into::into),
295            TermKind::Const(c) => tcx.lift(c).map(Into::into),
296        }
297    }
298}
299
300///////////////////////////////////////////////////////////////////////////
301// Traversal implementations.
302
303impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::AdtDef<'tcx> {
304    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, _visitor: &mut V) -> V::Result {
305        V::Result::output()
306    }
307}
308
309impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Pattern<'tcx> {
310    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
311        self,
312        folder: &mut F,
313    ) -> Result<Self, F::Error> {
314        let pat = (*self).clone().try_fold_with(folder)?;
315        Ok(if pat == *self { self } else { folder.cx().mk_pat(pat) })
316    }
317
318    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
319        let pat = (*self).clone().fold_with(folder);
320        if pat == *self { self } else { folder.cx().mk_pat(pat) }
321    }
322}
323
324impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Pattern<'tcx> {
325    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
326        (**self).visit_with(visitor)
327    }
328}
329
330impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Ty<'tcx> {
331    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
332        self,
333        folder: &mut F,
334    ) -> Result<Self, F::Error> {
335        folder.try_fold_ty(self)
336    }
337
338    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
339        folder.fold_ty(self)
340    }
341}
342
343impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Ty<'tcx> {
344    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
345        visitor.visit_ty(*self)
346    }
347}
348
349impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for Ty<'tcx> {
350    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
351        self,
352        folder: &mut F,
353    ) -> Result<Self, F::Error> {
354        let kind = match *self.kind() {
355            ty::RawPtr(ty, mutbl) => ty::RawPtr(ty.try_fold_with(folder)?, mutbl),
356            ty::Array(typ, sz) => ty::Array(typ.try_fold_with(folder)?, sz.try_fold_with(folder)?),
357            ty::Slice(typ) => ty::Slice(typ.try_fold_with(folder)?),
358            ty::Adt(tid, args) => ty::Adt(tid, args.try_fold_with(folder)?),
359            ty::Dynamic(trait_ty, region) => {
360                ty::Dynamic(trait_ty.try_fold_with(folder)?, region.try_fold_with(folder)?)
361            }
362            ty::Tuple(ts) => ty::Tuple(ts.try_fold_with(folder)?),
363            ty::FnDef(def_id, args) => ty::FnDef(def_id, args.try_fold_with(folder)?),
364            ty::FnPtr(sig_tys, hdr) => ty::FnPtr(sig_tys.try_fold_with(folder)?, hdr),
365            ty::UnsafeBinder(f) => ty::UnsafeBinder(f.try_fold_with(folder)?),
366            ty::Ref(r, ty, mutbl) => {
367                ty::Ref(r.try_fold_with(folder)?, ty.try_fold_with(folder)?, mutbl)
368            }
369            ty::Coroutine(did, args) => ty::Coroutine(did, args.try_fold_with(folder)?),
370            ty::CoroutineWitness(did, args) => {
371                ty::CoroutineWitness(did, args.try_fold_with(folder)?)
372            }
373            ty::Closure(did, args) => ty::Closure(did, args.try_fold_with(folder)?),
374            ty::CoroutineClosure(did, args) => {
375                ty::CoroutineClosure(did, args.try_fold_with(folder)?)
376            }
377            ty::Alias(kind, data) => ty::Alias(kind, data.try_fold_with(folder)?),
378            ty::Pat(ty, pat) => ty::Pat(ty.try_fold_with(folder)?, pat.try_fold_with(folder)?),
379
380            ty::Bool
381            | ty::Char
382            | ty::Str
383            | ty::Int(_)
384            | ty::Uint(_)
385            | ty::Float(_)
386            | ty::Error(_)
387            | ty::Infer(_)
388            | ty::Param(..)
389            | ty::Bound(..)
390            | ty::Placeholder(..)
391            | ty::Never
392            | ty::Foreign(..) => return Ok(self),
393        };
394
395        Ok(if *self.kind() == kind { self } else { folder.cx().mk_ty_from_kind(kind) })
396    }
397
398    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
399        let kind = match *self.kind() {
400            ty::RawPtr(ty, mutbl) => ty::RawPtr(ty.fold_with(folder), mutbl),
401            ty::Array(typ, sz) => ty::Array(typ.fold_with(folder), sz.fold_with(folder)),
402            ty::Slice(typ) => ty::Slice(typ.fold_with(folder)),
403            ty::Adt(tid, args) => ty::Adt(tid, args.fold_with(folder)),
404            ty::Dynamic(trait_ty, region) => {
405                ty::Dynamic(trait_ty.fold_with(folder), region.fold_with(folder))
406            }
407            ty::Tuple(ts) => ty::Tuple(ts.fold_with(folder)),
408            ty::FnDef(def_id, args) => ty::FnDef(def_id, args.fold_with(folder)),
409            ty::FnPtr(sig_tys, hdr) => ty::FnPtr(sig_tys.fold_with(folder), hdr),
410            ty::UnsafeBinder(f) => ty::UnsafeBinder(f.fold_with(folder)),
411            ty::Ref(r, ty, mutbl) => ty::Ref(r.fold_with(folder), ty.fold_with(folder), mutbl),
412            ty::Coroutine(did, args) => ty::Coroutine(did, args.fold_with(folder)),
413            ty::CoroutineWitness(did, args) => ty::CoroutineWitness(did, args.fold_with(folder)),
414            ty::Closure(did, args) => ty::Closure(did, args.fold_with(folder)),
415            ty::CoroutineClosure(did, args) => ty::CoroutineClosure(did, args.fold_with(folder)),
416            ty::Alias(kind, data) => ty::Alias(kind, data.fold_with(folder)),
417            ty::Pat(ty, pat) => ty::Pat(ty.fold_with(folder), pat.fold_with(folder)),
418
419            ty::Bool
420            | ty::Char
421            | ty::Str
422            | ty::Int(_)
423            | ty::Uint(_)
424            | ty::Float(_)
425            | ty::Error(_)
426            | ty::Infer(_)
427            | ty::Param(..)
428            | ty::Bound(..)
429            | ty::Placeholder(..)
430            | ty::Never
431            | ty::Foreign(..) => return self,
432        };
433
434        if *self.kind() == kind { self } else { folder.cx().mk_ty_from_kind(kind) }
435    }
436}
437
438impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for Ty<'tcx> {
439    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
440        match self.kind() {
441            ty::RawPtr(ty, _mutbl) => ty.visit_with(visitor),
442            ty::Array(typ, sz) => {
443                match ::rustc_ast_ir::visit::VisitorResult::branch(typ.visit_with(visitor)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(typ.visit_with(visitor));
444                sz.visit_with(visitor)
445            }
446            ty::Slice(typ) => typ.visit_with(visitor),
447            ty::Adt(_, args) => args.visit_with(visitor),
448            ty::Dynamic(trait_ty, reg) => {
449                match ::rustc_ast_ir::visit::VisitorResult::branch(trait_ty.visit_with(visitor))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(trait_ty.visit_with(visitor));
450                reg.visit_with(visitor)
451            }
452            ty::Tuple(ts) => ts.visit_with(visitor),
453            ty::FnDef(_, args) => args.visit_with(visitor),
454            ty::FnPtr(sig_tys, _) => sig_tys.visit_with(visitor),
455            ty::UnsafeBinder(f) => f.visit_with(visitor),
456            ty::Ref(r, ty, _) => {
457                match ::rustc_ast_ir::visit::VisitorResult::branch(r.visit_with(visitor)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(r.visit_with(visitor));
458                ty.visit_with(visitor)
459            }
460            ty::Coroutine(_did, args) => args.visit_with(visitor),
461            ty::CoroutineWitness(_did, args) => args.visit_with(visitor),
462            ty::Closure(_did, args) => args.visit_with(visitor),
463            ty::CoroutineClosure(_did, args) => args.visit_with(visitor),
464            ty::Alias(_, data) => data.visit_with(visitor),
465
466            ty::Pat(ty, pat) => {
467                match ::rustc_ast_ir::visit::VisitorResult::branch(ty.visit_with(visitor)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(ty.visit_with(visitor));
468                pat.visit_with(visitor)
469            }
470
471            ty::Error(guar) => guar.visit_with(visitor),
472
473            ty::Bool
474            | ty::Char
475            | ty::Str
476            | ty::Int(_)
477            | ty::Uint(_)
478            | ty::Float(_)
479            | ty::Infer(_)
480            | ty::Bound(..)
481            | ty::Placeholder(..)
482            | ty::Param(..)
483            | ty::Never
484            | ty::Foreign(..) => V::Result::output(),
485        }
486    }
487}
488
489impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Region<'tcx> {
490    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
491        self,
492        folder: &mut F,
493    ) -> Result<Self, F::Error> {
494        folder.try_fold_region(self)
495    }
496
497    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
498        folder.fold_region(self)
499    }
500}
501
502impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Region<'tcx> {
503    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
504        visitor.visit_region(*self)
505    }
506}
507
508impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
509    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
510        self,
511        folder: &mut F,
512    ) -> Result<Self, F::Error> {
513        folder.try_fold_predicate(self)
514    }
515
516    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
517        folder.fold_predicate(self)
518    }
519}
520
521// FIXME(clause): This is wonky
522impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Clause<'tcx> {
523    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
524        self,
525        folder: &mut F,
526    ) -> Result<Self, F::Error> {
527        Ok(folder.try_fold_predicate(self.as_predicate())?.expect_clause())
528    }
529
530    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
531        folder.fold_predicate(self.as_predicate()).expect_clause()
532    }
533}
534
535impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
536    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
537        self,
538        folder: &mut F,
539    ) -> Result<Self, F::Error> {
540        folder.try_fold_clauses(self)
541    }
542
543    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
544        folder.fold_clauses(self)
545    }
546}
547
548impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
549    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
550        visitor.visit_predicate(*self)
551    }
552}
553
554impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Clause<'tcx> {
555    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
556        visitor.visit_predicate(self.as_predicate())
557    }
558}
559
560impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
561    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
562        self,
563        folder: &mut F,
564    ) -> Result<Self, F::Error> {
565        // This method looks different to `Ty::try_super_fold_with` and `Const::super_fold_with`.
566        // Why is that? `PredicateKind` provides little scope for optimized folding, unlike
567        // `TyKind` and `ConstKind` (which have common variants that don't require recursive
568        // `fold_with` calls on their fields). So we just derive the `TypeFoldable` impl for
569        // `PredicateKind` and call it here because the derived code is as fast as hand-written
570        // code would be.
571        let new = self.kind().try_fold_with(folder)?;
572        Ok(folder.cx().reuse_or_mk_predicate(self, new))
573    }
574
575    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
576        // See comment in `Predicate::try_super_fold_with`.
577        let new = self.kind().fold_with(folder);
578        folder.cx().reuse_or_mk_predicate(self, new)
579    }
580}
581
582impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
583    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
584        // See comment in `Predicate::try_super_fold_with`.
585        self.kind().visit_with(visitor)
586    }
587}
588
589impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
590    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
591        visitor.visit_clauses(self)
592    }
593}
594
595impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
596    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
597        self.as_slice().visit_with(visitor)
598    }
599}
600
601impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
602    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
603        self,
604        folder: &mut F,
605    ) -> Result<Self, F::Error> {
606        ty::util::try_fold_list(self, folder, |tcx, v| tcx.mk_clauses(v))
607    }
608
609    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
610        ty::util::fold_list(self, folder, |tcx, v| tcx.mk_clauses(v))
611    }
612}
613
614impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Const<'tcx> {
615    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
616        self,
617        folder: &mut F,
618    ) -> Result<Self, F::Error> {
619        folder.try_fold_const(self)
620    }
621
622    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
623        folder.fold_const(self)
624    }
625}
626
627impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Const<'tcx> {
628    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
629        visitor.visit_const(*self)
630    }
631}
632
633impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for ty::Const<'tcx> {
634    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
635        self,
636        folder: &mut F,
637    ) -> Result<Self, F::Error> {
638        let kind = match self.kind() {
639            ConstKind::Unevaluated(uv) => ConstKind::Unevaluated(uv.try_fold_with(folder)?),
640            ConstKind::Value(v) => ConstKind::Value(v.try_fold_with(folder)?),
641            ConstKind::Expr(e) => ConstKind::Expr(e.try_fold_with(folder)?),
642
643            ConstKind::Param(_)
644            | ConstKind::Infer(_)
645            | ConstKind::Bound(..)
646            | ConstKind::Placeholder(_)
647            | ConstKind::Error(_) => return Ok(self),
648        };
649        if kind != self.kind() { Ok(folder.cx().mk_ct_from_kind(kind)) } else { Ok(self) }
650    }
651
652    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
653        let kind = match self.kind() {
654            ConstKind::Unevaluated(uv) => ConstKind::Unevaluated(uv.fold_with(folder)),
655            ConstKind::Value(v) => ConstKind::Value(v.fold_with(folder)),
656            ConstKind::Expr(e) => ConstKind::Expr(e.fold_with(folder)),
657
658            ConstKind::Param(_)
659            | ConstKind::Infer(_)
660            | ConstKind::Bound(..)
661            | ConstKind::Placeholder(_)
662            | ConstKind::Error(_) => return self,
663        };
664        if kind != self.kind() { folder.cx().mk_ct_from_kind(kind) } else { self }
665    }
666}
667
668impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::Const<'tcx> {
669    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
670        match self.kind() {
671            ConstKind::Unevaluated(uv) => uv.visit_with(visitor),
672            ConstKind::Value(v) => v.visit_with(visitor),
673            ConstKind::Expr(e) => e.visit_with(visitor),
674            ConstKind::Error(e) => e.visit_with(visitor),
675
676            ConstKind::Param(_)
677            | ConstKind::Infer(_)
678            | ConstKind::Bound(..)
679            | ConstKind::Placeholder(_) => V::Result::output(),
680        }
681    }
682}
683
684impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::ValTree<'tcx> {
685    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
686        let inner: &ty::ValTreeKind<TyCtxt<'tcx>> = &*self;
687        inner.visit_with(visitor)
688    }
689}
690
691impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::ValTree<'tcx> {
692    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
693        self,
694        folder: &mut F,
695    ) -> Result<Self, F::Error> {
696        let inner: &ty::ValTreeKind<TyCtxt<'tcx>> = &*self;
697        let new_inner = inner.clone().try_fold_with(folder)?;
698
699        if inner == &new_inner {
700            Ok(self)
701        } else {
702            let valtree = folder.cx().intern_valtree(new_inner);
703            Ok(valtree)
704        }
705    }
706
707    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
708        let inner: &ty::ValTreeKind<TyCtxt<'tcx>> = &*self;
709        let new_inner = inner.clone().fold_with(folder);
710
711        if inner == &new_inner { self } else { folder.cx().intern_valtree(new_inner) }
712    }
713}
714
715impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for rustc_span::ErrorGuaranteed {
716    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
717        visitor.visit_error(*self)
718    }
719}
720
721impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for rustc_span::ErrorGuaranteed {
722    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
723        self,
724        _folder: &mut F,
725    ) -> Result<Self, F::Error> {
726        Ok(self)
727    }
728
729    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, _folder: &mut F) -> Self {
730        self
731    }
732}
733
734impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for TyAndLayout<'tcx, Ty<'tcx>> {
735    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
736        visitor.visit_ty(self.ty)
737    }
738}
739
740impl<'tcx, T: TypeVisitable<TyCtxt<'tcx>> + Debug + Clone> TypeVisitable<TyCtxt<'tcx>>
741    for Spanned<T>
742{
743    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
744        match ::rustc_ast_ir::visit::VisitorResult::branch(self.node.visit_with(visitor))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(self.node.visit_with(visitor));
745        self.span.visit_with(visitor)
746    }
747}
748
749impl<'tcx, T: TypeFoldable<TyCtxt<'tcx>> + Debug + Clone> TypeFoldable<TyCtxt<'tcx>>
750    for Spanned<T>
751{
752    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
753        self,
754        folder: &mut F,
755    ) -> Result<Self, F::Error> {
756        Ok(Spanned {
757            node: self.node.try_fold_with(folder)?,
758            span: self.span.try_fold_with(folder)?,
759        })
760    }
761
762    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
763        Spanned { node: self.node.fold_with(folder), span: self.span.fold_with(folder) }
764    }
765}
766
767impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for &'tcx ty::List<LocalDefId> {
768    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
769        self,
770        _folder: &mut F,
771    ) -> Result<Self, F::Error> {
772        Ok(self)
773    }
774
775    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, _folder: &mut F) -> Self {
776        self
777    }
778}
779
780macro_rules! list_fold {
781    ($($ty:ty : $mk:ident),+ $(,)?) => {
782        $(
783            impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for $ty {
784                fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
785                    self,
786                    folder: &mut F,
787                ) -> Result<Self, F::Error> {
788                    ty::util::try_fold_list(self, folder, |tcx, v| tcx.$mk(v))
789                }
790
791                fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(
792                    self,
793                    folder: &mut F,
794                ) -> Self {
795                    ty::util::fold_list(self, folder, |tcx, v| tcx.$mk(v))
796                }
797            }
798        )*
799    }
800}
801
802impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for
    &'tcx ty::List<ty::ArgOutlivesPredicate<'tcx>> {
    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(self,
        folder: &mut F) -> Result<Self, F::Error> {
        ty::util::try_fold_list(self, folder, |tcx, v| tcx.mk_outlives(v))
    }
    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
        ty::util::fold_list(self, folder, |tcx, v| tcx.mk_outlives(v))
    }
}list_fold! {
803    &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> : mk_poly_existential_predicates,
804    &'tcx ty::List<(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)>: mk_predefined_opaques_in_body,
805    &'tcx ty::List<PlaceElem<'tcx>> : mk_place_elems,
806    &'tcx ty::List<ty::Pattern<'tcx>> : mk_patterns,
807    &'tcx ty::List<ty::ArgOutlivesPredicate<'tcx>> : mk_outlives,
808}