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>) -> Option<Self> {
        Some(self)
    }
}TrivialLiftImpls! {
187    (),
188    bool,
189    usize,
190    u64,
191    // tidy-alphabetical-start
192    crate::mir::Promoted,
193    crate::mir::interpret::AllocId,
194    crate::mir::interpret::Scalar,
195    crate::ty::ParamConst,
196    rustc_abi::ExternAbi,
197    rustc_abi::Size,
198    rustc_hir::Safety,
199    rustc_middle::mir::ConstValue,
200    rustc_type_ir::BoundConstness,
201    rustc_type_ir::FnSigKind,
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, T: Lift<TyCtxt<'tcx>>> Lift<TyCtxt<'tcx>> for Option<T> {
274    type Lifted = Option<T::Lifted>;
275    fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
276        Some(match self {
277            Some(x) => Some(tcx.lift(x)?),
278            None => None,
279        })
280    }
281}
282
283impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for Term<'a> {
284    type Lifted = ty::Term<'tcx>;
285    fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
286        match self.kind() {
287            TermKind::Ty(ty) => tcx.lift(ty).map(Into::into),
288            TermKind::Const(c) => tcx.lift(c).map(Into::into),
289        }
290    }
291}
292
293///////////////////////////////////////////////////////////////////////////
294// Traversal implementations.
295
296impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::AdtDef<'tcx> {
297    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, _visitor: &mut V) -> V::Result {
298        V::Result::output()
299    }
300}
301
302impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Pattern<'tcx> {
303    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
304        self,
305        folder: &mut F,
306    ) -> Result<Self, F::Error> {
307        let pat = (*self).clone().try_fold_with(folder)?;
308        Ok(if pat == *self { self } else { folder.cx().mk_pat(pat) })
309    }
310
311    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
312        let pat = (*self).clone().fold_with(folder);
313        if pat == *self { self } else { folder.cx().mk_pat(pat) }
314    }
315}
316
317impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Pattern<'tcx> {
318    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
319        (**self).visit_with(visitor)
320    }
321}
322
323impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Ty<'tcx> {
324    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
325        self,
326        folder: &mut F,
327    ) -> Result<Self, F::Error> {
328        folder.try_fold_ty(self)
329    }
330
331    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
332        folder.fold_ty(self)
333    }
334}
335
336impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Ty<'tcx> {
337    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
338        visitor.visit_ty(*self)
339    }
340}
341
342impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for Ty<'tcx> {
343    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
344        self,
345        folder: &mut F,
346    ) -> Result<Self, F::Error> {
347        let kind = match *self.kind() {
348            ty::RawPtr(ty, mutbl) => ty::RawPtr(ty.try_fold_with(folder)?, mutbl),
349            ty::Array(typ, sz) => ty::Array(typ.try_fold_with(folder)?, sz.try_fold_with(folder)?),
350            ty::Slice(typ) => ty::Slice(typ.try_fold_with(folder)?),
351            ty::Adt(tid, args) => ty::Adt(tid, args.try_fold_with(folder)?),
352            ty::Dynamic(trait_ty, region) => {
353                ty::Dynamic(trait_ty.try_fold_with(folder)?, region.try_fold_with(folder)?)
354            }
355            ty::Tuple(ts) => ty::Tuple(ts.try_fold_with(folder)?),
356            ty::FnDef(def_id, args) => ty::FnDef(def_id, args.try_fold_with(folder)?),
357            ty::FnPtr(sig_tys, hdr) => ty::FnPtr(sig_tys.try_fold_with(folder)?, hdr),
358            ty::UnsafeBinder(f) => ty::UnsafeBinder(f.try_fold_with(folder)?),
359            ty::Ref(r, ty, mutbl) => {
360                ty::Ref(r.try_fold_with(folder)?, ty.try_fold_with(folder)?, mutbl)
361            }
362            ty::Coroutine(did, args) => ty::Coroutine(did, args.try_fold_with(folder)?),
363            ty::CoroutineWitness(did, args) => {
364                ty::CoroutineWitness(did, args.try_fold_with(folder)?)
365            }
366            ty::Closure(did, args) => ty::Closure(did, args.try_fold_with(folder)?),
367            ty::CoroutineClosure(did, args) => {
368                ty::CoroutineClosure(did, args.try_fold_with(folder)?)
369            }
370            ty::Alias(data) => ty::Alias(data.try_fold_with(folder)?),
371            ty::Pat(ty, pat) => ty::Pat(ty.try_fold_with(folder)?, pat.try_fold_with(folder)?),
372
373            ty::Bool
374            | ty::Char
375            | ty::Str
376            | ty::Int(_)
377            | ty::Uint(_)
378            | ty::Float(_)
379            | ty::Error(_)
380            | ty::Infer(_)
381            | ty::Param(..)
382            | ty::Bound(..)
383            | ty::Placeholder(..)
384            | ty::Never
385            | ty::Foreign(..) => return Ok(self),
386        };
387
388        Ok(if *self.kind() == kind { self } else { folder.cx().mk_ty_from_kind(kind) })
389    }
390
391    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
392        let kind = match *self.kind() {
393            ty::RawPtr(ty, mutbl) => ty::RawPtr(ty.fold_with(folder), mutbl),
394            ty::Array(typ, sz) => ty::Array(typ.fold_with(folder), sz.fold_with(folder)),
395            ty::Slice(typ) => ty::Slice(typ.fold_with(folder)),
396            ty::Adt(tid, args) => ty::Adt(tid, args.fold_with(folder)),
397            ty::Dynamic(trait_ty, region) => {
398                ty::Dynamic(trait_ty.fold_with(folder), region.fold_with(folder))
399            }
400            ty::Tuple(ts) => ty::Tuple(ts.fold_with(folder)),
401            ty::FnDef(def_id, args) => ty::FnDef(def_id, args.fold_with(folder)),
402            ty::FnPtr(sig_tys, hdr) => ty::FnPtr(sig_tys.fold_with(folder), hdr),
403            ty::UnsafeBinder(f) => ty::UnsafeBinder(f.fold_with(folder)),
404            ty::Ref(r, ty, mutbl) => ty::Ref(r.fold_with(folder), ty.fold_with(folder), mutbl),
405            ty::Coroutine(did, args) => ty::Coroutine(did, args.fold_with(folder)),
406            ty::CoroutineWitness(did, args) => ty::CoroutineWitness(did, args.fold_with(folder)),
407            ty::Closure(did, args) => ty::Closure(did, args.fold_with(folder)),
408            ty::CoroutineClosure(did, args) => ty::CoroutineClosure(did, args.fold_with(folder)),
409            ty::Alias(data) => ty::Alias(data.fold_with(folder)),
410            ty::Pat(ty, pat) => ty::Pat(ty.fold_with(folder), pat.fold_with(folder)),
411
412            ty::Bool
413            | ty::Char
414            | ty::Str
415            | ty::Int(_)
416            | ty::Uint(_)
417            | ty::Float(_)
418            | ty::Error(_)
419            | ty::Infer(_)
420            | ty::Param(..)
421            | ty::Bound(..)
422            | ty::Placeholder(..)
423            | ty::Never
424            | ty::Foreign(..) => return self,
425        };
426
427        if *self.kind() == kind { self } else { folder.cx().mk_ty_from_kind(kind) }
428    }
429}
430
431impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for Ty<'tcx> {
432    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
433        match self.kind() {
434            ty::RawPtr(ty, _mutbl) => ty.visit_with(visitor),
435            ty::Array(typ, sz) => {
436                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));
437                sz.visit_with(visitor)
438            }
439            ty::Slice(typ) => typ.visit_with(visitor),
440            ty::Adt(_, args) => args.visit_with(visitor),
441            ty::Dynamic(trait_ty, reg) => {
442                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));
443                reg.visit_with(visitor)
444            }
445            ty::Tuple(ts) => ts.visit_with(visitor),
446            ty::FnDef(_, args) => args.visit_with(visitor),
447            ty::FnPtr(sig_tys, _) => sig_tys.visit_with(visitor),
448            ty::UnsafeBinder(f) => f.visit_with(visitor),
449            ty::Ref(r, ty, _) => {
450                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));
451                ty.visit_with(visitor)
452            }
453            ty::Coroutine(_did, args) => args.visit_with(visitor),
454            ty::CoroutineWitness(_did, args) => args.visit_with(visitor),
455            ty::Closure(_did, args) => args.visit_with(visitor),
456            ty::CoroutineClosure(_did, args) => args.visit_with(visitor),
457            ty::Alias(data) => data.visit_with(visitor),
458
459            ty::Pat(ty, pat) => {
460                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));
461                pat.visit_with(visitor)
462            }
463
464            ty::Error(guar) => guar.visit_with(visitor),
465
466            ty::Bool
467            | ty::Char
468            | ty::Str
469            | ty::Int(_)
470            | ty::Uint(_)
471            | ty::Float(_)
472            | ty::Infer(_)
473            | ty::Bound(..)
474            | ty::Placeholder(..)
475            | ty::Param(..)
476            | ty::Never
477            | ty::Foreign(..) => V::Result::output(),
478        }
479    }
480}
481
482impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Region<'tcx> {
483    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
484        self,
485        folder: &mut F,
486    ) -> Result<Self, F::Error> {
487        folder.try_fold_region(self)
488    }
489
490    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
491        folder.fold_region(self)
492    }
493}
494
495impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Region<'tcx> {
496    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
497        visitor.visit_region(*self)
498    }
499}
500
501impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
502    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
503        self,
504        folder: &mut F,
505    ) -> Result<Self, F::Error> {
506        folder.try_fold_predicate(self)
507    }
508
509    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
510        folder.fold_predicate(self)
511    }
512}
513
514// FIXME(clause): This is wonky
515impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Clause<'tcx> {
516    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
517        self,
518        folder: &mut F,
519    ) -> Result<Self, F::Error> {
520        Ok(folder.try_fold_predicate(self.as_predicate())?.expect_clause())
521    }
522
523    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
524        folder.fold_predicate(self.as_predicate()).expect_clause()
525    }
526}
527
528impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
529    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
530        self,
531        folder: &mut F,
532    ) -> Result<Self, F::Error> {
533        folder.try_fold_clauses(self)
534    }
535
536    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
537        folder.fold_clauses(self)
538    }
539}
540
541impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
542    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
543        visitor.visit_predicate(*self)
544    }
545}
546
547impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Clause<'tcx> {
548    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
549        visitor.visit_predicate(self.as_predicate())
550    }
551}
552
553impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
554    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
555        self,
556        folder: &mut F,
557    ) -> Result<Self, F::Error> {
558        // This method looks different to `Ty::try_super_fold_with` and `Const::super_fold_with`.
559        // Why is that? `PredicateKind` provides little scope for optimized folding, unlike
560        // `TyKind` and `ConstKind` (which have common variants that don't require recursive
561        // `fold_with` calls on their fields). So we just derive the `TypeFoldable` impl for
562        // `PredicateKind` and call it here because the derived code is as fast as hand-written
563        // code would be.
564        let new = self.kind().try_fold_with(folder)?;
565        Ok(folder.cx().reuse_or_mk_predicate(self, new))
566    }
567
568    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
569        // See comment in `Predicate::try_super_fold_with`.
570        let new = self.kind().fold_with(folder);
571        folder.cx().reuse_or_mk_predicate(self, new)
572    }
573}
574
575impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
576    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
577        // See comment in `Predicate::try_super_fold_with`.
578        self.kind().visit_with(visitor)
579    }
580}
581
582impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
583    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
584        visitor.visit_clauses(self)
585    }
586}
587
588impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
589    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
590        self.as_slice().visit_with(visitor)
591    }
592}
593
594impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
595    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
596        self,
597        folder: &mut F,
598    ) -> Result<Self, F::Error> {
599        ty::util::try_fold_list(self, folder, |tcx, v| tcx.mk_clauses(v))
600    }
601
602    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
603        ty::util::fold_list(self, folder, |tcx, v| tcx.mk_clauses(v))
604    }
605}
606
607impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Const<'tcx> {
608    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
609        self,
610        folder: &mut F,
611    ) -> Result<Self, F::Error> {
612        folder.try_fold_const(self)
613    }
614
615    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
616        folder.fold_const(self)
617    }
618}
619
620impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Const<'tcx> {
621    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
622        visitor.visit_const(*self)
623    }
624}
625
626impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for ty::Const<'tcx> {
627    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
628        self,
629        folder: &mut F,
630    ) -> Result<Self, F::Error> {
631        let kind = match self.kind() {
632            ConstKind::Unevaluated(uv) => ConstKind::Unevaluated(uv.try_fold_with(folder)?),
633            ConstKind::Value(v) => ConstKind::Value(v.try_fold_with(folder)?),
634            ConstKind::Expr(e) => ConstKind::Expr(e.try_fold_with(folder)?),
635
636            ConstKind::Param(_)
637            | ConstKind::Infer(_)
638            | ConstKind::Bound(..)
639            | ConstKind::Placeholder(_)
640            | ConstKind::Error(_) => return Ok(self),
641        };
642        if kind != self.kind() { Ok(folder.cx().mk_ct_from_kind(kind)) } else { Ok(self) }
643    }
644
645    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
646        let kind = match self.kind() {
647            ConstKind::Unevaluated(uv) => ConstKind::Unevaluated(uv.fold_with(folder)),
648            ConstKind::Value(v) => ConstKind::Value(v.fold_with(folder)),
649            ConstKind::Expr(e) => ConstKind::Expr(e.fold_with(folder)),
650
651            ConstKind::Param(_)
652            | ConstKind::Infer(_)
653            | ConstKind::Bound(..)
654            | ConstKind::Placeholder(_)
655            | ConstKind::Error(_) => return self,
656        };
657        if kind != self.kind() { folder.cx().mk_ct_from_kind(kind) } else { self }
658    }
659}
660
661impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::Const<'tcx> {
662    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
663        match self.kind() {
664            ConstKind::Unevaluated(uv) => uv.visit_with(visitor),
665            ConstKind::Value(v) => v.visit_with(visitor),
666            ConstKind::Expr(e) => e.visit_with(visitor),
667            ConstKind::Error(e) => e.visit_with(visitor),
668
669            ConstKind::Param(_)
670            | ConstKind::Infer(_)
671            | ConstKind::Bound(..)
672            | ConstKind::Placeholder(_) => V::Result::output(),
673        }
674    }
675}
676
677impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::ValTree<'tcx> {
678    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
679        let inner: &ty::ValTreeKind<TyCtxt<'tcx>> = &*self;
680        inner.visit_with(visitor)
681    }
682}
683
684impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::ValTree<'tcx> {
685    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
686        self,
687        folder: &mut F,
688    ) -> Result<Self, F::Error> {
689        let inner: &ty::ValTreeKind<TyCtxt<'tcx>> = &*self;
690        let new_inner = inner.clone().try_fold_with(folder)?;
691
692        if inner == &new_inner {
693            Ok(self)
694        } else {
695            let valtree = folder.cx().intern_valtree(new_inner);
696            Ok(valtree)
697        }
698    }
699
700    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
701        let inner: &ty::ValTreeKind<TyCtxt<'tcx>> = &*self;
702        let new_inner = inner.clone().fold_with(folder);
703
704        if inner == &new_inner { self } else { folder.cx().intern_valtree(new_inner) }
705    }
706}
707
708impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for rustc_span::ErrorGuaranteed {
709    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
710        visitor.visit_error(*self)
711    }
712}
713
714impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for rustc_span::ErrorGuaranteed {
715    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
716        self,
717        _folder: &mut F,
718    ) -> Result<Self, F::Error> {
719        Ok(self)
720    }
721
722    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, _folder: &mut F) -> Self {
723        self
724    }
725}
726
727impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for TyAndLayout<'tcx, Ty<'tcx>> {
728    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
729        visitor.visit_ty(self.ty)
730    }
731}
732
733impl<'tcx, T: TypeVisitable<TyCtxt<'tcx>> + Debug + Clone> TypeVisitable<TyCtxt<'tcx>>
734    for Spanned<T>
735{
736    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
737        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));
738        self.span.visit_with(visitor)
739    }
740}
741
742impl<'tcx, T: TypeFoldable<TyCtxt<'tcx>> + Debug + Clone> TypeFoldable<TyCtxt<'tcx>>
743    for Spanned<T>
744{
745    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
746        self,
747        folder: &mut F,
748    ) -> Result<Self, F::Error> {
749        Ok(Spanned {
750            node: self.node.try_fold_with(folder)?,
751            span: self.span.try_fold_with(folder)?,
752        })
753    }
754
755    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
756        Spanned { node: self.node.fold_with(folder), span: self.span.fold_with(folder) }
757    }
758}
759
760impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for &'tcx ty::List<LocalDefId> {
761    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
762        self,
763        _folder: &mut F,
764    ) -> Result<Self, F::Error> {
765        Ok(self)
766    }
767
768    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, _folder: &mut F) -> Self {
769        self
770    }
771}
772
773macro_rules! list_fold {
774    ($($ty:ty : $mk:ident),+ $(,)?) => {
775        $(
776            impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for $ty {
777                fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
778                    self,
779                    folder: &mut F,
780                ) -> Result<Self, F::Error> {
781                    ty::util::try_fold_list(self, folder, |tcx, v| tcx.$mk(v))
782                }
783
784                fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(
785                    self,
786                    folder: &mut F,
787                ) -> Self {
788                    ty::util::fold_list(self, folder, |tcx, v| tcx.$mk(v))
789                }
790            }
791        )*
792    }
793}
794
795impl<'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! {
796    &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> : mk_poly_existential_predicates,
797    &'tcx ty::List<(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)>: mk_predefined_opaques_in_body,
798    &'tcx ty::List<PlaceElem<'tcx>> : mk_place_elems,
799    &'tcx ty::List<ty::Pattern<'tcx>> : mk_patterns,
800    &'tcx ty::List<ty::ArgOutlivesPredicate<'tcx>> : mk_outlives,
801    &'tcx ty::List<ty::Const<'tcx>> : mk_const_list,
802}