]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/structural_impls.rs
Rollup merge of #83608 - Kimundi:index_many, r=Mark-Simulacrum
[rust.git] / compiler / rustc_middle / src / ty / structural_impls.rs
1 //! This module contains implements of the `Lift` and `TypeFoldable`
2 //! traits for various types in the Rust compiler. Most are written by
3 //! hand, though we've recently added some macros and proc-macros to help with the tedium.
4
5 use crate::mir::interpret;
6 use crate::mir::{Field, ProjectionKind};
7 use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeSuperFoldable};
8 use crate::ty::print::{with_no_trimmed_paths, FmtPrinter, Printer};
9 use crate::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor};
10 use crate::ty::{self, InferConst, Lift, Term, TermKind, Ty, TyCtxt};
11 use rustc_data_structures::functor::IdFunctor;
12 use rustc_hir::def::Namespace;
13 use rustc_index::vec::{Idx, IndexVec};
14
15 use std::fmt;
16 use std::mem::ManuallyDrop;
17 use std::ops::ControlFlow;
18 use std::rc::Rc;
19 use std::sync::Arc;
20
21 impl fmt::Debug for ty::TraitDef {
22     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23         ty::tls::with(|tcx| {
24             with_no_trimmed_paths!({
25                 f.write_str(
26                     &FmtPrinter::new(tcx, Namespace::TypeNS)
27                         .print_def_path(self.def_id, &[])?
28                         .into_buffer(),
29                 )
30             })
31         })
32     }
33 }
34
35 impl<'tcx> fmt::Debug for ty::AdtDef<'tcx> {
36     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37         ty::tls::with(|tcx| {
38             with_no_trimmed_paths!({
39                 f.write_str(
40                     &FmtPrinter::new(tcx, Namespace::TypeNS)
41                         .print_def_path(self.did(), &[])?
42                         .into_buffer(),
43                 )
44             })
45         })
46     }
47 }
48
49 impl 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
56 impl<'tcx> fmt::Debug for ty::ExistentialTraitRef<'tcx> {
57     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58         with_no_trimmed_paths!(fmt::Display::fmt(self, f))
59     }
60 }
61
62 impl<'tcx> fmt::Debug for ty::adjustment::Adjustment<'tcx> {
63     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64         write!(f, "{:?} -> {}", self.kind, self.target)
65     }
66 }
67
68 impl fmt::Debug for ty::BoundRegionKind {
69     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70         match *self {
71             ty::BrAnon(n, span) => write!(f, "BrAnon({n:?}, {span:?})"),
72             ty::BrNamed(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::BrEnv => write!(f, "BrEnv"),
80         }
81     }
82 }
83
84 impl fmt::Debug for ty::FreeRegion {
85     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86         write!(f, "ReFree({:?}, {:?})", self.scope, self.bound_region)
87     }
88 }
89
90 impl<'tcx> fmt::Debug for ty::FnSig<'tcx> {
91     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92         write!(f, "({:?}; c_variadic: {})->{:?}", self.inputs(), self.c_variadic, self.output())
93     }
94 }
95
96 impl<'tcx> fmt::Debug for ty::ConstVid<'tcx> {
97     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98         write!(f, "_#{}c", self.index)
99     }
100 }
101
102 impl fmt::Debug for ty::RegionVid {
103     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104         write!(f, "'_#{}r", self.index())
105     }
106 }
107
108 impl<'tcx> fmt::Debug for ty::TraitRef<'tcx> {
109     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110         with_no_trimmed_paths!(fmt::Display::fmt(self, f))
111     }
112 }
113
114 impl<'tcx> fmt::Debug for Ty<'tcx> {
115     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116         with_no_trimmed_paths!(fmt::Display::fmt(self, f))
117     }
118 }
119
120 impl fmt::Debug for ty::ParamTy {
121     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122         write!(f, "{}/#{}", self.name, self.index)
123     }
124 }
125
126 impl fmt::Debug for ty::ParamConst {
127     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128         write!(f, "{}/#{}", self.name, self.index)
129     }
130 }
131
132 impl<'tcx> fmt::Debug for ty::TraitPredicate<'tcx> {
133     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134         if let ty::BoundConstness::ConstIfConst = self.constness {
135             write!(f, "~const ")?;
136         }
137         write!(f, "TraitPredicate({:?}, polarity:{:?})", self.trait_ref, self.polarity)
138     }
139 }
140
141 impl<'tcx> fmt::Debug for ty::ProjectionPredicate<'tcx> {
142     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143         write!(f, "ProjectionPredicate({:?}, {:?})", self.projection_ty, self.term)
144     }
145 }
146
147 impl<'tcx> fmt::Debug for ty::Predicate<'tcx> {
148     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149         write!(f, "{:?}", self.kind())
150     }
151 }
152
153 impl<'tcx> fmt::Debug for ty::PredicateKind<'tcx> {
154     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155         match *self {
156             ty::PredicateKind::Trait(ref a) => a.fmt(f),
157             ty::PredicateKind::Subtype(ref pair) => pair.fmt(f),
158             ty::PredicateKind::Coerce(ref pair) => pair.fmt(f),
159             ty::PredicateKind::RegionOutlives(ref pair) => pair.fmt(f),
160             ty::PredicateKind::TypeOutlives(ref pair) => pair.fmt(f),
161             ty::PredicateKind::Projection(ref pair) => pair.fmt(f),
162             ty::PredicateKind::WellFormed(data) => write!(f, "WellFormed({:?})", data),
163             ty::PredicateKind::ObjectSafe(trait_def_id) => {
164                 write!(f, "ObjectSafe({:?})", trait_def_id)
165             }
166             ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
167                 write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_substs, kind)
168             }
169             ty::PredicateKind::ConstEvaluatable(ct) => {
170                 write!(f, "ConstEvaluatable({ct:?})")
171             }
172             ty::PredicateKind::ConstEquate(c1, c2) => write!(f, "ConstEquate({:?}, {:?})", c1, c2),
173             ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
174                 write!(f, "TypeWellFormedFromEnv({:?})", ty)
175             }
176         }
177     }
178 }
179
180 ///////////////////////////////////////////////////////////////////////////
181 // Atomic structs
182 //
183 // For things that don't carry any arena-allocated data (and are
184 // copy...), just add them to this list.
185
186 TrivialTypeTraversalAndLiftImpls! {
187     (),
188     bool,
189     usize,
190     ::rustc_target::abi::VariantIdx,
191     u32,
192     u64,
193     String,
194     crate::middle::region::Scope,
195     crate::ty::FloatTy,
196     ::rustc_ast::InlineAsmOptions,
197     ::rustc_ast::InlineAsmTemplatePiece,
198     ::rustc_ast::NodeId,
199     ::rustc_span::symbol::Symbol,
200     ::rustc_hir::def::Res,
201     ::rustc_hir::def_id::DefId,
202     ::rustc_hir::def_id::LocalDefId,
203     ::rustc_hir::HirId,
204     ::rustc_hir::MatchSource,
205     ::rustc_hir::Mutability,
206     ::rustc_hir::Unsafety,
207     ::rustc_target::asm::InlineAsmRegOrRegClass,
208     ::rustc_target::spec::abi::Abi,
209     crate::mir::coverage::ExpressionOperandId,
210     crate::mir::coverage::CounterValueReference,
211     crate::mir::coverage::InjectedExpressionId,
212     crate::mir::coverage::InjectedExpressionIndex,
213     crate::mir::coverage::MappedExpressionIndex,
214     crate::mir::Local,
215     crate::mir::Promoted,
216     crate::traits::Reveal,
217     crate::ty::adjustment::AutoBorrowMutability,
218     crate::ty::AdtKind,
219     crate::ty::BoundConstness,
220     // Including `BoundRegionKind` is a *bit* dubious, but direct
221     // references to bound region appear in `ty::Error`, and aren't
222     // really meant to be folded. In general, we can only fold a fully
223     // general `Region`.
224     crate::ty::BoundRegionKind,
225     crate::ty::AssocItem,
226     crate::ty::AssocKind,
227     crate::ty::Placeholder<crate::ty::BoundRegionKind>,
228     crate::ty::ClosureKind,
229     crate::ty::FreeRegion,
230     crate::ty::InferTy,
231     crate::ty::IntVarValue,
232     crate::ty::ParamConst,
233     crate::ty::ParamTy,
234     crate::ty::adjustment::PointerCast,
235     crate::ty::RegionVid,
236     crate::ty::UniverseIndex,
237     crate::ty::Variance,
238     ::rustc_span::Span,
239     ::rustc_errors::ErrorGuaranteed,
240     Field,
241     interpret::Scalar,
242     rustc_target::abi::Size,
243     rustc_type_ir::DebruijnIndex,
244     ty::BoundVar,
245     ty::Placeholder<ty::BoundVar>,
246 }
247
248 TrivialTypeTraversalAndLiftImpls! {
249     for<'tcx> {
250         ty::ValTree<'tcx>,
251     }
252 }
253
254 ///////////////////////////////////////////////////////////////////////////
255 // Lift implementations
256
257 impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>> Lift<'tcx> for (A, B) {
258     type Lifted = (A::Lifted, B::Lifted);
259     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
260         Some((tcx.lift(self.0)?, tcx.lift(self.1)?))
261     }
262 }
263
264 impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>, C: Lift<'tcx>> Lift<'tcx> for (A, B, C) {
265     type Lifted = (A::Lifted, B::Lifted, C::Lifted);
266     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
267         Some((tcx.lift(self.0)?, tcx.lift(self.1)?, tcx.lift(self.2)?))
268     }
269 }
270
271 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Option<T> {
272     type Lifted = Option<T::Lifted>;
273     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
274         Some(match self {
275             Some(x) => Some(tcx.lift(x)?),
276             None => None,
277         })
278     }
279 }
280
281 impl<'tcx, T: Lift<'tcx>, E: Lift<'tcx>> Lift<'tcx> for Result<T, E> {
282     type Lifted = Result<T::Lifted, E::Lifted>;
283     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
284         match self {
285             Ok(x) => tcx.lift(x).map(Ok),
286             Err(e) => tcx.lift(e).map(Err),
287         }
288     }
289 }
290
291 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Box<T> {
292     type Lifted = Box<T::Lifted>;
293     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
294         Some(Box::new(tcx.lift(*self)?))
295     }
296 }
297
298 impl<'tcx, T: Lift<'tcx> + Clone> Lift<'tcx> for Rc<T> {
299     type Lifted = Rc<T::Lifted>;
300     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
301         Some(Rc::new(tcx.lift(self.as_ref().clone())?))
302     }
303 }
304
305 impl<'tcx, T: Lift<'tcx> + Clone> Lift<'tcx> for Arc<T> {
306     type Lifted = Arc<T::Lifted>;
307     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
308         Some(Arc::new(tcx.lift(self.as_ref().clone())?))
309     }
310 }
311 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Vec<T> {
312     type Lifted = Vec<T::Lifted>;
313     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
314         self.into_iter().map(|v| tcx.lift(v)).collect()
315     }
316 }
317
318 impl<'tcx, I: Idx, T: Lift<'tcx>> Lift<'tcx> for IndexVec<I, T> {
319     type Lifted = IndexVec<I, T::Lifted>;
320     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
321         self.into_iter().map(|e| tcx.lift(e)).collect()
322     }
323 }
324
325 impl<'a, 'tcx> Lift<'tcx> for Term<'a> {
326     type Lifted = ty::Term<'tcx>;
327     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
328         Some(
329             match self.unpack() {
330                 TermKind::Ty(ty) => TermKind::Ty(tcx.lift(ty)?),
331                 TermKind::Const(c) => TermKind::Const(tcx.lift(c)?),
332             }
333             .pack(),
334         )
335     }
336 }
337 impl<'a, 'tcx> Lift<'tcx> for ty::ParamEnv<'a> {
338     type Lifted = ty::ParamEnv<'tcx>;
339     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
340         tcx.lift(self.caller_bounds())
341             .map(|caller_bounds| ty::ParamEnv::new(caller_bounds, self.reveal(), self.constness()))
342     }
343 }
344
345 ///////////////////////////////////////////////////////////////////////////
346 // TypeFoldable implementations.
347
348 /// AdtDefs are basically the same as a DefId.
349 impl<'tcx> TypeFoldable<'tcx> for ty::AdtDef<'tcx> {
350     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, _folder: &mut F) -> Result<Self, F::Error> {
351         Ok(self)
352     }
353 }
354
355 impl<'tcx> TypeVisitable<'tcx> for ty::AdtDef<'tcx> {
356     fn visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> ControlFlow<V::BreakTy> {
357         ControlFlow::CONTINUE
358     }
359 }
360
361 impl<'tcx, T: TypeFoldable<'tcx>, U: TypeFoldable<'tcx>> TypeFoldable<'tcx> for (T, U) {
362     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(
363         self,
364         folder: &mut F,
365     ) -> Result<(T, U), F::Error> {
366         Ok((self.0.try_fold_with(folder)?, self.1.try_fold_with(folder)?))
367     }
368 }
369
370 impl<'tcx, T: TypeVisitable<'tcx>, U: TypeVisitable<'tcx>> TypeVisitable<'tcx> for (T, U) {
371     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
372         self.0.visit_with(visitor)?;
373         self.1.visit_with(visitor)
374     }
375 }
376
377 impl<'tcx, A: TypeFoldable<'tcx>, B: TypeFoldable<'tcx>, C: TypeFoldable<'tcx>> TypeFoldable<'tcx>
378     for (A, B, C)
379 {
380     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(
381         self,
382         folder: &mut F,
383     ) -> Result<(A, B, C), F::Error> {
384         Ok((
385             self.0.try_fold_with(folder)?,
386             self.1.try_fold_with(folder)?,
387             self.2.try_fold_with(folder)?,
388         ))
389     }
390 }
391
392 impl<'tcx, A: TypeVisitable<'tcx>, B: TypeVisitable<'tcx>, C: TypeVisitable<'tcx>>
393     TypeVisitable<'tcx> for (A, B, C)
394 {
395     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
396         self.0.visit_with(visitor)?;
397         self.1.visit_with(visitor)?;
398         self.2.visit_with(visitor)
399     }
400 }
401
402 EnumTypeTraversalImpl! {
403     impl<'tcx, T> TypeFoldable<'tcx> for Option<T> {
404         (Some)(a),
405         (None),
406     } where T: TypeFoldable<'tcx>
407 }
408 EnumTypeTraversalImpl! {
409     impl<'tcx, T> TypeVisitable<'tcx> for Option<T> {
410         (Some)(a),
411         (None),
412     } where T: TypeVisitable<'tcx>
413 }
414
415 EnumTypeTraversalImpl! {
416     impl<'tcx, T, E> TypeFoldable<'tcx> for Result<T, E> {
417         (Ok)(a),
418         (Err)(a),
419     } where T: TypeFoldable<'tcx>, E: TypeFoldable<'tcx>,
420 }
421 EnumTypeTraversalImpl! {
422     impl<'tcx, T, E> TypeVisitable<'tcx> for Result<T, E> {
423         (Ok)(a),
424         (Err)(a),
425     } where T: TypeVisitable<'tcx>, E: TypeVisitable<'tcx>,
426 }
427
428 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Rc<T> {
429     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(
430         mut self,
431         folder: &mut F,
432     ) -> Result<Self, F::Error> {
433         // We merely want to replace the contained `T`, if at all possible,
434         // so that we don't needlessly allocate a new `Rc` or indeed clone
435         // the contained type.
436         unsafe {
437             // First step is to ensure that we have a unique reference to
438             // the contained type, which `Rc::make_mut` will accomplish (by
439             // allocating a new `Rc` and cloning the `T` only if required).
440             // This is done *before* casting to `Rc<ManuallyDrop<T>>` so that
441             // panicking during `make_mut` does not leak the `T`.
442             Rc::make_mut(&mut self);
443
444             // Casting to `Rc<ManuallyDrop<T>>` is safe because `ManuallyDrop`
445             // is `repr(transparent)`.
446             let ptr = Rc::into_raw(self).cast::<ManuallyDrop<T>>();
447             let mut unique = Rc::from_raw(ptr);
448
449             // Call to `Rc::make_mut` above guarantees that `unique` is the
450             // sole reference to the contained value, so we can avoid doing
451             // a checked `get_mut` here.
452             let slot = Rc::get_mut_unchecked(&mut unique);
453
454             // Semantically move the contained type out from `unique`, fold
455             // it, then move the folded value back into `unique`.  Should
456             // folding fail, `ManuallyDrop` ensures that the "moved-out"
457             // value is not re-dropped.
458             let owned = ManuallyDrop::take(slot);
459             let folded = owned.try_fold_with(folder)?;
460             *slot = ManuallyDrop::new(folded);
461
462             // Cast back to `Rc<T>`.
463             Ok(Rc::from_raw(Rc::into_raw(unique).cast()))
464         }
465     }
466 }
467
468 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for Rc<T> {
469     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
470         (**self).visit_with(visitor)
471     }
472 }
473
474 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Arc<T> {
475     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(
476         mut self,
477         folder: &mut F,
478     ) -> Result<Self, F::Error> {
479         // We merely want to replace the contained `T`, if at all possible,
480         // so that we don't needlessly allocate a new `Arc` or indeed clone
481         // the contained type.
482         unsafe {
483             // First step is to ensure that we have a unique reference to
484             // the contained type, which `Arc::make_mut` will accomplish (by
485             // allocating a new `Arc` and cloning the `T` only if required).
486             // This is done *before* casting to `Arc<ManuallyDrop<T>>` so that
487             // panicking during `make_mut` does not leak the `T`.
488             Arc::make_mut(&mut self);
489
490             // Casting to `Arc<ManuallyDrop<T>>` is safe because `ManuallyDrop`
491             // is `repr(transparent)`.
492             let ptr = Arc::into_raw(self).cast::<ManuallyDrop<T>>();
493             let mut unique = Arc::from_raw(ptr);
494
495             // Call to `Arc::make_mut` above guarantees that `unique` is the
496             // sole reference to the contained value, so we can avoid doing
497             // a checked `get_mut` here.
498             let slot = Arc::get_mut_unchecked(&mut unique);
499
500             // Semantically move the contained type out from `unique`, fold
501             // it, then move the folded value back into `unique`.  Should
502             // folding fail, `ManuallyDrop` ensures that the "moved-out"
503             // value is not re-dropped.
504             let owned = ManuallyDrop::take(slot);
505             let folded = owned.try_fold_with(folder)?;
506             *slot = ManuallyDrop::new(folded);
507
508             // Cast back to `Arc<T>`.
509             Ok(Arc::from_raw(Arc::into_raw(unique).cast()))
510         }
511     }
512 }
513
514 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for Arc<T> {
515     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
516         (**self).visit_with(visitor)
517     }
518 }
519
520 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Box<T> {
521     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
522         self.try_map_id(|value| value.try_fold_with(folder))
523     }
524 }
525
526 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for Box<T> {
527     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
528         (**self).visit_with(visitor)
529     }
530 }
531
532 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Vec<T> {
533     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
534         self.try_map_id(|t| t.try_fold_with(folder))
535     }
536 }
537
538 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for Vec<T> {
539     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
540         self.iter().try_for_each(|t| t.visit_with(visitor))
541     }
542 }
543
544 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for &[T] {
545     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
546         self.iter().try_for_each(|t| t.visit_with(visitor))
547     }
548 }
549
550 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Box<[T]> {
551     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
552         self.try_map_id(|t| t.try_fold_with(folder))
553     }
554 }
555
556 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for Box<[T]> {
557     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
558         self.iter().try_for_each(|t| t.visit_with(visitor))
559     }
560 }
561
562 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for ty::Binder<'tcx, T> {
563     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
564         folder.try_fold_binder(self)
565     }
566 }
567
568 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for ty::Binder<'tcx, T> {
569     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
570         visitor.visit_binder(self)
571     }
572 }
573
574 impl<'tcx, T: TypeFoldable<'tcx>> TypeSuperFoldable<'tcx> for ty::Binder<'tcx, T> {
575     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
576         self,
577         folder: &mut F,
578     ) -> Result<Self, F::Error> {
579         self.try_map_bound(|ty| ty.try_fold_with(folder))
580     }
581 }
582
583 impl<'tcx, T: TypeVisitable<'tcx>> TypeSuperVisitable<'tcx> for ty::Binder<'tcx, T> {
584     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
585         self.as_ref().skip_binder().visit_with(visitor)
586     }
587 }
588
589 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> {
590     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
591         ty::util::fold_list(self, folder, |tcx, v| tcx.intern_poly_existential_predicates(v))
592     }
593 }
594
595 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<ProjectionKind> {
596     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
597         ty::util::fold_list(self, folder, |tcx, v| tcx.intern_projs(v))
598     }
599 }
600
601 impl<'tcx> TypeFoldable<'tcx> for Ty<'tcx> {
602     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
603         folder.try_fold_ty(self)
604     }
605 }
606
607 impl<'tcx> TypeVisitable<'tcx> for Ty<'tcx> {
608     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
609         visitor.visit_ty(*self)
610     }
611 }
612
613 impl<'tcx> TypeSuperFoldable<'tcx> for Ty<'tcx> {
614     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
615         self,
616         folder: &mut F,
617     ) -> Result<Self, F::Error> {
618         let kind = match *self.kind() {
619             ty::RawPtr(tm) => ty::RawPtr(tm.try_fold_with(folder)?),
620             ty::Array(typ, sz) => ty::Array(typ.try_fold_with(folder)?, sz.try_fold_with(folder)?),
621             ty::Slice(typ) => ty::Slice(typ.try_fold_with(folder)?),
622             ty::Adt(tid, substs) => ty::Adt(tid, substs.try_fold_with(folder)?),
623             ty::Dynamic(trait_ty, region, representation) => ty::Dynamic(
624                 trait_ty.try_fold_with(folder)?,
625                 region.try_fold_with(folder)?,
626                 representation,
627             ),
628             ty::Tuple(ts) => ty::Tuple(ts.try_fold_with(folder)?),
629             ty::FnDef(def_id, substs) => ty::FnDef(def_id, substs.try_fold_with(folder)?),
630             ty::FnPtr(f) => ty::FnPtr(f.try_fold_with(folder)?),
631             ty::Ref(r, ty, mutbl) => {
632                 ty::Ref(r.try_fold_with(folder)?, ty.try_fold_with(folder)?, mutbl)
633             }
634             ty::Generator(did, substs, movability) => {
635                 ty::Generator(did, substs.try_fold_with(folder)?, movability)
636             }
637             ty::GeneratorWitness(types) => ty::GeneratorWitness(types.try_fold_with(folder)?),
638             ty::Closure(did, substs) => ty::Closure(did, substs.try_fold_with(folder)?),
639             ty::Projection(data) => ty::Projection(data.try_fold_with(folder)?),
640             ty::Opaque(did, substs) => ty::Opaque(did, substs.try_fold_with(folder)?),
641
642             ty::Bool
643             | ty::Char
644             | ty::Str
645             | ty::Int(_)
646             | ty::Uint(_)
647             | ty::Float(_)
648             | ty::Error(_)
649             | ty::Infer(_)
650             | ty::Param(..)
651             | ty::Bound(..)
652             | ty::Placeholder(..)
653             | ty::Never
654             | ty::Foreign(..) => return Ok(self),
655         };
656
657         Ok(if *self.kind() == kind { self } else { folder.tcx().mk_ty(kind) })
658     }
659 }
660
661 impl<'tcx> TypeSuperVisitable<'tcx> for Ty<'tcx> {
662     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
663         match self.kind() {
664             ty::RawPtr(ref tm) => tm.visit_with(visitor),
665             ty::Array(typ, sz) => {
666                 typ.visit_with(visitor)?;
667                 sz.visit_with(visitor)
668             }
669             ty::Slice(typ) => typ.visit_with(visitor),
670             ty::Adt(_, substs) => substs.visit_with(visitor),
671             ty::Dynamic(ref trait_ty, ref reg, _) => {
672                 trait_ty.visit_with(visitor)?;
673                 reg.visit_with(visitor)
674             }
675             ty::Tuple(ts) => ts.visit_with(visitor),
676             ty::FnDef(_, substs) => substs.visit_with(visitor),
677             ty::FnPtr(ref f) => f.visit_with(visitor),
678             ty::Ref(r, ty, _) => {
679                 r.visit_with(visitor)?;
680                 ty.visit_with(visitor)
681             }
682             ty::Generator(_did, ref substs, _) => substs.visit_with(visitor),
683             ty::GeneratorWitness(ref types) => types.visit_with(visitor),
684             ty::Closure(_did, ref substs) => substs.visit_with(visitor),
685             ty::Projection(ref data) => data.visit_with(visitor),
686             ty::Opaque(_, ref substs) => substs.visit_with(visitor),
687
688             ty::Bool
689             | ty::Char
690             | ty::Str
691             | ty::Int(_)
692             | ty::Uint(_)
693             | ty::Float(_)
694             | ty::Error(_)
695             | ty::Infer(_)
696             | ty::Bound(..)
697             | ty::Placeholder(..)
698             | ty::Param(..)
699             | ty::Never
700             | ty::Foreign(..) => ControlFlow::CONTINUE,
701         }
702     }
703 }
704
705 impl<'tcx> TypeFoldable<'tcx> for ty::Region<'tcx> {
706     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
707         folder.try_fold_region(self)
708     }
709 }
710
711 impl<'tcx> TypeVisitable<'tcx> for ty::Region<'tcx> {
712     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
713         visitor.visit_region(*self)
714     }
715 }
716
717 impl<'tcx> TypeSuperFoldable<'tcx> for ty::Region<'tcx> {
718     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
719         self,
720         _folder: &mut F,
721     ) -> Result<Self, F::Error> {
722         Ok(self)
723     }
724 }
725
726 impl<'tcx> TypeSuperVisitable<'tcx> for ty::Region<'tcx> {
727     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> ControlFlow<V::BreakTy> {
728         ControlFlow::CONTINUE
729     }
730 }
731
732 impl<'tcx> TypeFoldable<'tcx> for ty::Predicate<'tcx> {
733     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
734         folder.try_fold_predicate(self)
735     }
736 }
737
738 impl<'tcx> TypeVisitable<'tcx> for ty::Predicate<'tcx> {
739     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
740         visitor.visit_predicate(*self)
741     }
742
743     #[inline]
744     fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool {
745         self.outer_exclusive_binder() > binder
746     }
747
748     #[inline]
749     fn has_type_flags(&self, flags: ty::TypeFlags) -> bool {
750         self.flags().intersects(flags)
751     }
752 }
753
754 impl<'tcx> TypeSuperFoldable<'tcx> for ty::Predicate<'tcx> {
755     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
756         self,
757         folder: &mut F,
758     ) -> Result<Self, F::Error> {
759         let new = self.kind().try_fold_with(folder)?;
760         Ok(folder.tcx().reuse_or_mk_predicate(self, new))
761     }
762 }
763
764 impl<'tcx> TypeSuperVisitable<'tcx> for ty::Predicate<'tcx> {
765     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
766         self.kind().visit_with(visitor)
767     }
768 }
769
770 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<ty::Predicate<'tcx>> {
771     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
772         ty::util::fold_list(self, folder, |tcx, v| tcx.intern_predicates(v))
773     }
774 }
775
776 impl<'tcx, T: TypeFoldable<'tcx>, I: Idx> TypeFoldable<'tcx> for IndexVec<I, T> {
777     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
778         self.try_map_id(|x| x.try_fold_with(folder))
779     }
780 }
781
782 impl<'tcx, T: TypeVisitable<'tcx>, I: Idx> TypeVisitable<'tcx> for IndexVec<I, T> {
783     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
784         self.iter().try_for_each(|t| t.visit_with(visitor))
785     }
786 }
787
788 impl<'tcx> TypeFoldable<'tcx> for ty::Const<'tcx> {
789     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
790         folder.try_fold_const(self)
791     }
792 }
793
794 impl<'tcx> TypeVisitable<'tcx> for ty::Const<'tcx> {
795     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
796         visitor.visit_const(*self)
797     }
798 }
799
800 impl<'tcx> TypeSuperFoldable<'tcx> for ty::Const<'tcx> {
801     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
802         self,
803         folder: &mut F,
804     ) -> Result<Self, F::Error> {
805         let ty = self.ty().try_fold_with(folder)?;
806         let kind = self.kind().try_fold_with(folder)?;
807         if ty != self.ty() || kind != self.kind() {
808             Ok(folder.tcx().mk_const(kind, ty))
809         } else {
810             Ok(self)
811         }
812     }
813 }
814
815 impl<'tcx> TypeSuperVisitable<'tcx> for ty::Const<'tcx> {
816     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
817         self.ty().visit_with(visitor)?;
818         self.kind().visit_with(visitor)
819     }
820 }
821
822 impl<'tcx> TypeFoldable<'tcx> for InferConst<'tcx> {
823     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, _folder: &mut F) -> Result<Self, F::Error> {
824         Ok(self)
825     }
826 }
827
828 impl<'tcx> TypeVisitable<'tcx> for InferConst<'tcx> {
829     fn visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> ControlFlow<V::BreakTy> {
830         ControlFlow::CONTINUE
831     }
832 }
833
834 impl<'tcx> TypeSuperVisitable<'tcx> for ty::UnevaluatedConst<'tcx> {
835     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
836         self.substs.visit_with(visitor)
837     }
838 }