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