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.unpack() {
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.unpack() {
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> TypeVisitable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
574    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
575        visitor.visit_predicate(*self)
576    }
577}
578
579impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Clause<'tcx> {
580    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
581        visitor.visit_predicate(self.as_predicate())
582    }
583}
584
585impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
586    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
587        self,
588        folder: &mut F,
589    ) -> Result<Self, F::Error> {
590        let new = self.kind().try_fold_with(folder)?;
591        Ok(folder.cx().reuse_or_mk_predicate(self, new))
592    }
593
594    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
595        let new = self.kind().fold_with(folder);
596        folder.cx().reuse_or_mk_predicate(self, new)
597    }
598}
599
600impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
601    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
602        self.kind().visit_with(visitor)
603    }
604}
605
606impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
607    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
608        visitor.visit_clauses(self)
609    }
610}
611
612impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::Clauses<'tcx> {
613    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
614        self.as_slice().visit_with(visitor)
615    }
616}
617
618impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ty::Const<'tcx> {
619    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
620        self,
621        folder: &mut F,
622    ) -> Result<Self, F::Error> {
623        folder.try_fold_const(self)
624    }
625
626    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
627        folder.fold_const(self)
628    }
629}
630
631impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for ty::Const<'tcx> {
632    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
633        visitor.visit_const(*self)
634    }
635}
636
637impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for ty::Const<'tcx> {
638    fn try_super_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
639        self,
640        folder: &mut F,
641    ) -> Result<Self, F::Error> {
642        let kind = match self.kind() {
643            ConstKind::Param(p) => ConstKind::Param(p.try_fold_with(folder)?),
644            ConstKind::Infer(i) => ConstKind::Infer(i.try_fold_with(folder)?),
645            ConstKind::Bound(d, b) => {
646                ConstKind::Bound(d.try_fold_with(folder)?, b.try_fold_with(folder)?)
647            }
648            ConstKind::Placeholder(p) => ConstKind::Placeholder(p.try_fold_with(folder)?),
649            ConstKind::Unevaluated(uv) => ConstKind::Unevaluated(uv.try_fold_with(folder)?),
650            ConstKind::Value(v) => ConstKind::Value(v.try_fold_with(folder)?),
651            ConstKind::Error(e) => ConstKind::Error(e.try_fold_with(folder)?),
652            ConstKind::Expr(e) => ConstKind::Expr(e.try_fold_with(folder)?),
653        };
654        if kind != self.kind() { Ok(folder.cx().mk_ct_from_kind(kind)) } else { Ok(self) }
655    }
656
657    fn super_fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
658        let kind = match self.kind() {
659            ConstKind::Param(p) => ConstKind::Param(p.fold_with(folder)),
660            ConstKind::Infer(i) => ConstKind::Infer(i.fold_with(folder)),
661            ConstKind::Bound(d, b) => ConstKind::Bound(d.fold_with(folder), b.fold_with(folder)),
662            ConstKind::Placeholder(p) => ConstKind::Placeholder(p.fold_with(folder)),
663            ConstKind::Unevaluated(uv) => ConstKind::Unevaluated(uv.fold_with(folder)),
664            ConstKind::Value(v) => ConstKind::Value(v.fold_with(folder)),
665            ConstKind::Error(e) => ConstKind::Error(e.fold_with(folder)),
666            ConstKind::Expr(e) => ConstKind::Expr(e.fold_with(folder)),
667        };
668        if kind != self.kind() { folder.cx().mk_ct_from_kind(kind) } else { self }
669    }
670}
671
672impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::Const<'tcx> {
673    fn super_visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
674        match self.kind() {
675            ConstKind::Param(p) => p.visit_with(visitor),
676            ConstKind::Infer(i) => i.visit_with(visitor),
677            ConstKind::Bound(d, b) => {
678                try_visit!(d.visit_with(visitor));
679                b.visit_with(visitor)
680            }
681            ConstKind::Placeholder(p) => p.visit_with(visitor),
682            ConstKind::Unevaluated(uv) => uv.visit_with(visitor),
683            ConstKind::Value(v) => v.visit_with(visitor),
684            ConstKind::Error(e) => e.visit_with(visitor),
685            ConstKind::Expr(e) => e.visit_with(visitor),
686        }
687    }
688}
689
690impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for rustc_span::ErrorGuaranteed {
691    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
692        visitor.visit_error(*self)
693    }
694}
695
696impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for rustc_span::ErrorGuaranteed {
697    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
698        self,
699        _folder: &mut F,
700    ) -> Result<Self, F::Error> {
701        Ok(self)
702    }
703
704    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, _folder: &mut F) -> Self {
705        self
706    }
707}
708
709impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for TyAndLayout<'tcx, Ty<'tcx>> {
710    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
711        visitor.visit_ty(self.ty)
712    }
713}
714
715impl<'tcx, T: TypeVisitable<TyCtxt<'tcx>> + Debug + Clone> TypeVisitable<TyCtxt<'tcx>>
716    for Spanned<T>
717{
718    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
719        try_visit!(self.node.visit_with(visitor));
720        self.span.visit_with(visitor)
721    }
722}
723
724impl<'tcx, T: TypeFoldable<TyCtxt<'tcx>> + Debug + Clone> TypeFoldable<TyCtxt<'tcx>>
725    for Spanned<T>
726{
727    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
728        self,
729        folder: &mut F,
730    ) -> Result<Self, F::Error> {
731        Ok(Spanned {
732            node: self.node.try_fold_with(folder)?,
733            span: self.span.try_fold_with(folder)?,
734        })
735    }
736
737    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
738        Spanned { node: self.node.fold_with(folder), span: self.span.fold_with(folder) }
739    }
740}
741
742impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for &'tcx ty::List<LocalDefId> {
743    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
744        self,
745        _folder: &mut F,
746    ) -> Result<Self, F::Error> {
747        Ok(self)
748    }
749
750    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, _folder: &mut F) -> Self {
751        self
752    }
753}
754
755macro_rules! list_fold {
756    ($($ty:ty : $mk:ident),+ $(,)?) => {
757        $(
758            impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for $ty {
759                fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
760                    self,
761                    folder: &mut F,
762                ) -> Result<Self, F::Error> {
763                    ty::util::try_fold_list(self, folder, |tcx, v| tcx.$mk(v))
764                }
765
766                fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(
767                    self,
768                    folder: &mut F,
769                ) -> Self {
770                    ty::util::fold_list(self, folder, |tcx, v| tcx.$mk(v))
771                }
772            }
773        )*
774    }
775}
776
777list_fold! {
778    ty::Clauses<'tcx> : mk_clauses,
779    &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> : mk_poly_existential_predicates,
780    &'tcx ty::List<PlaceElem<'tcx>> : mk_place_elems,
781    &'tcx ty::List<ty::Pattern<'tcx>> : mk_patterns,
782}
OSZAR »