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