Skip to main content

rustc_middle/ty/
structural_impls.rs

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