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