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