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