]> git.lizzy.rs Git - rust.git/blob - src/librustc_middle/ty/structural_impls.rs
num_counters to u32, after implementing TypeFoldable
[rust.git] / src / librustc_middle / 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::ProjectionKind;
7 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
8 use crate::ty::print::{FmtPrinter, Printer};
9 use crate::ty::{self, InferConst, Lift, Ty, TyCtxt};
10 use rustc_hir as hir;
11 use rustc_hir::def::Namespace;
12 use rustc_hir::def_id::CRATE_DEF_INDEX;
13 use rustc_index::vec::{Idx, IndexVec};
14
15 use smallvec::SmallVec;
16 use std::fmt;
17 use std::rc::Rc;
18 use std::sync::Arc;
19
20 impl fmt::Debug for ty::TraitDef {
21     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22         ty::tls::with(|tcx| {
23             FmtPrinter::new(tcx, f, Namespace::TypeNS).print_def_path(self.def_id, &[])?;
24             Ok(())
25         })
26     }
27 }
28
29 impl fmt::Debug for ty::AdtDef {
30     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31         ty::tls::with(|tcx| {
32             FmtPrinter::new(tcx, f, Namespace::TypeNS).print_def_path(self.did, &[])?;
33             Ok(())
34         })
35     }
36 }
37
38 impl fmt::Debug for ty::UpvarId {
39     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40         let name = ty::tls::with(|tcx| tcx.hir().name(self.var_path.hir_id));
41         write!(f, "UpvarId({:?};`{}`;{:?})", self.var_path.hir_id, name, self.closure_expr_id)
42     }
43 }
44
45 impl fmt::Debug for ty::UpvarBorrow<'tcx> {
46     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47         write!(f, "UpvarBorrow({:?}, {:?})", self.kind, self.region)
48     }
49 }
50
51 impl fmt::Debug for ty::ExistentialTraitRef<'tcx> {
52     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53         fmt::Display::fmt(self, f)
54     }
55 }
56
57 impl fmt::Debug for ty::adjustment::Adjustment<'tcx> {
58     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59         write!(f, "{:?} -> {}", self.kind, self.target)
60     }
61 }
62
63 impl fmt::Debug for ty::BoundRegion {
64     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65         match *self {
66             ty::BrAnon(n) => write!(f, "BrAnon({:?})", n),
67             ty::BrNamed(did, name) => {
68                 if did.index == CRATE_DEF_INDEX {
69                     write!(f, "BrNamed({})", name)
70                 } else {
71                     write!(f, "BrNamed({:?}, {})", did, name)
72                 }
73             }
74             ty::BrEnv => write!(f, "BrEnv"),
75         }
76     }
77 }
78
79 impl fmt::Debug for ty::RegionKind {
80     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81         match *self {
82             ty::ReEarlyBound(ref data) => write!(f, "ReEarlyBound({}, {})", data.index, data.name),
83
84             ty::ReLateBound(binder_id, ref bound_region) => {
85                 write!(f, "ReLateBound({:?}, {:?})", binder_id, bound_region)
86             }
87
88             ty::ReFree(ref fr) => fr.fmt(f),
89
90             ty::ReStatic => write!(f, "ReStatic"),
91
92             ty::ReVar(ref vid) => vid.fmt(f),
93
94             ty::RePlaceholder(placeholder) => write!(f, "RePlaceholder({:?})", placeholder),
95
96             ty::ReEmpty(ui) => write!(f, "ReEmpty({:?})", ui),
97
98             ty::ReErased => write!(f, "ReErased"),
99         }
100     }
101 }
102
103 impl fmt::Debug for ty::FreeRegion {
104     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105         write!(f, "ReFree({:?}, {:?})", self.scope, self.bound_region)
106     }
107 }
108
109 impl fmt::Debug for ty::Variance {
110     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111         f.write_str(match *self {
112             ty::Covariant => "+",
113             ty::Contravariant => "-",
114             ty::Invariant => "o",
115             ty::Bivariant => "*",
116         })
117     }
118 }
119
120 impl fmt::Debug for ty::FnSig<'tcx> {
121     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122         write!(f, "({:?}; c_variadic: {})->{:?}", self.inputs(), self.c_variadic, self.output())
123     }
124 }
125
126 impl fmt::Debug for ty::TyVid {
127     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128         write!(f, "_#{}t", self.index)
129     }
130 }
131
132 impl<'tcx> fmt::Debug for ty::ConstVid<'tcx> {
133     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134         write!(f, "_#{}c", self.index)
135     }
136 }
137
138 impl fmt::Debug for ty::IntVid {
139     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140         write!(f, "_#{}i", self.index)
141     }
142 }
143
144 impl fmt::Debug for ty::FloatVid {
145     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146         write!(f, "_#{}f", self.index)
147     }
148 }
149
150 impl fmt::Debug for ty::RegionVid {
151     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152         write!(f, "'_#{}r", self.index())
153     }
154 }
155
156 impl fmt::Debug for ty::InferTy {
157     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158         match *self {
159             ty::TyVar(ref v) => v.fmt(f),
160             ty::IntVar(ref v) => v.fmt(f),
161             ty::FloatVar(ref v) => v.fmt(f),
162             ty::FreshTy(v) => write!(f, "FreshTy({:?})", v),
163             ty::FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
164             ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({:?})", v),
165         }
166     }
167 }
168
169 impl fmt::Debug for ty::IntVarValue {
170     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171         match *self {
172             ty::IntType(ref v) => v.fmt(f),
173             ty::UintType(ref v) => v.fmt(f),
174         }
175     }
176 }
177
178 impl fmt::Debug for ty::FloatVarValue {
179     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180         self.0.fmt(f)
181     }
182 }
183
184 impl fmt::Debug for ty::TraitRef<'tcx> {
185     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186         fmt::Display::fmt(self, f)
187     }
188 }
189
190 impl fmt::Debug for Ty<'tcx> {
191     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192         fmt::Display::fmt(self, f)
193     }
194 }
195
196 impl fmt::Debug for ty::ParamTy {
197     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198         write!(f, "{}/#{}", self.name, self.index)
199     }
200 }
201
202 impl fmt::Debug for ty::ParamConst {
203     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204         write!(f, "{}/#{}", self.name, self.index)
205     }
206 }
207
208 impl fmt::Debug for ty::TraitPredicate<'tcx> {
209     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210         write!(f, "TraitPredicate({:?})", self.trait_ref)
211     }
212 }
213
214 impl fmt::Debug for ty::ProjectionPredicate<'tcx> {
215     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216         write!(f, "ProjectionPredicate({:?}, {:?})", self.projection_ty, self.ty)
217     }
218 }
219
220 impl fmt::Debug for ty::Predicate<'tcx> {
221     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222         write!(f, "{:?}", self.kind())
223     }
224 }
225
226 impl fmt::Debug for ty::PredicateKind<'tcx> {
227     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228         match *self {
229             ty::PredicateKind::Trait(ref a, constness) => {
230                 if let hir::Constness::Const = constness {
231                     write!(f, "const ")?;
232                 }
233                 a.fmt(f)
234             }
235             ty::PredicateKind::Subtype(ref pair) => pair.fmt(f),
236             ty::PredicateKind::RegionOutlives(ref pair) => pair.fmt(f),
237             ty::PredicateKind::TypeOutlives(ref pair) => pair.fmt(f),
238             ty::PredicateKind::Projection(ref pair) => pair.fmt(f),
239             ty::PredicateKind::WellFormed(data) => write!(f, "WellFormed({:?})", data),
240             ty::PredicateKind::ObjectSafe(trait_def_id) => {
241                 write!(f, "ObjectSafe({:?})", trait_def_id)
242             }
243             ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
244                 write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_substs, kind)
245             }
246             ty::PredicateKind::ConstEvaluatable(def_id, substs) => {
247                 write!(f, "ConstEvaluatable({:?}, {:?})", def_id, substs)
248             }
249             ty::PredicateKind::ConstEquate(c1, c2) => write!(f, "ConstEquate({:?}, {:?})", c1, c2),
250         }
251     }
252 }
253
254 ///////////////////////////////////////////////////////////////////////////
255 // Atomic structs
256 //
257 // For things that don't carry any arena-allocated data (and are
258 // copy...), just add them to this list.
259
260 CloneTypeFoldableAndLiftImpls! {
261     (),
262     bool,
263     usize,
264     ::rustc_target::abi::VariantIdx,
265     u32,
266     u64,
267     String,
268     crate::middle::region::Scope,
269     ::rustc_ast::ast::FloatTy,
270     ::rustc_ast::ast::InlineAsmOptions,
271     ::rustc_ast::ast::InlineAsmTemplatePiece,
272     ::rustc_ast::ast::NodeId,
273     ::rustc_span::symbol::Symbol,
274     ::rustc_hir::def::Res,
275     ::rustc_hir::def_id::DefId,
276     ::rustc_hir::LlvmInlineAsmInner,
277     ::rustc_hir::MatchSource,
278     ::rustc_hir::Mutability,
279     ::rustc_hir::Unsafety,
280     ::rustc_target::asm::InlineAsmRegOrRegClass,
281     ::rustc_target::spec::abi::Abi,
282     crate::mir::Local,
283     crate::mir::Promoted,
284     crate::traits::Reveal,
285     crate::ty::adjustment::AutoBorrowMutability,
286     crate::ty::AdtKind,
287     // Including `BoundRegion` is a *bit* dubious, but direct
288     // references to bound region appear in `ty::Error`, and aren't
289     // really meant to be folded. In general, we can only fold a fully
290     // general `Region`.
291     crate::ty::BoundRegion,
292     crate::ty::Placeholder<crate::ty::BoundRegion>,
293     crate::ty::ClosureKind,
294     crate::ty::FreeRegion,
295     crate::ty::InferTy,
296     crate::ty::IntVarValue,
297     crate::ty::ParamConst,
298     crate::ty::ParamTy,
299     crate::ty::adjustment::PointerCast,
300     crate::ty::RegionVid,
301     crate::ty::UniverseIndex,
302     crate::ty::Variance,
303     ::rustc_span::Span,
304 }
305
306 ///////////////////////////////////////////////////////////////////////////
307 // Lift implementations
308
309 // FIXME(eddyb) replace all the uses of `Option::map` with `?`.
310 impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>> Lift<'tcx> for (A, B) {
311     type Lifted = (A::Lifted, B::Lifted);
312     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
313         tcx.lift(&self.0).and_then(|a| tcx.lift(&self.1).map(|b| (a, b)))
314     }
315 }
316
317 impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>, C: Lift<'tcx>> Lift<'tcx> for (A, B, C) {
318     type Lifted = (A::Lifted, B::Lifted, C::Lifted);
319     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
320         tcx.lift(&self.0)
321             .and_then(|a| tcx.lift(&self.1).and_then(|b| tcx.lift(&self.2).map(|c| (a, b, c))))
322     }
323 }
324
325 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Option<T> {
326     type Lifted = Option<T::Lifted>;
327     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
328         match *self {
329             Some(ref x) => tcx.lift(x).map(Some),
330             None => Some(None),
331         }
332     }
333 }
334
335 impl<'tcx, T: Lift<'tcx>, E: Lift<'tcx>> Lift<'tcx> for Result<T, E> {
336     type Lifted = Result<T::Lifted, E::Lifted>;
337     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
338         match *self {
339             Ok(ref x) => tcx.lift(x).map(Ok),
340             Err(ref e) => tcx.lift(e).map(Err),
341         }
342     }
343 }
344
345 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Box<T> {
346     type Lifted = Box<T::Lifted>;
347     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
348         tcx.lift(&**self).map(Box::new)
349     }
350 }
351
352 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Rc<T> {
353     type Lifted = Rc<T::Lifted>;
354     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
355         tcx.lift(&**self).map(Rc::new)
356     }
357 }
358
359 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Arc<T> {
360     type Lifted = Arc<T::Lifted>;
361     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
362         tcx.lift(&**self).map(Arc::new)
363     }
364 }
365
366 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for [T] {
367     type Lifted = Vec<T::Lifted>;
368     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
369         // type annotation needed to inform `projection_must_outlive`
370         let mut result: Vec<<T as Lift<'tcx>>::Lifted> = Vec::with_capacity(self.len());
371         for x in self {
372             if let Some(value) = tcx.lift(x) {
373                 result.push(value);
374             } else {
375                 return None;
376             }
377         }
378         Some(result)
379     }
380 }
381
382 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Vec<T> {
383     type Lifted = Vec<T::Lifted>;
384     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
385         tcx.lift(&self[..])
386     }
387 }
388
389 impl<'tcx, I: Idx, T: Lift<'tcx>> Lift<'tcx> for IndexVec<I, T> {
390     type Lifted = IndexVec<I, T::Lifted>;
391     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
392         self.iter().map(|e| tcx.lift(e)).collect()
393     }
394 }
395
396 impl<'a, 'tcx> Lift<'tcx> for ty::TraitRef<'a> {
397     type Lifted = ty::TraitRef<'tcx>;
398     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
399         tcx.lift(&self.substs).map(|substs| ty::TraitRef { def_id: self.def_id, substs })
400     }
401 }
402
403 impl<'a, 'tcx> Lift<'tcx> for ty::ExistentialTraitRef<'a> {
404     type Lifted = ty::ExistentialTraitRef<'tcx>;
405     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
406         tcx.lift(&self.substs).map(|substs| ty::ExistentialTraitRef { def_id: self.def_id, substs })
407     }
408 }
409
410 impl<'a, 'tcx> Lift<'tcx> for ty::ExistentialPredicate<'a> {
411     type Lifted = ty::ExistentialPredicate<'tcx>;
412     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
413         match self {
414             ty::ExistentialPredicate::Trait(x) => tcx.lift(x).map(ty::ExistentialPredicate::Trait),
415             ty::ExistentialPredicate::Projection(x) => {
416                 tcx.lift(x).map(ty::ExistentialPredicate::Projection)
417             }
418             ty::ExistentialPredicate::AutoTrait(def_id) => {
419                 Some(ty::ExistentialPredicate::AutoTrait(*def_id))
420             }
421         }
422     }
423 }
424
425 impl<'a, 'tcx> Lift<'tcx> for ty::TraitPredicate<'a> {
426     type Lifted = ty::TraitPredicate<'tcx>;
427     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<ty::TraitPredicate<'tcx>> {
428         tcx.lift(&self.trait_ref).map(|trait_ref| ty::TraitPredicate { trait_ref })
429     }
430 }
431
432 impl<'a, 'tcx> Lift<'tcx> for ty::SubtypePredicate<'a> {
433     type Lifted = ty::SubtypePredicate<'tcx>;
434     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<ty::SubtypePredicate<'tcx>> {
435         tcx.lift(&(self.a, self.b)).map(|(a, b)| ty::SubtypePredicate {
436             a_is_expected: self.a_is_expected,
437             a,
438             b,
439         })
440     }
441 }
442
443 impl<'tcx, A: Copy + Lift<'tcx>, B: Copy + Lift<'tcx>> Lift<'tcx> for ty::OutlivesPredicate<A, B> {
444     type Lifted = ty::OutlivesPredicate<A::Lifted, B::Lifted>;
445     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
446         tcx.lift(&(self.0, self.1)).map(|(a, b)| ty::OutlivesPredicate(a, b))
447     }
448 }
449
450 impl<'a, 'tcx> Lift<'tcx> for ty::ProjectionTy<'a> {
451     type Lifted = ty::ProjectionTy<'tcx>;
452     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<ty::ProjectionTy<'tcx>> {
453         tcx.lift(&self.substs)
454             .map(|substs| ty::ProjectionTy { item_def_id: self.item_def_id, substs })
455     }
456 }
457
458 impl<'a, 'tcx> Lift<'tcx> for ty::ProjectionPredicate<'a> {
459     type Lifted = ty::ProjectionPredicate<'tcx>;
460     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<ty::ProjectionPredicate<'tcx>> {
461         tcx.lift(&(self.projection_ty, self.ty))
462             .map(|(projection_ty, ty)| ty::ProjectionPredicate { projection_ty, ty })
463     }
464 }
465
466 impl<'a, 'tcx> Lift<'tcx> for ty::ExistentialProjection<'a> {
467     type Lifted = ty::ExistentialProjection<'tcx>;
468     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
469         tcx.lift(&self.substs).map(|substs| ty::ExistentialProjection {
470             substs,
471             ty: tcx.lift(&self.ty).expect("type must lift when substs do"),
472             item_def_id: self.item_def_id,
473         })
474     }
475 }
476
477 impl<'a, 'tcx> Lift<'tcx> for ty::PredicateKind<'a> {
478     type Lifted = ty::PredicateKind<'tcx>;
479     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
480         match *self {
481             ty::PredicateKind::Trait(ref binder, constness) => {
482                 tcx.lift(binder).map(|binder| ty::PredicateKind::Trait(binder, constness))
483             }
484             ty::PredicateKind::Subtype(ref binder) => {
485                 tcx.lift(binder).map(ty::PredicateKind::Subtype)
486             }
487             ty::PredicateKind::RegionOutlives(ref binder) => {
488                 tcx.lift(binder).map(ty::PredicateKind::RegionOutlives)
489             }
490             ty::PredicateKind::TypeOutlives(ref binder) => {
491                 tcx.lift(binder).map(ty::PredicateKind::TypeOutlives)
492             }
493             ty::PredicateKind::Projection(ref binder) => {
494                 tcx.lift(binder).map(ty::PredicateKind::Projection)
495             }
496             ty::PredicateKind::WellFormed(ty) => tcx.lift(&ty).map(ty::PredicateKind::WellFormed),
497             ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
498                 tcx.lift(&closure_substs).map(|closure_substs| {
499                     ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind)
500                 })
501             }
502             ty::PredicateKind::ObjectSafe(trait_def_id) => {
503                 Some(ty::PredicateKind::ObjectSafe(trait_def_id))
504             }
505             ty::PredicateKind::ConstEvaluatable(def_id, substs) => {
506                 tcx.lift(&substs).map(|substs| ty::PredicateKind::ConstEvaluatable(def_id, substs))
507             }
508             ty::PredicateKind::ConstEquate(c1, c2) => {
509                 tcx.lift(&(c1, c2)).map(|(c1, c2)| ty::PredicateKind::ConstEquate(c1, c2))
510             }
511         }
512     }
513 }
514
515 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for ty::Binder<T> {
516     type Lifted = ty::Binder<T::Lifted>;
517     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
518         tcx.lift(self.skip_binder()).map(ty::Binder::bind)
519     }
520 }
521
522 impl<'a, 'tcx> Lift<'tcx> for ty::ParamEnv<'a> {
523     type Lifted = ty::ParamEnv<'tcx>;
524     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
525         tcx.lift(&self.caller_bounds).map(|caller_bounds| ty::ParamEnv {
526             reveal: self.reveal,
527             caller_bounds,
528             def_id: self.def_id,
529         })
530     }
531 }
532
533 impl<'a, 'tcx, T: Lift<'tcx>> Lift<'tcx> for ty::ParamEnvAnd<'a, T> {
534     type Lifted = ty::ParamEnvAnd<'tcx, T::Lifted>;
535     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
536         tcx.lift(&self.param_env).and_then(|param_env| {
537             tcx.lift(&self.value).map(|value| ty::ParamEnvAnd { param_env, value })
538         })
539     }
540 }
541
542 impl<'a, 'tcx> Lift<'tcx> for ty::ClosureSubsts<'a> {
543     type Lifted = ty::ClosureSubsts<'tcx>;
544     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
545         tcx.lift(&self.substs).map(|substs| ty::ClosureSubsts { substs })
546     }
547 }
548
549 impl<'a, 'tcx> Lift<'tcx> for ty::GeneratorSubsts<'a> {
550     type Lifted = ty::GeneratorSubsts<'tcx>;
551     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
552         tcx.lift(&self.substs).map(|substs| ty::GeneratorSubsts { substs })
553     }
554 }
555
556 impl<'a, 'tcx> Lift<'tcx> for ty::adjustment::Adjustment<'a> {
557     type Lifted = ty::adjustment::Adjustment<'tcx>;
558     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
559         tcx.lift(&self.kind).and_then(|kind| {
560             tcx.lift(&self.target).map(|target| ty::adjustment::Adjustment { kind, target })
561         })
562     }
563 }
564
565 impl<'a, 'tcx> Lift<'tcx> for ty::adjustment::Adjust<'a> {
566     type Lifted = ty::adjustment::Adjust<'tcx>;
567     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
568         match *self {
569             ty::adjustment::Adjust::NeverToAny => Some(ty::adjustment::Adjust::NeverToAny),
570             ty::adjustment::Adjust::Pointer(ptr) => Some(ty::adjustment::Adjust::Pointer(ptr)),
571             ty::adjustment::Adjust::Deref(ref overloaded) => {
572                 tcx.lift(overloaded).map(ty::adjustment::Adjust::Deref)
573             }
574             ty::adjustment::Adjust::Borrow(ref autoref) => {
575                 tcx.lift(autoref).map(ty::adjustment::Adjust::Borrow)
576             }
577         }
578     }
579 }
580
581 impl<'a, 'tcx> Lift<'tcx> for ty::adjustment::OverloadedDeref<'a> {
582     type Lifted = ty::adjustment::OverloadedDeref<'tcx>;
583     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
584         tcx.lift(&self.region)
585             .map(|region| ty::adjustment::OverloadedDeref { region, mutbl: self.mutbl })
586     }
587 }
588
589 impl<'a, 'tcx> Lift<'tcx> for ty::adjustment::AutoBorrow<'a> {
590     type Lifted = ty::adjustment::AutoBorrow<'tcx>;
591     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
592         match *self {
593             ty::adjustment::AutoBorrow::Ref(r, m) => {
594                 tcx.lift(&r).map(|r| ty::adjustment::AutoBorrow::Ref(r, m))
595             }
596             ty::adjustment::AutoBorrow::RawPtr(m) => Some(ty::adjustment::AutoBorrow::RawPtr(m)),
597         }
598     }
599 }
600
601 impl<'a, 'tcx> Lift<'tcx> for ty::GenSig<'a> {
602     type Lifted = ty::GenSig<'tcx>;
603     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
604         tcx.lift(&(self.resume_ty, self.yield_ty, self.return_ty))
605             .map(|(resume_ty, yield_ty, return_ty)| ty::GenSig { resume_ty, yield_ty, return_ty })
606     }
607 }
608
609 impl<'a, 'tcx> Lift<'tcx> for ty::FnSig<'a> {
610     type Lifted = ty::FnSig<'tcx>;
611     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
612         tcx.lift(&self.inputs_and_output).map(|x| ty::FnSig {
613             inputs_and_output: x,
614             c_variadic: self.c_variadic,
615             unsafety: self.unsafety,
616             abi: self.abi,
617         })
618     }
619 }
620
621 impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for ty::error::ExpectedFound<T> {
622     type Lifted = ty::error::ExpectedFound<T::Lifted>;
623     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
624         tcx.lift(&self.expected).and_then(|expected| {
625             tcx.lift(&self.found).map(|found| ty::error::ExpectedFound { expected, found })
626         })
627     }
628 }
629
630 impl<'a, 'tcx> Lift<'tcx> for ty::error::TypeError<'a> {
631     type Lifted = ty::error::TypeError<'tcx>;
632     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
633         use crate::ty::error::TypeError::*;
634
635         Some(match *self {
636             Mismatch => Mismatch,
637             UnsafetyMismatch(x) => UnsafetyMismatch(x),
638             AbiMismatch(x) => AbiMismatch(x),
639             Mutability => Mutability,
640             TupleSize(x) => TupleSize(x),
641             FixedArraySize(x) => FixedArraySize(x),
642             ArgCount => ArgCount,
643             RegionsDoesNotOutlive(a, b) => {
644                 return tcx.lift(&(a, b)).map(|(a, b)| RegionsDoesNotOutlive(a, b));
645             }
646             RegionsInsufficientlyPolymorphic(a, b) => {
647                 return tcx.lift(&b).map(|b| RegionsInsufficientlyPolymorphic(a, b));
648             }
649             RegionsOverlyPolymorphic(a, b) => {
650                 return tcx.lift(&b).map(|b| RegionsOverlyPolymorphic(a, b));
651             }
652             RegionsPlaceholderMismatch => RegionsPlaceholderMismatch,
653             IntMismatch(x) => IntMismatch(x),
654             FloatMismatch(x) => FloatMismatch(x),
655             Traits(x) => Traits(x),
656             VariadicMismatch(x) => VariadicMismatch(x),
657             CyclicTy(t) => return tcx.lift(&t).map(|t| CyclicTy(t)),
658             ProjectionMismatched(x) => ProjectionMismatched(x),
659             ProjectionBoundsLength(x) => ProjectionBoundsLength(x),
660             Sorts(ref x) => return tcx.lift(x).map(Sorts),
661             ExistentialMismatch(ref x) => return tcx.lift(x).map(ExistentialMismatch),
662             ConstMismatch(ref x) => return tcx.lift(x).map(ConstMismatch),
663             IntrinsicCast => IntrinsicCast,
664             TargetFeatureCast(ref x) => TargetFeatureCast(*x),
665             ObjectUnsafeCoercion(ref x) => return tcx.lift(x).map(ObjectUnsafeCoercion),
666         })
667     }
668 }
669
670 impl<'a, 'tcx> Lift<'tcx> for ty::InstanceDef<'a> {
671     type Lifted = ty::InstanceDef<'tcx>;
672     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
673         match *self {
674             ty::InstanceDef::Item(def_id) => Some(ty::InstanceDef::Item(def_id)),
675             ty::InstanceDef::VtableShim(def_id) => Some(ty::InstanceDef::VtableShim(def_id)),
676             ty::InstanceDef::ReifyShim(def_id) => Some(ty::InstanceDef::ReifyShim(def_id)),
677             ty::InstanceDef::Intrinsic(def_id) => Some(ty::InstanceDef::Intrinsic(def_id)),
678             ty::InstanceDef::FnPtrShim(def_id, ref ty) => {
679                 Some(ty::InstanceDef::FnPtrShim(def_id, tcx.lift(ty)?))
680             }
681             ty::InstanceDef::Virtual(def_id, n) => Some(ty::InstanceDef::Virtual(def_id, n)),
682             ty::InstanceDef::ClosureOnceShim { call_once } => {
683                 Some(ty::InstanceDef::ClosureOnceShim { call_once })
684             }
685             ty::InstanceDef::DropGlue(def_id, ref ty) => {
686                 Some(ty::InstanceDef::DropGlue(def_id, tcx.lift(ty)?))
687             }
688             ty::InstanceDef::CloneShim(def_id, ref ty) => {
689                 Some(ty::InstanceDef::CloneShim(def_id, tcx.lift(ty)?))
690             }
691         }
692     }
693 }
694
695 ///////////////////////////////////////////////////////////////////////////
696 // TypeFoldable implementations.
697 //
698 // Ideally, each type should invoke `folder.fold_foo(self)` and
699 // nothing else. In some cases, though, we haven't gotten around to
700 // adding methods on the `folder` yet, and thus the folding is
701 // hard-coded here. This is less-flexible, because folders cannot
702 // override the behavior, but there are a lot of random types and one
703 // can easily refactor the folding into the TypeFolder trait as
704 // needed.
705
706 /// AdtDefs are basically the same as a DefId.
707 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::AdtDef {
708     fn super_fold_with<F: TypeFolder<'tcx>>(&self, _folder: &mut F) -> Self {
709         *self
710     }
711
712     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> bool {
713         false
714     }
715 }
716
717 impl<'tcx, T: TypeFoldable<'tcx>, U: TypeFoldable<'tcx>> TypeFoldable<'tcx> for (T, U) {
718     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> (T, U) {
719         (self.0.fold_with(folder), self.1.fold_with(folder))
720     }
721
722     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
723         self.0.visit_with(visitor) || self.1.visit_with(visitor)
724     }
725 }
726
727 EnumTypeFoldableImpl! {
728     impl<'tcx, T> TypeFoldable<'tcx> for Option<T> {
729         (Some)(a),
730         (None),
731     } where T: TypeFoldable<'tcx>
732 }
733
734 EnumTypeFoldableImpl! {
735     impl<'tcx, T, E> TypeFoldable<'tcx> for Result<T, E> {
736         (Ok)(a),
737         (Err)(a),
738     } where T: TypeFoldable<'tcx>, E: TypeFoldable<'tcx>,
739 }
740
741 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Rc<T> {
742     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
743         Rc::new((**self).fold_with(folder))
744     }
745
746     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
747         (**self).visit_with(visitor)
748     }
749 }
750
751 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Arc<T> {
752     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
753         Arc::new((**self).fold_with(folder))
754     }
755
756     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
757         (**self).visit_with(visitor)
758     }
759 }
760
761 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Box<T> {
762     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
763         let content: T = (**self).fold_with(folder);
764         box content
765     }
766
767     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
768         (**self).visit_with(visitor)
769     }
770 }
771
772 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Vec<T> {
773     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
774         self.iter().map(|t| t.fold_with(folder)).collect()
775     }
776
777     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
778         self.iter().any(|t| t.visit_with(visitor))
779     }
780 }
781
782 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Box<[T]> {
783     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
784         self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>().into_boxed_slice()
785     }
786
787     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
788         self.iter().any(|t| t.visit_with(visitor))
789     }
790 }
791
792 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for ty::Binder<T> {
793     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
794         self.map_bound_ref(|ty| ty.fold_with(folder))
795     }
796
797     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
798         folder.fold_binder(self)
799     }
800
801     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
802         self.skip_binder().visit_with(visitor)
803     }
804
805     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
806         visitor.visit_binder(self)
807     }
808 }
809
810 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<ty::ExistentialPredicate<'tcx>> {
811     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
812         fold_list(*self, folder, |tcx, v| tcx.intern_existential_predicates(v))
813     }
814
815     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
816         self.iter().any(|p| p.visit_with(visitor))
817     }
818 }
819
820 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<Ty<'tcx>> {
821     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
822         fold_list(*self, folder, |tcx, v| tcx.intern_type_list(v))
823     }
824
825     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
826         self.iter().any(|t| t.visit_with(visitor))
827     }
828 }
829
830 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<ProjectionKind> {
831     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
832         fold_list(*self, folder, |tcx, v| tcx.intern_projs(v))
833     }
834
835     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
836         self.iter().any(|t| t.visit_with(visitor))
837     }
838 }
839
840 impl<'tcx> TypeFoldable<'tcx> for ty::instance::Instance<'tcx> {
841     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
842         use crate::ty::InstanceDef::*;
843         Self {
844             substs: self.substs.fold_with(folder),
845             def: match self.def {
846                 Item(did) => Item(did.fold_with(folder)),
847                 VtableShim(did) => VtableShim(did.fold_with(folder)),
848                 ReifyShim(did) => ReifyShim(did.fold_with(folder)),
849                 Intrinsic(did) => Intrinsic(did.fold_with(folder)),
850                 FnPtrShim(did, ty) => FnPtrShim(did.fold_with(folder), ty.fold_with(folder)),
851                 Virtual(did, i) => Virtual(did.fold_with(folder), i),
852                 ClosureOnceShim { call_once } => {
853                     ClosureOnceShim { call_once: call_once.fold_with(folder) }
854                 }
855                 DropGlue(did, ty) => DropGlue(did.fold_with(folder), ty.fold_with(folder)),
856                 CloneShim(did, ty) => CloneShim(did.fold_with(folder), ty.fold_with(folder)),
857             },
858         }
859     }
860
861     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
862         use crate::ty::InstanceDef::*;
863         self.substs.visit_with(visitor)
864             || match self.def {
865                 Item(did) | VtableShim(did) | ReifyShim(did) | Intrinsic(did) | Virtual(did, _) => {
866                     did.visit_with(visitor)
867                 }
868                 FnPtrShim(did, ty) | CloneShim(did, ty) => {
869                     did.visit_with(visitor) || ty.visit_with(visitor)
870                 }
871                 DropGlue(did, ty) => did.visit_with(visitor) || ty.visit_with(visitor),
872                 ClosureOnceShim { call_once } => call_once.visit_with(visitor),
873             }
874     }
875 }
876
877 impl<'tcx> TypeFoldable<'tcx> for interpret::GlobalId<'tcx> {
878     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
879         Self { instance: self.instance.fold_with(folder), promoted: self.promoted }
880     }
881
882     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
883         self.instance.visit_with(visitor)
884     }
885 }
886
887 impl<'tcx> TypeFoldable<'tcx> for Ty<'tcx> {
888     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
889         let kind = match self.kind {
890             ty::RawPtr(tm) => ty::RawPtr(tm.fold_with(folder)),
891             ty::Array(typ, sz) => ty::Array(typ.fold_with(folder), sz.fold_with(folder)),
892             ty::Slice(typ) => ty::Slice(typ.fold_with(folder)),
893             ty::Adt(tid, substs) => ty::Adt(tid, substs.fold_with(folder)),
894             ty::Dynamic(ref trait_ty, ref region) => {
895                 ty::Dynamic(trait_ty.fold_with(folder), region.fold_with(folder))
896             }
897             ty::Tuple(ts) => ty::Tuple(ts.fold_with(folder)),
898             ty::FnDef(def_id, substs) => ty::FnDef(def_id, substs.fold_with(folder)),
899             ty::FnPtr(f) => ty::FnPtr(f.fold_with(folder)),
900             ty::Ref(ref r, ty, mutbl) => ty::Ref(r.fold_with(folder), ty.fold_with(folder), mutbl),
901             ty::Generator(did, substs, movability) => {
902                 ty::Generator(did, substs.fold_with(folder), movability)
903             }
904             ty::GeneratorWitness(types) => ty::GeneratorWitness(types.fold_with(folder)),
905             ty::Closure(did, substs) => ty::Closure(did, substs.fold_with(folder)),
906             ty::Projection(ref data) => ty::Projection(data.fold_with(folder)),
907             ty::Opaque(did, substs) => ty::Opaque(did, substs.fold_with(folder)),
908
909             ty::Bool
910             | ty::Char
911             | ty::Str
912             | ty::Int(_)
913             | ty::Uint(_)
914             | ty::Float(_)
915             | ty::Error(_)
916             | ty::Infer(_)
917             | ty::Param(..)
918             | ty::Bound(..)
919             | ty::Placeholder(..)
920             | ty::Never
921             | ty::Foreign(..) => return self,
922         };
923
924         if self.kind == kind { self } else { folder.tcx().mk_ty(kind) }
925     }
926
927     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
928         folder.fold_ty(*self)
929     }
930
931     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
932         match self.kind {
933             ty::RawPtr(ref tm) => tm.visit_with(visitor),
934             ty::Array(typ, sz) => typ.visit_with(visitor) || sz.visit_with(visitor),
935             ty::Slice(typ) => typ.visit_with(visitor),
936             ty::Adt(_, substs) => substs.visit_with(visitor),
937             ty::Dynamic(ref trait_ty, ref reg) => {
938                 trait_ty.visit_with(visitor) || reg.visit_with(visitor)
939             }
940             ty::Tuple(ts) => ts.visit_with(visitor),
941             ty::FnDef(_, substs) => substs.visit_with(visitor),
942             ty::FnPtr(ref f) => f.visit_with(visitor),
943             ty::Ref(r, ty, _) => r.visit_with(visitor) || ty.visit_with(visitor),
944             ty::Generator(_did, ref substs, _) => substs.visit_with(visitor),
945             ty::GeneratorWitness(ref types) => types.visit_with(visitor),
946             ty::Closure(_did, ref substs) => substs.visit_with(visitor),
947             ty::Projection(ref data) => data.visit_with(visitor),
948             ty::Opaque(_, ref substs) => substs.visit_with(visitor),
949
950             ty::Bool
951             | ty::Char
952             | ty::Str
953             | ty::Int(_)
954             | ty::Uint(_)
955             | ty::Float(_)
956             | ty::Error(_)
957             | ty::Infer(_)
958             | ty::Bound(..)
959             | ty::Placeholder(..)
960             | ty::Param(..)
961             | ty::Never
962             | ty::Foreign(..) => false,
963         }
964     }
965
966     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
967         visitor.visit_ty(self)
968     }
969 }
970
971 impl<'tcx> TypeFoldable<'tcx> for ty::Region<'tcx> {
972     fn super_fold_with<F: TypeFolder<'tcx>>(&self, _folder: &mut F) -> Self {
973         *self
974     }
975
976     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
977         folder.fold_region(*self)
978     }
979
980     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> bool {
981         false
982     }
983
984     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
985         visitor.visit_region(*self)
986     }
987 }
988
989 impl<'tcx> TypeFoldable<'tcx> for ty::Predicate<'tcx> {
990     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
991         let new = ty::PredicateKind::super_fold_with(self.kind, folder);
992         if new != *self.kind { folder.tcx().mk_predicate(new) } else { *self }
993     }
994
995     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
996         ty::PredicateKind::super_visit_with(self.kind, visitor)
997     }
998 }
999
1000 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<ty::Predicate<'tcx>> {
1001     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
1002         fold_list(*self, folder, |tcx, v| tcx.intern_predicates(v))
1003     }
1004
1005     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1006         self.iter().any(|p| p.visit_with(visitor))
1007     }
1008 }
1009
1010 impl<'tcx, T: TypeFoldable<'tcx>, I: Idx> TypeFoldable<'tcx> for IndexVec<I, T> {
1011     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
1012         self.iter().map(|x| x.fold_with(folder)).collect()
1013     }
1014
1015     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1016         self.iter().any(|t| t.visit_with(visitor))
1017     }
1018 }
1019
1020 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::Const<'tcx> {
1021     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
1022         let ty = self.ty.fold_with(folder);
1023         let val = self.val.fold_with(folder);
1024         if ty != self.ty || val != self.val {
1025             folder.tcx().mk_const(ty::Const { ty, val })
1026         } else {
1027             *self
1028         }
1029     }
1030
1031     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
1032         folder.fold_const(*self)
1033     }
1034
1035     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1036         self.ty.visit_with(visitor) || self.val.visit_with(visitor)
1037     }
1038
1039     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1040         visitor.visit_const(self)
1041     }
1042 }
1043
1044 impl<'tcx> TypeFoldable<'tcx> for ty::ConstKind<'tcx> {
1045     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
1046         match *self {
1047             ty::ConstKind::Infer(ic) => ty::ConstKind::Infer(ic.fold_with(folder)),
1048             ty::ConstKind::Param(p) => ty::ConstKind::Param(p.fold_with(folder)),
1049             ty::ConstKind::Unevaluated(did, substs, promoted) => {
1050                 ty::ConstKind::Unevaluated(did, substs.fold_with(folder), promoted)
1051             }
1052             ty::ConstKind::Value(_)
1053             | ty::ConstKind::Bound(..)
1054             | ty::ConstKind::Placeholder(..)
1055             | ty::ConstKind::Error(_) => *self,
1056         }
1057     }
1058
1059     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1060         match *self {
1061             ty::ConstKind::Infer(ic) => ic.visit_with(visitor),
1062             ty::ConstKind::Param(p) => p.visit_with(visitor),
1063             ty::ConstKind::Unevaluated(_, substs, _) => substs.visit_with(visitor),
1064             ty::ConstKind::Value(_)
1065             | ty::ConstKind::Bound(..)
1066             | ty::ConstKind::Placeholder(_)
1067             | ty::ConstKind::Error(_) => false,
1068         }
1069     }
1070 }
1071
1072 impl<'tcx> TypeFoldable<'tcx> for InferConst<'tcx> {
1073     fn super_fold_with<F: TypeFolder<'tcx>>(&self, _folder: &mut F) -> Self {
1074         *self
1075     }
1076
1077     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _visitor: &mut V) -> bool {
1078         false
1079     }
1080 }
1081
1082 // Does the equivalent of
1083 // ```
1084 // let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1085 // folder.tcx().intern_*(&v)
1086 // ```
1087 fn fold_list<'tcx, F, T>(
1088     list: &'tcx ty::List<T>,
1089     folder: &mut F,
1090     intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> &'tcx ty::List<T>,
1091 ) -> &'tcx ty::List<T>
1092 where
1093     F: TypeFolder<'tcx>,
1094     T: TypeFoldable<'tcx> + PartialEq + Copy,
1095 {
1096     let mut iter = list.iter();
1097     // Look for the first element that changed
1098     if let Some((i, new_t)) = iter.by_ref().enumerate().find_map(|(i, t)| {
1099         let new_t = t.fold_with(folder);
1100         if new_t == t { None } else { Some((i, new_t)) }
1101     }) {
1102         // An element changed, prepare to intern the resulting list
1103         let mut new_list = SmallVec::<[_; 8]>::with_capacity(list.len());
1104         new_list.extend_from_slice(&list[..i]);
1105         new_list.push(new_t);
1106         new_list.extend(iter.map(|t| t.fold_with(folder)));
1107         intern(folder.tcx(), &new_list)
1108     } else {
1109         list
1110     }
1111 }