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