]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/structural_impls.rs
Auto merge of #102596 - scottmcm:option-bool-calloc, 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) => write!(f, "BrAnon({:?})", n),
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(uv) => {
170                 write!(f, "ConstEvaluatable({:?}, {:?})", uv.def, uv.substs)
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     ty::DelaySpanBugEmitted,
244     rustc_type_ir::DebruijnIndex,
245     ty::BoundVar,
246     ty::Placeholder<ty::BoundVar>,
247 }
248
249 TrivialTypeTraversalAndLiftImpls! {
250     for<'tcx> {
251         ty::ValTree<'tcx>,
252     }
253 }
254
255 ///////////////////////////////////////////////////////////////////////////
256 // Lift implementations
257
258 impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>> Lift<'tcx> for (A, B) {
259     type Lifted = (A::Lifted, B::Lifted);
260     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
261         Some((tcx.lift(self.0)?, tcx.lift(self.1)?))
262     }
263 }
264
265 impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>, C: Lift<'tcx>> Lift<'tcx> for (A, B, C) {
266     type Lifted = (A::Lifted, B::Lifted, C::Lifted);
267     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
268         Some((tcx.lift(self.0)?, tcx.lift(self.1)?, tcx.lift(self.2)?))
269     }
270 }
271
272 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Option<T> {
273     type Lifted = Option<T::Lifted>;
274     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
275         Some(match self {
276             Some(x) => Some(tcx.lift(x)?),
277             None => None,
278         })
279     }
280 }
281
282 impl<'tcx, T: Lift<'tcx>, E: Lift<'tcx>> Lift<'tcx> for Result<T, E> {
283     type Lifted = Result<T::Lifted, E::Lifted>;
284     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
285         match self {
286             Ok(x) => tcx.lift(x).map(Ok),
287             Err(e) => tcx.lift(e).map(Err),
288         }
289     }
290 }
291
292 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Box<T> {
293     type Lifted = Box<T::Lifted>;
294     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
295         Some(Box::new(tcx.lift(*self)?))
296     }
297 }
298
299 impl<'tcx, T: Lift<'tcx> + Clone> Lift<'tcx> for Rc<T> {
300     type Lifted = Rc<T::Lifted>;
301     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
302         Some(Rc::new(tcx.lift(self.as_ref().clone())?))
303     }
304 }
305
306 impl<'tcx, T: Lift<'tcx> + Clone> Lift<'tcx> for Arc<T> {
307     type Lifted = Arc<T::Lifted>;
308     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
309         Some(Arc::new(tcx.lift(self.as_ref().clone())?))
310     }
311 }
312 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Vec<T> {
313     type Lifted = Vec<T::Lifted>;
314     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
315         self.into_iter().map(|v| tcx.lift(v)).collect()
316     }
317 }
318
319 impl<'tcx, I: Idx, T: Lift<'tcx>> Lift<'tcx> for IndexVec<I, T> {
320     type Lifted = IndexVec<I, T::Lifted>;
321     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
322         self.into_iter().map(|e| tcx.lift(e)).collect()
323     }
324 }
325
326 impl<'a, 'tcx> Lift<'tcx> for Term<'a> {
327     type Lifted = ty::Term<'tcx>;
328     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
329         Some(
330             match self.unpack() {
331                 TermKind::Ty(ty) => TermKind::Ty(tcx.lift(ty)?),
332                 TermKind::Const(c) => TermKind::Const(tcx.lift(c)?),
333             }
334             .pack(),
335         )
336     }
337 }
338 impl<'a, 'tcx> Lift<'tcx> for ty::ParamEnv<'a> {
339     type Lifted = ty::ParamEnv<'tcx>;
340     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
341         tcx.lift(self.caller_bounds())
342             .map(|caller_bounds| ty::ParamEnv::new(caller_bounds, self.reveal(), self.constness()))
343     }
344 }
345
346 ///////////////////////////////////////////////////////////////////////////
347 // TypeFoldable implementations.
348
349 /// AdtDefs are basically the same as a DefId.
350 impl<'tcx> TypeFoldable<'tcx> for ty::AdtDef<'tcx> {
351     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, _folder: &mut F) -> Result<Self, F::Error> {
352         Ok(self)
353     }
354 }
355
356 impl<'tcx> TypeVisitable<'tcx> for ty::AdtDef<'tcx> {
357     fn visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> ControlFlow<V::BreakTy> {
358         ControlFlow::CONTINUE
359     }
360 }
361
362 impl<'tcx, T: TypeFoldable<'tcx>, U: TypeFoldable<'tcx>> TypeFoldable<'tcx> for (T, U) {
363     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(
364         self,
365         folder: &mut F,
366     ) -> Result<(T, U), F::Error> {
367         Ok((self.0.try_fold_with(folder)?, self.1.try_fold_with(folder)?))
368     }
369 }
370
371 impl<'tcx, T: TypeVisitable<'tcx>, U: TypeVisitable<'tcx>> TypeVisitable<'tcx> for (T, U) {
372     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
373         self.0.visit_with(visitor)?;
374         self.1.visit_with(visitor)
375     }
376 }
377
378 impl<'tcx, A: TypeFoldable<'tcx>, B: TypeFoldable<'tcx>, C: TypeFoldable<'tcx>> TypeFoldable<'tcx>
379     for (A, B, C)
380 {
381     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(
382         self,
383         folder: &mut F,
384     ) -> Result<(A, B, C), F::Error> {
385         Ok((
386             self.0.try_fold_with(folder)?,
387             self.1.try_fold_with(folder)?,
388             self.2.try_fold_with(folder)?,
389         ))
390     }
391 }
392
393 impl<'tcx, A: TypeVisitable<'tcx>, B: TypeVisitable<'tcx>, C: TypeVisitable<'tcx>>
394     TypeVisitable<'tcx> for (A, B, C)
395 {
396     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
397         self.0.visit_with(visitor)?;
398         self.1.visit_with(visitor)?;
399         self.2.visit_with(visitor)
400     }
401 }
402
403 EnumTypeTraversalImpl! {
404     impl<'tcx, T> TypeFoldable<'tcx> for Option<T> {
405         (Some)(a),
406         (None),
407     } where T: TypeFoldable<'tcx>
408 }
409 EnumTypeTraversalImpl! {
410     impl<'tcx, T> TypeVisitable<'tcx> for Option<T> {
411         (Some)(a),
412         (None),
413     } where T: TypeVisitable<'tcx>
414 }
415
416 EnumTypeTraversalImpl! {
417     impl<'tcx, T, E> TypeFoldable<'tcx> for Result<T, E> {
418         (Ok)(a),
419         (Err)(a),
420     } where T: TypeFoldable<'tcx>, E: TypeFoldable<'tcx>,
421 }
422 EnumTypeTraversalImpl! {
423     impl<'tcx, T, E> TypeVisitable<'tcx> for Result<T, E> {
424         (Ok)(a),
425         (Err)(a),
426     } where T: TypeVisitable<'tcx>, E: TypeVisitable<'tcx>,
427 }
428
429 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Rc<T> {
430     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(
431         mut self,
432         folder: &mut F,
433     ) -> Result<Self, F::Error> {
434         // We merely want to replace the contained `T`, if at all possible,
435         // so that we don't needlessly allocate a new `Rc` or indeed clone
436         // the contained type.
437         unsafe {
438             // First step is to ensure that we have a unique reference to
439             // the contained type, which `Rc::make_mut` will accomplish (by
440             // allocating a new `Rc` and cloning the `T` only if required).
441             // This is done *before* casting to `Rc<ManuallyDrop<T>>` so that
442             // panicking during `make_mut` does not leak the `T`.
443             Rc::make_mut(&mut self);
444
445             // Casting to `Rc<ManuallyDrop<T>>` is safe because `ManuallyDrop`
446             // is `repr(transparent)`.
447             let ptr = Rc::into_raw(self).cast::<ManuallyDrop<T>>();
448             let mut unique = Rc::from_raw(ptr);
449
450             // Call to `Rc::make_mut` above guarantees that `unique` is the
451             // sole reference to the contained value, so we can avoid doing
452             // a checked `get_mut` here.
453             let slot = Rc::get_mut_unchecked(&mut unique);
454
455             // Semantically move the contained type out from `unique`, fold
456             // it, then move the folded value back into `unique`.  Should
457             // folding fail, `ManuallyDrop` ensures that the "moved-out"
458             // value is not re-dropped.
459             let owned = ManuallyDrop::take(slot);
460             let folded = owned.try_fold_with(folder)?;
461             *slot = ManuallyDrop::new(folded);
462
463             // Cast back to `Rc<T>`.
464             Ok(Rc::from_raw(Rc::into_raw(unique).cast()))
465         }
466     }
467 }
468
469 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for Rc<T> {
470     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
471         (**self).visit_with(visitor)
472     }
473 }
474
475 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Arc<T> {
476     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(
477         mut self,
478         folder: &mut F,
479     ) -> Result<Self, F::Error> {
480         // We merely want to replace the contained `T`, if at all possible,
481         // so that we don't needlessly allocate a new `Arc` or indeed clone
482         // the contained type.
483         unsafe {
484             // First step is to ensure that we have a unique reference to
485             // the contained type, which `Arc::make_mut` will accomplish (by
486             // allocating a new `Arc` and cloning the `T` only if required).
487             // This is done *before* casting to `Arc<ManuallyDrop<T>>` so that
488             // panicking during `make_mut` does not leak the `T`.
489             Arc::make_mut(&mut self);
490
491             // Casting to `Arc<ManuallyDrop<T>>` is safe because `ManuallyDrop`
492             // is `repr(transparent)`.
493             let ptr = Arc::into_raw(self).cast::<ManuallyDrop<T>>();
494             let mut unique = Arc::from_raw(ptr);
495
496             // Call to `Arc::make_mut` above guarantees that `unique` is the
497             // sole reference to the contained value, so we can avoid doing
498             // a checked `get_mut` here.
499             let slot = Arc::get_mut_unchecked(&mut unique);
500
501             // Semantically move the contained type out from `unique`, fold
502             // it, then move the folded value back into `unique`.  Should
503             // folding fail, `ManuallyDrop` ensures that the "moved-out"
504             // value is not re-dropped.
505             let owned = ManuallyDrop::take(slot);
506             let folded = owned.try_fold_with(folder)?;
507             *slot = ManuallyDrop::new(folded);
508
509             // Cast back to `Arc<T>`.
510             Ok(Arc::from_raw(Arc::into_raw(unique).cast()))
511         }
512     }
513 }
514
515 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for Arc<T> {
516     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
517         (**self).visit_with(visitor)
518     }
519 }
520
521 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Box<T> {
522     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
523         self.try_map_id(|value| value.try_fold_with(folder))
524     }
525 }
526
527 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for Box<T> {
528     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
529         (**self).visit_with(visitor)
530     }
531 }
532
533 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Vec<T> {
534     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
535         self.try_map_id(|t| t.try_fold_with(folder))
536     }
537 }
538
539 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for Vec<T> {
540     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
541         self.iter().try_for_each(|t| t.visit_with(visitor))
542     }
543 }
544
545 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for &[T] {
546     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
547         self.iter().try_for_each(|t| t.visit_with(visitor))
548     }
549 }
550
551 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Box<[T]> {
552     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
553         self.try_map_id(|t| t.try_fold_with(folder))
554     }
555 }
556
557 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for Box<[T]> {
558     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
559         self.iter().try_for_each(|t| t.visit_with(visitor))
560     }
561 }
562
563 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for ty::Binder<'tcx, T> {
564     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
565         folder.try_fold_binder(self)
566     }
567 }
568
569 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for ty::Binder<'tcx, T> {
570     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
571         visitor.visit_binder(self)
572     }
573 }
574
575 impl<'tcx, T: TypeFoldable<'tcx>> TypeSuperFoldable<'tcx> for ty::Binder<'tcx, T> {
576     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
577         self,
578         folder: &mut F,
579     ) -> Result<Self, F::Error> {
580         self.try_map_bound(|ty| ty.try_fold_with(folder))
581     }
582 }
583
584 impl<'tcx, T: TypeVisitable<'tcx>> TypeSuperVisitable<'tcx> for ty::Binder<'tcx, T> {
585     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
586         self.as_ref().skip_binder().visit_with(visitor)
587     }
588 }
589
590 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>> {
591     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
592         ty::util::fold_list(self, folder, |tcx, v| tcx.intern_poly_existential_predicates(v))
593     }
594 }
595
596 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<ProjectionKind> {
597     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
598         ty::util::fold_list(self, folder, |tcx, v| tcx.intern_projs(v))
599     }
600 }
601
602 impl<'tcx> TypeFoldable<'tcx> for Ty<'tcx> {
603     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
604         folder.try_fold_ty(self)
605     }
606 }
607
608 impl<'tcx> TypeVisitable<'tcx> for Ty<'tcx> {
609     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
610         visitor.visit_ty(*self)
611     }
612 }
613
614 impl<'tcx> TypeSuperFoldable<'tcx> for Ty<'tcx> {
615     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
616         self,
617         folder: &mut F,
618     ) -> Result<Self, F::Error> {
619         let kind = match *self.kind() {
620             ty::RawPtr(tm) => ty::RawPtr(tm.try_fold_with(folder)?),
621             ty::Array(typ, sz) => ty::Array(typ.try_fold_with(folder)?, sz.try_fold_with(folder)?),
622             ty::Slice(typ) => ty::Slice(typ.try_fold_with(folder)?),
623             ty::Adt(tid, substs) => ty::Adt(tid, substs.try_fold_with(folder)?),
624             ty::Dynamic(trait_ty, region, representation) => ty::Dynamic(
625                 trait_ty.try_fold_with(folder)?,
626                 region.try_fold_with(folder)?,
627                 representation,
628             ),
629             ty::Tuple(ts) => ty::Tuple(ts.try_fold_with(folder)?),
630             ty::FnDef(def_id, substs) => ty::FnDef(def_id, substs.try_fold_with(folder)?),
631             ty::FnPtr(f) => ty::FnPtr(f.try_fold_with(folder)?),
632             ty::Ref(r, ty, mutbl) => {
633                 ty::Ref(r.try_fold_with(folder)?, ty.try_fold_with(folder)?, mutbl)
634             }
635             ty::Generator(did, substs, movability) => {
636                 ty::Generator(did, substs.try_fold_with(folder)?, movability)
637             }
638             ty::GeneratorWitness(types) => ty::GeneratorWitness(types.try_fold_with(folder)?),
639             ty::Closure(did, substs) => ty::Closure(did, substs.try_fold_with(folder)?),
640             ty::Projection(data) => ty::Projection(data.try_fold_with(folder)?),
641             ty::Opaque(did, substs) => ty::Opaque(did, substs.try_fold_with(folder)?),
642
643             ty::Bool
644             | ty::Char
645             | ty::Str
646             | ty::Int(_)
647             | ty::Uint(_)
648             | ty::Float(_)
649             | ty::Error(_)
650             | ty::Infer(_)
651             | ty::Param(..)
652             | ty::Bound(..)
653             | ty::Placeholder(..)
654             | ty::Never
655             | ty::Foreign(..) => return Ok(self),
656         };
657
658         Ok(if *self.kind() == kind { self } else { folder.tcx().mk_ty(kind) })
659     }
660 }
661
662 impl<'tcx> TypeSuperVisitable<'tcx> for Ty<'tcx> {
663     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
664         match self.kind() {
665             ty::RawPtr(ref tm) => tm.visit_with(visitor),
666             ty::Array(typ, sz) => {
667                 typ.visit_with(visitor)?;
668                 sz.visit_with(visitor)
669             }
670             ty::Slice(typ) => typ.visit_with(visitor),
671             ty::Adt(_, substs) => substs.visit_with(visitor),
672             ty::Dynamic(ref trait_ty, ref reg, _) => {
673                 trait_ty.visit_with(visitor)?;
674                 reg.visit_with(visitor)
675             }
676             ty::Tuple(ts) => ts.visit_with(visitor),
677             ty::FnDef(_, substs) => substs.visit_with(visitor),
678             ty::FnPtr(ref f) => f.visit_with(visitor),
679             ty::Ref(r, ty, _) => {
680                 r.visit_with(visitor)?;
681                 ty.visit_with(visitor)
682             }
683             ty::Generator(_did, ref substs, _) => substs.visit_with(visitor),
684             ty::GeneratorWitness(ref types) => types.visit_with(visitor),
685             ty::Closure(_did, ref substs) => substs.visit_with(visitor),
686             ty::Projection(ref data) => data.visit_with(visitor),
687             ty::Opaque(_, ref substs) => substs.visit_with(visitor),
688
689             ty::Bool
690             | ty::Char
691             | ty::Str
692             | ty::Int(_)
693             | ty::Uint(_)
694             | ty::Float(_)
695             | ty::Error(_)
696             | ty::Infer(_)
697             | ty::Bound(..)
698             | ty::Placeholder(..)
699             | ty::Param(..)
700             | ty::Never
701             | ty::Foreign(..) => ControlFlow::CONTINUE,
702         }
703     }
704 }
705
706 impl<'tcx> TypeFoldable<'tcx> for ty::Region<'tcx> {
707     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
708         folder.try_fold_region(self)
709     }
710 }
711
712 impl<'tcx> TypeVisitable<'tcx> for ty::Region<'tcx> {
713     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
714         visitor.visit_region(*self)
715     }
716 }
717
718 impl<'tcx> TypeSuperFoldable<'tcx> for ty::Region<'tcx> {
719     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
720         self,
721         _folder: &mut F,
722     ) -> Result<Self, F::Error> {
723         Ok(self)
724     }
725 }
726
727 impl<'tcx> TypeSuperVisitable<'tcx> for ty::Region<'tcx> {
728     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> ControlFlow<V::BreakTy> {
729         ControlFlow::CONTINUE
730     }
731 }
732
733 impl<'tcx> TypeFoldable<'tcx> for ty::Predicate<'tcx> {
734     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
735         folder.try_fold_predicate(self)
736     }
737 }
738
739 impl<'tcx> TypeVisitable<'tcx> for ty::Predicate<'tcx> {
740     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
741         visitor.visit_predicate(*self)
742     }
743
744     #[inline]
745     fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool {
746         self.outer_exclusive_binder() > binder
747     }
748
749     #[inline]
750     fn has_type_flags(&self, flags: ty::TypeFlags) -> bool {
751         self.flags().intersects(flags)
752     }
753 }
754
755 impl<'tcx> TypeSuperFoldable<'tcx> for ty::Predicate<'tcx> {
756     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
757         self,
758         folder: &mut F,
759     ) -> Result<Self, F::Error> {
760         let new = self.kind().try_fold_with(folder)?;
761         Ok(folder.tcx().reuse_or_mk_predicate(self, new))
762     }
763 }
764
765 impl<'tcx> TypeSuperVisitable<'tcx> for ty::Predicate<'tcx> {
766     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
767         self.kind().visit_with(visitor)
768     }
769 }
770
771 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<ty::Predicate<'tcx>> {
772     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
773         ty::util::fold_list(self, folder, |tcx, v| tcx.intern_predicates(v))
774     }
775 }
776
777 impl<'tcx, T: TypeFoldable<'tcx>, I: Idx> TypeFoldable<'tcx> for IndexVec<I, T> {
778     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
779         self.try_map_id(|x| x.try_fold_with(folder))
780     }
781 }
782
783 impl<'tcx, T: TypeVisitable<'tcx>, I: Idx> TypeVisitable<'tcx> for IndexVec<I, T> {
784     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
785         self.iter().try_for_each(|t| t.visit_with(visitor))
786     }
787 }
788
789 impl<'tcx> TypeFoldable<'tcx> for ty::Const<'tcx> {
790     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
791         folder.try_fold_const(self)
792     }
793 }
794
795 impl<'tcx> TypeVisitable<'tcx> for ty::Const<'tcx> {
796     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
797         visitor.visit_const(*self)
798     }
799 }
800
801 impl<'tcx> TypeSuperFoldable<'tcx> for ty::Const<'tcx> {
802     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
803         self,
804         folder: &mut F,
805     ) -> Result<Self, F::Error> {
806         let ty = self.ty().try_fold_with(folder)?;
807         let kind = self.kind().try_fold_with(folder)?;
808         if ty != self.ty() || kind != self.kind() {
809             Ok(folder.tcx().mk_const(ty::ConstS { ty, kind }))
810         } else {
811             Ok(self)
812         }
813     }
814 }
815
816 impl<'tcx> TypeSuperVisitable<'tcx> for ty::Const<'tcx> {
817     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
818         self.ty().visit_with(visitor)?;
819         self.kind().visit_with(visitor)
820     }
821 }
822
823 impl<'tcx> TypeFoldable<'tcx> for InferConst<'tcx> {
824     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, _folder: &mut F) -> Result<Self, F::Error> {
825         Ok(self)
826     }
827 }
828
829 impl<'tcx> TypeVisitable<'tcx> for InferConst<'tcx> {
830     fn visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> ControlFlow<V::BreakTy> {
831         ControlFlow::CONTINUE
832     }
833 }
834
835 impl<'tcx> TypeFoldable<'tcx> for ty::UnevaluatedConst<'tcx> {
836     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
837         folder.try_fold_ty_unevaluated(self)
838     }
839 }
840
841 impl<'tcx> TypeVisitable<'tcx> for ty::UnevaluatedConst<'tcx> {
842     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
843         visitor.visit_ty_unevaluated(*self)
844     }
845 }
846
847 impl<'tcx> TypeSuperFoldable<'tcx> for ty::UnevaluatedConst<'tcx> {
848     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
849         self,
850         folder: &mut F,
851     ) -> Result<Self, F::Error> {
852         Ok(ty::UnevaluatedConst { def: self.def, substs: self.substs.try_fold_with(folder)? })
853     }
854 }
855
856 impl<'tcx> TypeSuperVisitable<'tcx> for ty::UnevaluatedConst<'tcx> {
857     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
858         self.substs.visit_with(visitor)
859     }
860 }