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};
7use std::marker::PhantomData;
8
9use rustc_abi::TyAndLayout;
10use rustc_hir::def::Namespace;
11use rustc_hir::def_id::LocalDefId;
12use rustc_span::source_map::Spanned;
13use rustc_type_ir::{ConstKind, TypeFolder, VisitorResult, try_visit};
14
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, |p| {
28                    p.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, |p| {
41                    p.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            write!(f, "{}", cv)
171        } else {
172            // Fall back to something verbose.
173            write!(f, "{:?}", self.kind())
174        }
175    }
176}
177
178impl fmt::Debug for ty::BoundTy {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        match self.kind {
181            ty::BoundTyKind::Anon => write!(f, "{:?}", self.var),
182            ty::BoundTyKind::Param(def_id) => write!(f, "{def_id:?}"),
183        }
184    }
185}
186
187impl<T: fmt::Debug> fmt::Debug for ty::Placeholder<T> {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        if self.universe == ty::UniverseIndex::ROOT {
190            write!(f, "!{:?}", self.bound)
191        } else {
192            write!(f, "!{}_{:?}", self.universe.index(), self.bound)
193        }
194    }
195}
196
197impl<'tcx> fmt::Debug for GenericArg<'tcx> {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        match self.kind() {
200            GenericArgKind::Lifetime(lt) => lt.fmt(f),
201            GenericArgKind::Type(ty) => ty.fmt(f),
202            GenericArgKind::Const(ct) => ct.fmt(f),
203        }
204    }
205}
206
207impl<'tcx> fmt::Debug for Region<'tcx> {
208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209        write!(f, "{:?}", self.kind())
210    }
211}
212
213///////////////////////////////////////////////////////////////////////////
214// Atomic structs
215//
216// For things that don't carry any arena-allocated data (and are
217// copy...), just add them to one of these lists as appropriate.
218
219// For things for which the type library provides traversal implementations
220// for all Interners, we only need to provide a Lift implementation.
221TrivialLiftImpls! {
222    (),
223    bool,
224    usize,
225    u64,
226    // tidy-alphabetical-start
227    crate::mir::Promoted,
228    crate::mir::interpret::AllocId,
229    crate::mir::interpret::Scalar,
230    crate::ty::ParamConst,
231    rustc_abi::ExternAbi,
232    rustc_abi::Size,
233    rustc_hir::Safety,
234    rustc_middle::mir::ConstValue,
235    rustc_type_ir::BoundConstness,
236    rustc_type_ir::PredicatePolarity,
237    // tidy-alphabetical-end
238}
239
240// For some things about which the type library does not know, or does not
241// provide any traversal implementations, we need to provide a traversal
242// implementation (only for TyCtxt<'_> interners).
243TrivialTypeTraversalImpls! {
244    // tidy-alphabetical-start
245    crate::infer::canonical::Certainty,
246    crate::mir::BasicBlock,
247    crate::mir::BindingForm<'tcx>,
248    crate::mir::BlockTailInfo,
249    crate::mir::BorrowKind,
250    crate::mir::CastKind,
251    crate::mir::ConstValue,
252    crate::mir::CoroutineSavedLocal,
253    crate::mir::FakeReadCause,
254    crate::mir::Local,
255    crate::mir::MirPhase,
256    crate::mir::NullOp<'tcx>,
257    crate::mir::Promoted,
258    crate::mir::RawPtrKind,
259    crate::mir::RetagKind,
260    crate::mir::SourceInfo,
261    crate::mir::SourceScope,
262    crate::mir::SourceScopeLocalData,
263    crate::mir::SwitchTargets,
264    crate::traits::IsConstable,
265    crate::traits::OverflowError,
266    crate::ty::AdtKind,
267    crate::ty::AssocItem,
268    crate::ty::AssocKind,
269    crate::ty::BoundRegion,
270    crate::ty::UserTypeAnnotationIndex,
271    crate::ty::ValTree<'tcx>,
272    crate::ty::abstract_const::NotConstEvaluatable,
273    crate::ty::adjustment::AutoBorrowMutability,
274    crate::ty::adjustment::PointerCoercion,
275    rustc_abi::FieldIdx,
276    rustc_abi::VariantIdx,
277    rustc_ast::InlineAsmOptions,
278    rustc_ast::InlineAsmTemplatePiece,
279    rustc_hir::CoroutineKind,
280    rustc_hir::HirId,
281    rustc_hir::MatchSource,
282    rustc_hir::RangeEnd,
283    rustc_hir::def_id::LocalDefId,
284    rustc_span::Ident,
285    rustc_span::Span,
286    rustc_span::Symbol,
287    rustc_target::asm::InlineAsmRegOrRegClass,
288    // tidy-alphabetical-end
289}
290
291// For some things about which the type library does not know, or does not
292// provide any traversal implementations, we need to provide a traversal
293// implementation and a lift implementation (the former only for TyCtxt<'_>
294// interners).
295TrivialTypeTraversalAndLiftImpls! {
296    // tidy-alphabetical-start
297    crate::ty::ParamTy,
298    crate::ty::PlaceholderType,
299    crate::ty::instance::ReifyReason,
300    rustc_hir::def_id::DefId,
301    // tidy-alphabetical-end
302}
303
304///////////////////////////////////////////////////////////////////////////
305// Lift implementations
306
307impl<'tcx> Lift<TyCtxt<'tcx>> for PhantomData<&()> {
308    type Lifted = PhantomData<&'tcx ()>;
309    fn lift_to_interner(self, _: TyCtxt<'tcx>) -> Option<Self::Lifted> {
310        Some(PhantomData)
311    }
312}
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::Unevaluated(uv) => ConstKind::Unevaluated(uv.try_fold_with(folder)?),
668            ConstKind::Value(v) => ConstKind::Value(v.try_fold_with(folder)?),
669            ConstKind::Expr(e) => ConstKind::Expr(e.try_fold_with(folder)?),
670
671            ConstKind::Param(_)
672            | ConstKind::Infer(_)
673            | ConstKind::Bound(..)
674            | ConstKind::Placeholder(_)
675            | ConstKind::Error(_) => return Ok(self),
676        };
677        if kind != self.kind() { Ok(folder.cx().mk_ct_from_kind(kind)) } else { Ok(self) }
678    }
679
680    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
681        let kind = match self.kind() {
682            ConstKind::Unevaluated(uv) => ConstKind::Unevaluated(uv.fold_with(folder)),
683            ConstKind::Value(v) => ConstKind::Value(v.fold_with(folder)),
684            ConstKind::Expr(e) => ConstKind::Expr(e.fold_with(folder)),
685
686            ConstKind::Param(_)
687            | ConstKind::Infer(_)
688            | ConstKind::Bound(..)
689            | ConstKind::Placeholder(_)
690            | ConstKind::Error(_) => return self,
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::Unevaluated(uv) => uv.visit_with(visitor),
700            ConstKind::Value(v) => v.visit_with(visitor),
701            ConstKind::Expr(e) => e.visit_with(visitor),
702            ConstKind::Error(e) => e.visit_with(visitor),
703
704            ConstKind::Param(_)
705            | ConstKind::Infer(_)
706            | ConstKind::Bound(..)
707            | ConstKind::Placeholder(_) => V::Result::output(),
708        }
709    }
710}
711
712impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for rustc_span::ErrorGuaranteed {
713    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
714        visitor.visit_error(*self)
715    }
716}
717
718impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for rustc_span::ErrorGuaranteed {
719    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
720        self,
721        _folder: &mut F,
722    ) -> Result<Self, F::Error> {
723        Ok(self)
724    }
725
726    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, _folder: &mut F) -> Self {
727        self
728    }
729}
730
731impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for TyAndLayout<'tcx, Ty<'tcx>> {
732    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
733        visitor.visit_ty(self.ty)
734    }
735}
736
737impl<'tcx, T: TypeVisitable<TyCtxt<'tcx>> + Debug + Clone> TypeVisitable<TyCtxt<'tcx>>
738    for Spanned<T>
739{
740    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
741        try_visit!(self.node.visit_with(visitor));
742        self.span.visit_with(visitor)
743    }
744}
745
746impl<'tcx, T: TypeFoldable<TyCtxt<'tcx>> + Debug + Clone> TypeFoldable<TyCtxt<'tcx>>
747    for Spanned<T>
748{
749    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
750        self,
751        folder: &mut F,
752    ) -> Result<Self, F::Error> {
753        Ok(Spanned {
754            node: self.node.try_fold_with(folder)?,
755            span: self.span.try_fold_with(folder)?,
756        })
757    }
758
759    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
760        Spanned { node: self.node.fold_with(folder), span: self.span.fold_with(folder) }
761    }
762}
763
764impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for &'tcx ty::List<LocalDefId> {
765    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
766        self,
767        _folder: &mut F,
768    ) -> Result<Self, F::Error> {
769        Ok(self)
770    }
771
772    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, _folder: &mut F) -> Self {
773        self
774    }
775}
776
777macro_rules! list_fold {
778    ($($ty:ty : $mk:ident),+ $(,)?) => {
779        $(
780            impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for $ty {
781                fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
782                    self,
783                    folder: &mut F,
784                ) -> Result<Self, F::Error> {
785                    ty::util::try_fold_list(self, folder, |tcx, v| tcx.$mk(v))
786                }
787
788                fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(
789                    self,
790                    folder: &mut F,
791                ) -> Self {
792                    ty::util::fold_list(self, folder, |tcx, v| tcx.$mk(v))
793                }
794            }
795        )*
796    }
797}
798
799list_fold! {
800    &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> : mk_poly_existential_predicates,
801    &'tcx ty::List<PlaceElem<'tcx>> : mk_place_elems,
802    &'tcx ty::List<ty::Pattern<'tcx>> : mk_patterns,
803    &'tcx ty::List<ty::ArgOutlivesPredicate<'tcx>> : mk_outlives,
804}