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