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};
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
172///////////////////////////////////////////////////////////////////////////
173// Atomic structs
174//
175// For things that don't carry any arena-allocated data (and are
176// copy...), just add them to one of these lists as appropriate.
177
178// For things for which the type library provides traversal implementations
179// for all Interners, we only need to provide a Lift implementation.
180impl<'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! {
181    bool,
182    usize,
183    u64,
184    // tidy-alphabetical-start
185    crate::mir::Promoted,
186    crate::mir::interpret::AllocId,
187    crate::mir::interpret::Scalar,
188    crate::ty::ParamConst,
189    rustc_abi::ExternAbi,
190    rustc_abi::Size,
191    rustc_hir::Safety,
192    rustc_middle::mir::ConstValue,
193    rustc_span::Symbol,
194    rustc_type_ir::BoundConstness,
195    rustc_type_ir::PredicatePolarity,
196    // tidy-alphabetical-end
197}
198
199// For some things about which the type library does not know, or does not
200// provide any traversal implementations, we need to provide a traversal
201// implementation (only for TyCtxt<'_> interners).
202impl<'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! {
203    // tidy-alphabetical-start
204    crate::infer::canonical::Certainty,
205    crate::mir::BasicBlock,
206    crate::mir::BindingForm<'tcx>,
207    crate::mir::BlockTailInfo,
208    crate::mir::BorrowKind,
209    crate::mir::CastKind,
210    crate::mir::ConstValue,
211    crate::mir::CoroutineSavedLocal,
212    crate::mir::FakeReadCause,
213    crate::mir::Local,
214    crate::mir::MirPhase,
215    crate::mir::Promoted,
216    crate::mir::RawPtrKind,
217    crate::mir::SourceInfo,
218    crate::mir::SourceScope,
219    crate::mir::SourceScopeLocalData,
220    crate::mir::SwitchTargets,
221    crate::mir::WithRetag,
222    crate::traits::IsConstable,
223    crate::traits::OverflowError,
224    crate::ty::AdtKind,
225    crate::ty::AssocItem,
226    crate::ty::AssocKind,
227    crate::ty::BoundRegion<'tcx>,
228    crate::ty::BoundTy<'tcx>,
229    crate::ty::ScalarInt,
230    crate::ty::UserTypeAnnotationIndex,
231    crate::ty::abstract_const::NotConstEvaluatable,
232    crate::ty::adjustment::AutoBorrowMutability,
233    crate::ty::adjustment::PointerCoercion,
234    rustc_abi::FieldIdx,
235    rustc_abi::VariantIdx,
236    rustc_ast::InlineAsmOptions,
237    rustc_ast::InlineAsmTemplatePiece,
238    rustc_hir::CoroutineKind,
239    rustc_hir::HirId,
240    rustc_hir::MatchSource,
241    rustc_hir::RangeEnd,
242    rustc_hir::attrs::AttributeKind,
243    rustc_hir::def_id::LocalDefId,
244    rustc_span::Ident,
245    rustc_span::Span,
246    rustc_span::Symbol,
247    rustc_span::def_id::ModId,
248    rustc_target::asm::InlineAsmRegOrRegClass,
249    // tidy-alphabetical-end
250}
251
252// For some things about which the type library does not know, or does not
253// provide any traversal implementations, we need to provide a traversal
254// implementation and a lift implementation (the former only for TyCtxt<'_>
255// interners).
256impl<'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! {
257    // tidy-alphabetical-start
258    crate::mir::RuntimeChecks,
259    crate::ty::ParamTy,
260    crate::ty::instance::ReifyReason,
261    rustc_hir::def_id::DefId,
262    // tidy-alphabetical-end
263}
264
265impl<'tcx> crate::ty::Lift<crate::ty::TyCtxt<'tcx>> for ty::LateParamRegion {
    type Lifted = Self;
    fn lift_to_interner(self, _: crate::ty::TyCtxt<'tcx>) -> Self { self }
}TrivialLiftImpls! {
266    rustc_span::ErrorGuaranteed,
267    ty::EarlyParamRegion,
268    ty::LateParamRegion,
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::Predicate<'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_predicate(self)
494    }
495
496    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
497        folder.fold_predicate(self)
498    }
499}
500
501// FIXME(clause): This is wonky
502impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Clause<'tcx> {
503    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
504        self,
505        folder: &mut F,
506    ) -> Result<Self, F::Error> {
507        Ok(folder.try_fold_predicate(self.as_predicate())?.expect_clause())
508    }
509
510    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
511        folder.fold_predicate(self.as_predicate()).expect_clause()
512    }
513}
514
515impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
516    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
517        self,
518        folder: &mut F,
519    ) -> Result<Self, F::Error> {
520        folder.try_fold_clauses(self)
521    }
522
523    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
524        folder.fold_clauses(self)
525    }
526}
527
528impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
529    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
530        visitor.visit_predicate(*self)
531    }
532}
533
534impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Clause<'tcx> {
535    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
536        visitor.visit_predicate(self.as_predicate())
537    }
538}
539
540impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
541    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
542        self,
543        folder: &mut F,
544    ) -> Result<Self, F::Error> {
545        // This method looks different to `Ty::try_super_fold_with` and `Const::super_fold_with`.
546        // Why is that? `PredicateKind` provides little scope for optimized folding, unlike
547        // `TyKind` and `ConstKind` (which have common variants that don't require recursive
548        // `fold_with` calls on their fields). So we just derive the `TypeFoldable` impl for
549        // `PredicateKind` and call it here because the derived code is as fast as hand-written
550        // code would be.
551        let new = self.kind().try_fold_with(folder)?;
552        Ok(folder.cx().reuse_or_mk_predicate(self, new))
553    }
554
555    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
556        // See comment in `Predicate::try_super_fold_with`.
557        let new = self.kind().fold_with(folder);
558        folder.cx().reuse_or_mk_predicate(self, new)
559    }
560}
561
562impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
563    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
564        // See comment in `Predicate::try_super_fold_with`.
565        self.kind().visit_with(visitor)
566    }
567}
568
569impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
570    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
571        visitor.visit_clauses(self)
572    }
573}
574
575impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
576    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
577        self.as_slice().visit_with(visitor)
578    }
579}
580
581impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
582    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
583        self,
584        folder: &mut F,
585    ) -> Result<Self, F::Error> {
586        ty::util::try_fold_list(self, folder, |tcx, v| tcx.mk_clauses(v))
587    }
588
589    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
590        ty::util::fold_list(self, folder, |tcx, v| tcx.mk_clauses(v))
591    }
592}
593
594impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Const<'tcx> {
595    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
596        self,
597        folder: &mut F,
598    ) -> Result<Self, F::Error> {
599        folder.try_fold_const(self)
600    }
601
602    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
603        folder.fold_const(self)
604    }
605}
606
607impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Const<'tcx> {
608    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
609        visitor.visit_const(*self)
610    }
611}
612
613impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for ty::Const<'tcx> {
614    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
615        self,
616        folder: &mut F,
617    ) -> Result<Self, F::Error> {
618        let kind = match self.kind() {
619            ConstKind::Alias(is_rigid, alias_const) => {
620                ConstKind::Alias(is_rigid, alias_const.try_fold_with(folder)?)
621            }
622            ConstKind::Value(v) => ConstKind::Value(v.try_fold_with(folder)?),
623            ConstKind::Expr(e) => ConstKind::Expr(e.try_fold_with(folder)?),
624
625            ConstKind::Param(_)
626            | ConstKind::Infer(_)
627            | ConstKind::Bound(..)
628            | ConstKind::Placeholder(_)
629            | ConstKind::Error(_) => return Ok(self),
630        };
631        if kind != self.kind() { Ok(folder.cx().mk_ct_from_kind(kind)) } else { Ok(self) }
632    }
633
634    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
635        let kind = match self.kind() {
636            ConstKind::Alias(is_rigid, alias_const) => {
637                ConstKind::Alias(is_rigid, alias_const.fold_with(folder))
638            }
639            ConstKind::Value(v) => ConstKind::Value(v.fold_with(folder)),
640            ConstKind::Expr(e) => ConstKind::Expr(e.fold_with(folder)),
641
642            ConstKind::Param(_)
643            | ConstKind::Infer(_)
644            | ConstKind::Bound(..)
645            | ConstKind::Placeholder(_)
646            | ConstKind::Error(_) => return self,
647        };
648        if kind != self.kind() { folder.cx().mk_ct_from_kind(kind) } else { self }
649    }
650}
651
652impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::Const<'tcx> {
653    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
654        match self.kind() {
655            ConstKind::Alias(_, alias_const) => alias_const.visit_with(visitor),
656            ConstKind::Value(v) => v.visit_with(visitor),
657            ConstKind::Expr(e) => e.visit_with(visitor),
658            ConstKind::Error(e) => e.visit_with(visitor),
659
660            ConstKind::Param(_)
661            | ConstKind::Infer(_)
662            | ConstKind::Bound(..)
663            | ConstKind::Placeholder(_) => V::Result::output(),
664        }
665    }
666}
667
668impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::ValTree<'tcx> {
669    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
670        let inner: &ty::ValTreeKind<TyCtxt<'tcx>> = &*self;
671        inner.visit_with(visitor)
672    }
673}
674
675impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::ValTree<'tcx> {
676    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
677        self,
678        folder: &mut F,
679    ) -> Result<Self, F::Error> {
680        let inner: &ty::ValTreeKind<TyCtxt<'tcx>> = &*self;
681        let new_inner = inner.clone().try_fold_with(folder)?;
682
683        if inner == &new_inner {
684            Ok(self)
685        } else {
686            let valtree = folder.cx().intern_valtree(new_inner);
687            Ok(valtree)
688        }
689    }
690
691    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
692        let inner: &ty::ValTreeKind<TyCtxt<'tcx>> = &*self;
693        let new_inner = inner.clone().fold_with(folder);
694
695        if inner == &new_inner { self } else { folder.cx().intern_valtree(new_inner) }
696    }
697}
698
699impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for rustc_span::ErrorGuaranteed {
700    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
701        visitor.visit_error(*self)
702    }
703}
704
705impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for rustc_span::ErrorGuaranteed {
706    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
707        self,
708        _folder: &mut F,
709    ) -> Result<Self, F::Error> {
710        Ok(self)
711    }
712
713    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, _folder: &mut F) -> Self {
714        self
715    }
716}
717
718impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for TyAndLayout<'tcx, Ty<'tcx>> {
719    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
720        visitor.visit_ty(self.ty)
721    }
722}
723
724impl<'tcx, T: TypeVisitable<TyCtxt<'tcx>> + Debug + Clone> TypeVisitable<TyCtxt<'tcx>>
725    for Spanned<T>
726{
727    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
728        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));
729        self.span.visit_with(visitor)
730    }
731}
732
733impl<'tcx, T: TypeFoldable<TyCtxt<'tcx>> + Debug + Clone> TypeFoldable<TyCtxt<'tcx>>
734    for Spanned<T>
735{
736    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
737        self,
738        folder: &mut F,
739    ) -> Result<Self, F::Error> {
740        Ok(Spanned {
741            node: self.node.try_fold_with(folder)?,
742            span: self.span.try_fold_with(folder)?,
743        })
744    }
745
746    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
747        Spanned { node: self.node.fold_with(folder), span: self.span.fold_with(folder) }
748    }
749}
750
751impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for &'tcx ty::List<LocalDefId> {
752    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
753        self,
754        _folder: &mut F,
755    ) -> Result<Self, F::Error> {
756        Ok(self)
757    }
758
759    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, _folder: &mut F) -> Self {
760        self
761    }
762}
763
764macro_rules! list_fold {
765    ($($ty:ty : $mk:ident),+ $(,)?) => {
766        $(
767            impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for $ty {
768                fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
769                    self,
770                    folder: &mut F,
771                ) -> Result<Self, F::Error> {
772                    ty::util::try_fold_list(self, folder, |tcx, v| tcx.$mk(v))
773                }
774
775                fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(
776                    self,
777                    folder: &mut F,
778                ) -> Self {
779                    ty::util::fold_list(self, folder, |tcx, v| tcx.$mk(v))
780                }
781            }
782        )*
783    }
784}
785
786impl<'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! {
787    &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> : mk_poly_existential_predicates,
788    &'tcx ty::List<(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)>: mk_predefined_opaques_in_body,
789    &'tcx ty::List<PlaceElem<'tcx>> : mk_place_elems,
790    &'tcx ty::List<ty::Pattern<'tcx>> : mk_patterns,
791    &'tcx ty::List<ty::ArgOutlivesPredicate<'tcx>> : mk_outlives,
792    &'tcx ty::List<ty::Const<'tcx>> : mk_const_list,
793}