1 //! Generalized type folding mechanism. The setup is a bit convoluted
2 //! but allows for convenient usage. Let T be an instance of some
3 //! "foldable type" (one which implements `TypeFoldable`) and F be an
4 //! instance of a "folder" (a type which implements `TypeFolder`). Then
5 //! the setup is intended to be:
7 //! T.fold_with(F) --calls--> F.fold_T(T) --calls--> T.super_fold_with(F)
9 //! This way, when you define a new folder F, you can override
10 //! `fold_T()` to customize the behavior, and invoke `T.super_fold_with()`
11 //! to get the original behavior. Meanwhile, to actually fold
12 //! something, you can just write `T.fold_with(F)`, which is
13 //! convenient. (Note that `fold_with` will also transparently handle
14 //! things like a `Vec<T>` where T is foldable and so on.)
16 //! In this ideal setup, the only function that actually *does*
17 //! anything is `T.super_fold_with()`, which traverses the type `T`.
18 //! Moreover, `T.super_fold_with()` should only ever call `T.fold_with()`.
20 //! In some cases, we follow a degenerate pattern where we do not have
21 //! a `fold_T` method. Instead, `T.fold_with` traverses the structure directly.
22 //! This is suboptimal because the behavior cannot be overridden, but it's
23 //! much less work to implement. If you ever *do* need an override that
24 //! doesn't exist, it's not hard to convert the degenerate pattern into the
27 //! A `TypeFoldable` T can also be visited by a `TypeVisitor` V using similar setup:
29 //! T.visit_with(V) --calls--> V.visit_T(T) --calls--> T.super_visit_with(V).
31 //! These methods return true to indicate that the visitor has found what it is
32 //! looking for, and does not need to visit anything else.
34 use crate::ty::{self, flags::FlagComputation, Binder, Ty, TyCtxt, TypeFlags};
36 use rustc_hir::def_id::DefId;
38 use rustc_data_structures::fx::FxHashSet;
39 use rustc_data_structures::sso::SsoHashSet;
40 use std::collections::BTreeMap;
42 use std::ops::ControlFlow;
44 /// This trait is implemented for every type that can be folded.
45 /// Basically, every type that has a corresponding method in `TypeFolder`.
47 /// To implement this conveniently, use the derive macro located in `rustc_macros`.
48 pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
49 /// Consumers may find this more convenient to use with infallible folders than
50 /// [`try_super_fold_with`][`TypeFoldable::try_super_fold_with`], to which the
51 /// provided default definition delegates. Implementors **should not** override
52 /// this provided default definition, to ensure that the two methods are coherent
53 /// (provide a definition of `try_super_fold_with` instead).
54 fn super_fold_with<F: TypeFolder<'tcx, Error = !>>(self, folder: &mut F) -> Self {
55 self.try_super_fold_with(folder).into_ok()
57 /// Consumers may find this more convenient to use with infallible folders than
58 /// [`try_fold_with`][`TypeFoldable::try_fold_with`], to which the provided
59 /// default definition delegates. Implementors **should not** override this
60 /// provided default definition, to ensure that the two methods are coherent
61 /// (provide a definition of `try_fold_with` instead).
62 fn fold_with<F: TypeFolder<'tcx, Error = !>>(self, folder: &mut F) -> Self {
63 self.try_fold_with(folder).into_ok()
66 fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
69 ) -> Result<Self, F::Error>;
71 fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
72 self.try_super_fold_with(folder)
75 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy>;
76 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
77 self.super_visit_with(visitor)
80 /// Returns `true` if `self` has any late-bound regions that are either
81 /// bound by `binder` or bound by some binder outside of `binder`.
82 /// If `binder` is `ty::INNERMOST`, this indicates whether
83 /// there are any late-bound regions that appear free.
84 fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool {
85 self.visit_with(&mut HasEscapingVarsVisitor { outer_index: binder }).is_break()
88 /// Returns `true` if this `self` has any regions that escape `binder` (and
89 /// hence are not bound by it).
90 fn has_vars_bound_above(&self, binder: ty::DebruijnIndex) -> bool {
91 self.has_vars_bound_at_or_above(binder.shifted_in(1))
94 fn has_escaping_bound_vars(&self) -> bool {
95 self.has_vars_bound_at_or_above(ty::INNERMOST)
98 fn definitely_has_type_flags(&self, tcx: TyCtxt<'tcx>, flags: TypeFlags) -> bool {
99 self.visit_with(&mut HasTypeFlagsVisitor { tcx: Some(tcx), flags }).break_value()
103 #[instrument(level = "trace")]
104 fn has_type_flags(&self, flags: TypeFlags) -> bool {
105 self.visit_with(&mut HasTypeFlagsVisitor { tcx: None, flags }).break_value()
108 fn has_projections(&self) -> bool {
109 self.has_type_flags(TypeFlags::HAS_PROJECTION)
111 fn has_opaque_types(&self) -> bool {
112 self.has_type_flags(TypeFlags::HAS_TY_OPAQUE)
114 fn references_error(&self) -> bool {
115 self.has_type_flags(TypeFlags::HAS_ERROR)
117 fn potentially_has_param_types_or_consts(&self) -> bool {
119 TypeFlags::HAS_KNOWN_TY_PARAM
120 | TypeFlags::HAS_KNOWN_CT_PARAM
121 | TypeFlags::HAS_UNKNOWN_DEFAULT_CONST_SUBSTS,
124 fn definitely_has_param_types_or_consts(&self, tcx: TyCtxt<'tcx>) -> bool {
125 self.definitely_has_type_flags(
127 TypeFlags::HAS_KNOWN_TY_PARAM | TypeFlags::HAS_KNOWN_CT_PARAM,
130 fn has_infer_regions(&self) -> bool {
131 self.has_type_flags(TypeFlags::HAS_RE_INFER)
133 fn has_infer_types(&self) -> bool {
134 self.has_type_flags(TypeFlags::HAS_TY_INFER)
136 fn has_infer_types_or_consts(&self) -> bool {
137 self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_CT_INFER)
139 fn needs_infer(&self) -> bool {
140 self.has_type_flags(TypeFlags::NEEDS_INFER)
142 fn has_placeholders(&self) -> bool {
144 TypeFlags::HAS_RE_PLACEHOLDER
145 | TypeFlags::HAS_TY_PLACEHOLDER
146 | TypeFlags::HAS_CT_PLACEHOLDER,
149 fn potentially_needs_subst(&self) -> bool {
151 TypeFlags::KNOWN_NEEDS_SUBST | TypeFlags::HAS_UNKNOWN_DEFAULT_CONST_SUBSTS,
154 fn definitely_needs_subst(&self, tcx: TyCtxt<'tcx>) -> bool {
155 self.definitely_has_type_flags(tcx, TypeFlags::KNOWN_NEEDS_SUBST)
157 /// "Free" regions in this context means that it has any region
158 /// that is not (a) erased or (b) late-bound.
159 fn has_free_regions(&self, tcx: TyCtxt<'tcx>) -> bool {
160 self.definitely_has_type_flags(tcx, TypeFlags::HAS_KNOWN_FREE_REGIONS)
163 fn has_erased_regions(&self) -> bool {
164 self.has_type_flags(TypeFlags::HAS_RE_ERASED)
167 /// True if there are any un-erased free regions.
168 fn has_erasable_regions(&self, tcx: TyCtxt<'tcx>) -> bool {
169 self.definitely_has_type_flags(tcx, TypeFlags::HAS_KNOWN_FREE_REGIONS)
172 /// Indicates whether this value definitely references only 'global'
173 /// generic parameters that are the same regardless of what fn we are
174 /// in. This is used for caching.
176 /// Note that this function is pessimistic and may incorrectly return
178 fn is_known_global(&self) -> bool {
179 !self.has_type_flags(TypeFlags::HAS_POTENTIAL_FREE_LOCAL_NAMES)
182 /// Indicates whether this value references only 'global'
183 /// generic parameters that are the same regardless of what fn we are
184 /// in. This is used for caching.
185 fn is_global(&self, tcx: TyCtxt<'tcx>) -> bool {
186 !self.definitely_has_type_flags(tcx, TypeFlags::HAS_KNOWN_FREE_LOCAL_NAMES)
189 /// True if there are any late-bound regions
190 fn has_late_bound_regions(&self) -> bool {
191 self.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND)
194 /// Indicates whether this value still has parameters/placeholders/inference variables
195 /// which could be replaced later, in a way that would change the results of `impl`
197 fn still_further_specializable(&self) -> bool {
198 self.has_type_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE)
202 impl<'tcx> TypeFoldable<'tcx> for hir::Constness {
203 fn try_super_fold_with<F: TypeFolder<'tcx>>(self, _: &mut F) -> Result<Self, F::Error> {
206 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> ControlFlow<V::BreakTy> {
207 ControlFlow::CONTINUE
211 /// The `TypeFolder` trait defines the actual *folding*. There is a
212 /// method defined for every foldable type. Each of these has a
213 /// default implementation that does an "identity" fold. Within each
214 /// identity fold, it should invoke `foo.fold_with(self)` to fold each
217 /// If this folder is fallible (and therefore its [`Error`][`TypeFolder::Error`]
218 /// associated type is something other than the default, never),
219 /// [`FallibleTypeFolder`] should be implemented manually; otherwise,
220 /// a blanket implementation of [`FallibleTypeFolder`] will defer to
221 /// the infallible methods of this trait to ensure that the two APIs
223 pub trait TypeFolder<'tcx>: Sized {
226 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
228 fn fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Binder<'tcx, T>
230 T: TypeFoldable<'tcx>,
231 Self: TypeFolder<'tcx, Error = !>,
233 t.super_fold_with(self)
236 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx>
238 Self: TypeFolder<'tcx, Error = !>,
240 t.super_fold_with(self)
243 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx>
245 Self: TypeFolder<'tcx, Error = !>,
247 r.super_fold_with(self)
250 fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>
252 Self: TypeFolder<'tcx, Error = !>,
254 c.super_fold_with(self)
257 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx>
259 Self: TypeFolder<'tcx, Error = !>,
261 p.super_fold_with(self)
264 fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx>
266 Self: TypeFolder<'tcx, Error = !>,
268 bug!("most type folders should not be folding MIR datastructures: {:?}", c)
272 /// The `FallibleTypeFolder` trait defines the actual *folding*. There is a
273 /// method defined for every foldable type. Each of these has a
274 /// default implementation that does an "identity" fold. Within each
275 /// identity fold, it should invoke `foo.try_fold_with(self)` to fold each
278 /// A blanket implementation of this trait (that defers to the relevant
279 /// method of [`TypeFolder`]) is provided for all infallible folders in
280 /// order to ensure the two APIs are coherent.
281 pub trait FallibleTypeFolder<'tcx>: TypeFolder<'tcx> {
282 fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, Self::Error>
284 T: TypeFoldable<'tcx>,
286 t.try_super_fold_with(self)
289 fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
290 t.try_super_fold_with(self)
293 fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
294 r.try_super_fold_with(self)
299 c: &'tcx ty::Const<'tcx>,
300 ) -> Result<&'tcx ty::Const<'tcx>, Self::Error> {
301 c.try_super_fold_with(self)
304 fn try_fold_predicate(
306 p: ty::Predicate<'tcx>,
307 ) -> Result<ty::Predicate<'tcx>, Self::Error> {
308 p.try_super_fold_with(self)
311 fn try_fold_mir_const(
313 c: mir::ConstantKind<'tcx>,
314 ) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
315 bug!("most type folders should not be folding MIR datastructures: {:?}", c)
319 // Blanket implementation of fallible trait for infallible folders
320 // delegates to infallible methods to prevent incoherence
321 impl<'tcx, F> FallibleTypeFolder<'tcx> for F
323 F: TypeFolder<'tcx, Error = !>,
325 fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, Self::Error>
327 T: TypeFoldable<'tcx>,
329 Ok(self.fold_binder(t))
332 fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
336 fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
337 Ok(self.fold_region(r))
342 c: &'tcx ty::Const<'tcx>,
343 ) -> Result<&'tcx ty::Const<'tcx>, Self::Error> {
344 Ok(self.fold_const(c))
347 fn try_fold_predicate(
349 p: ty::Predicate<'tcx>,
350 ) -> Result<ty::Predicate<'tcx>, Self::Error> {
351 Ok(self.fold_predicate(p))
354 fn try_fold_mir_const(
356 c: mir::ConstantKind<'tcx>,
357 ) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
358 Ok(self.fold_mir_const(c))
362 pub trait TypeVisitor<'tcx>: Sized {
364 /// Supplies the `tcx` for an unevaluated anonymous constant in case its default substs
365 /// are not yet supplied.
367 /// Returning `None` for this method is only recommended if the `TypeVisitor`
368 /// does not care about default anon const substs, as it ignores generic parameters,
369 /// and fetching the default substs would cause a query cycle.
371 /// For visitors which return `None` we completely skip the default substs in `ty::Unevaluated::super_visit_with`.
372 /// This means that incorrectly returning `None` can very quickly lead to ICE or other critical bugs, so be careful and
373 /// try to return an actual `tcx` if possible.
374 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>>;
376 fn visit_binder<T: TypeFoldable<'tcx>>(
379 ) -> ControlFlow<Self::BreakTy> {
380 t.super_visit_with(self)
383 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
384 t.super_visit_with(self)
387 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
388 r.super_visit_with(self)
391 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
392 c.super_visit_with(self)
395 fn visit_unevaluated_const(&mut self, uv: ty::Unevaluated<'tcx>) -> ControlFlow<Self::BreakTy> {
396 uv.super_visit_with(self)
399 fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
400 p.super_visit_with(self)
404 ///////////////////////////////////////////////////////////////////////////
405 // Some sample folders
407 pub struct BottomUpFolder<'tcx, F, G, H>
409 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
410 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
411 H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
413 pub tcx: TyCtxt<'tcx>,
419 impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
421 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
422 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
423 H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
425 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
429 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
430 let t = ty.super_fold_with(self);
434 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
435 let r = r.super_fold_with(self);
439 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
440 let ct = ct.super_fold_with(self);
445 ///////////////////////////////////////////////////////////////////////////
448 impl<'tcx> TyCtxt<'tcx> {
449 /// Folds the escaping and free regions in `value` using `f`, and
450 /// sets `skipped_regions` to true if any late-bound region was found
452 pub fn fold_regions<T>(
455 skipped_regions: &mut bool,
456 mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
459 T: TypeFoldable<'tcx>,
461 value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
464 /// Invoke `callback` on every region appearing free in `value`.
465 pub fn for_each_free_region(
467 value: &impl TypeFoldable<'tcx>,
468 mut callback: impl FnMut(ty::Region<'tcx>),
470 self.any_free_region_meets(value, |r| {
476 /// Returns `true` if `callback` returns true for every region appearing free in `value`.
477 pub fn all_free_regions_meet(
479 value: &impl TypeFoldable<'tcx>,
480 mut callback: impl FnMut(ty::Region<'tcx>) -> bool,
482 !self.any_free_region_meets(value, |r| !callback(r))
485 /// Returns `true` if `callback` returns true for some region appearing free in `value`.
486 pub fn any_free_region_meets(
488 value: &impl TypeFoldable<'tcx>,
489 callback: impl FnMut(ty::Region<'tcx>) -> bool,
491 struct RegionVisitor<'tcx, F> {
493 /// The index of a binder *just outside* the things we have
494 /// traversed. If we encounter a bound region bound by this
495 /// binder or one outer to it, it appears free. Example:
498 /// for<'a> fn(for<'b> fn(), T)
500 /// | | | | here, would be shifted in 1
501 /// | | | here, would be shifted in 2
502 /// | | here, would be `INNERMOST` shifted in by 1
503 /// | here, initially, binder would be `INNERMOST`
506 /// You see that, initially, *any* bound value is free,
507 /// because we've not traversed any binders. As we pass
508 /// through a binder, we shift the `outer_index` by 1 to
509 /// account for the new binder that encloses us.
510 outer_index: ty::DebruijnIndex,
514 impl<'tcx, F> TypeVisitor<'tcx> for RegionVisitor<'tcx, F>
516 F: FnMut(ty::Region<'tcx>) -> bool,
520 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
524 fn visit_binder<T: TypeFoldable<'tcx>>(
527 ) -> ControlFlow<Self::BreakTy> {
528 self.outer_index.shift_in(1);
529 let result = t.as_ref().skip_binder().visit_with(self);
530 self.outer_index.shift_out(1);
534 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
536 ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => {
537 ControlFlow::CONTINUE
540 if (self.callback)(r) {
543 ControlFlow::CONTINUE
549 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
550 // We're only interested in types involving regions
551 if ty.flags().intersects(TypeFlags::HAS_POTENTIAL_FREE_REGIONS) {
552 ty.super_visit_with(self)
554 ControlFlow::CONTINUE
560 .visit_with(&mut RegionVisitor { tcx: self, outer_index: ty::INNERMOST, callback })
565 /// Folds over the substructure of a type, visiting its component
566 /// types and all regions that occur *free* within it.
568 /// That is, `Ty` can contain function or method types that bind
569 /// regions at the call site (`ReLateBound`), and occurrences of
570 /// regions (aka "lifetimes") that are bound within a type are not
571 /// visited by this folder; only regions that occur free will be
572 /// visited by `fld_r`.
574 pub struct RegionFolder<'a, 'tcx> {
576 skipped_regions: &'a mut bool,
578 /// Stores the index of a binder *just outside* the stuff we have
579 /// visited. So this begins as INNERMOST; when we pass through a
580 /// binder, it is incremented (via `shift_in`).
581 current_index: ty::DebruijnIndex,
583 /// Callback invokes for each free region. The `DebruijnIndex`
584 /// points to the binder *just outside* the ones we have passed
587 &'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
590 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
594 skipped_regions: &'a mut bool,
595 fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
596 ) -> RegionFolder<'a, 'tcx> {
597 RegionFolder { tcx, skipped_regions, current_index: ty::INNERMOST, fold_region_fn }
601 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
602 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
606 fn fold_binder<T: TypeFoldable<'tcx>>(
608 t: ty::Binder<'tcx, T>,
609 ) -> ty::Binder<'tcx, T> {
610 self.current_index.shift_in(1);
611 let t = t.super_fold_with(self);
612 self.current_index.shift_out(1);
616 #[instrument(skip(self), level = "debug")]
617 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
619 ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
620 debug!(?self.current_index, "skipped bound region");
621 *self.skipped_regions = true;
625 debug!(?self.current_index, "folding free region");
626 (self.fold_region_fn)(r, self.current_index)
632 ///////////////////////////////////////////////////////////////////////////
633 // Bound vars replacer
635 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
636 struct BoundVarReplacer<'a, 'tcx> {
639 /// As with `RegionFolder`, represents the index of a binder *just outside*
640 /// the ones we have visited.
641 current_index: ty::DebruijnIndex,
643 fld_r: Option<&'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a)>,
644 fld_t: Option<&'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a)>,
645 fld_c: Option<&'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx> + 'a)>,
648 impl<'a, 'tcx> BoundVarReplacer<'a, 'tcx> {
651 fld_r: Option<&'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a)>,
652 fld_t: Option<&'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a)>,
653 fld_c: Option<&'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx> + 'a)>,
655 BoundVarReplacer { tcx, current_index: ty::INNERMOST, fld_r, fld_t, fld_c }
659 impl<'a, 'tcx> TypeFolder<'tcx> for BoundVarReplacer<'a, 'tcx> {
660 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
664 fn fold_binder<T: TypeFoldable<'tcx>>(
666 t: ty::Binder<'tcx, T>,
667 ) -> ty::Binder<'tcx, T> {
668 self.current_index.shift_in(1);
669 let t = t.super_fold_with(self);
670 self.current_index.shift_out(1);
674 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
676 ty::Bound(debruijn, bound_ty) if debruijn == self.current_index => {
677 if let Some(fld_t) = self.fld_t.as_mut() {
678 let ty = fld_t(bound_ty);
679 return ty::fold::shift_vars(self.tcx, &ty, self.current_index.as_u32());
682 _ if t.has_vars_bound_at_or_above(self.current_index) => {
683 return t.super_fold_with(self);
690 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
692 ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
693 if let Some(fld_r) = self.fld_r.as_mut() {
694 let region = fld_r(br);
695 return if let ty::ReLateBound(debruijn1, br) = *region {
696 // If the callback returns a late-bound region,
697 // that region should always use the INNERMOST
698 // debruijn index. Then we adjust it to the
700 assert_eq!(debruijn1, ty::INNERMOST);
701 self.tcx.mk_region(ty::ReLateBound(debruijn, br))
712 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
714 ty::Const { val: ty::ConstKind::Bound(debruijn, bound_const), ty }
715 if debruijn == self.current_index =>
717 if let Some(fld_c) = self.fld_c.as_mut() {
718 let ct = fld_c(bound_const, ty);
719 return ty::fold::shift_vars(self.tcx, &ct, self.current_index.as_u32());
722 _ if ct.has_vars_bound_at_or_above(self.current_index) => {
723 return ct.super_fold_with(self);
731 impl<'tcx> TyCtxt<'tcx> {
732 /// Replaces all regions bound by the given `Binder` with the
733 /// results returned by the closure; the closure is expected to
734 /// return a free region (relative to this binder), and hence the
735 /// binder is removed in the return type. The closure is invoked
736 /// once for each unique `BoundRegionKind`; multiple references to the
737 /// same `BoundRegionKind` will reuse the previous result. A map is
738 /// returned at the end with each bound region and the free region
739 /// that replaced it.
741 /// This method only replaces late bound regions and the result may still
742 /// contain escaping bound types.
743 pub fn replace_late_bound_regions<T, F>(
745 value: Binder<'tcx, T>,
747 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
749 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
750 T: TypeFoldable<'tcx>,
752 let mut region_map = BTreeMap::new();
754 |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br));
755 let value = value.skip_binder();
756 let value = if !value.has_escaping_bound_vars() {
759 let mut replacer = BoundVarReplacer::new(self, Some(&mut real_fld_r), None, None);
760 value.fold_with(&mut replacer)
765 /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
766 /// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c`
767 /// closure replaces escaping bound consts.
768 pub fn replace_escaping_bound_vars<T, F, G, H>(
776 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
777 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
778 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
779 T: TypeFoldable<'tcx>,
781 if !value.has_escaping_bound_vars() {
785 BoundVarReplacer::new(self, Some(&mut fld_r), Some(&mut fld_t), Some(&mut fld_c));
786 value.fold_with(&mut replacer)
790 /// Replaces all types or regions bound by the given `Binder`. The `fld_r`
791 /// closure replaces bound regions while the `fld_t` closure replaces bound
793 pub fn replace_bound_vars<T, F, G, H>(
795 value: Binder<'tcx, T>,
799 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
801 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
802 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
803 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
804 T: TypeFoldable<'tcx>,
806 let mut region_map = BTreeMap::new();
807 let real_fld_r = |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br));
808 let value = self.replace_escaping_bound_vars(value.skip_binder(), real_fld_r, fld_t, fld_c);
812 /// Replaces any late-bound regions bound in `value` with
813 /// free variants attached to `all_outlive_scope`.
814 pub fn liberate_late_bound_regions<T>(
816 all_outlive_scope: DefId,
817 value: ty::Binder<'tcx, T>,
820 T: TypeFoldable<'tcx>,
822 self.replace_late_bound_regions(value, |br| {
823 self.mk_region(ty::ReFree(ty::FreeRegion {
824 scope: all_outlive_scope,
825 bound_region: br.kind,
831 pub fn shift_bound_var_indices<T>(self, bound_vars: usize, value: T) -> T
833 T: TypeFoldable<'tcx>,
835 self.replace_escaping_bound_vars(
838 self.mk_region(ty::ReLateBound(
841 var: ty::BoundVar::from_usize(r.var.as_usize() + bound_vars),
847 self.mk_ty(ty::Bound(
850 var: ty::BoundVar::from_usize(t.var.as_usize() + bound_vars),
856 self.mk_const(ty::Const {
857 val: ty::ConstKind::Bound(
859 ty::BoundVar::from_usize(c.as_usize() + bound_vars),
867 /// Returns a set of all late-bound regions that are constrained
868 /// by `value`, meaning that if we instantiate those LBR with
869 /// variables and equate `value` with something else, those
870 /// variables will also be equated.
871 pub fn collect_constrained_late_bound_regions<T>(
873 value: &Binder<'tcx, T>,
874 ) -> FxHashSet<ty::BoundRegionKind>
876 T: TypeFoldable<'tcx>,
878 self.collect_late_bound_regions(value, true)
881 /// Returns a set of all late-bound regions that appear in `value` anywhere.
882 pub fn collect_referenced_late_bound_regions<T>(
884 value: &Binder<'tcx, T>,
885 ) -> FxHashSet<ty::BoundRegionKind>
887 T: TypeFoldable<'tcx>,
889 self.collect_late_bound_regions(value, false)
892 fn collect_late_bound_regions<T>(
894 value: &Binder<'tcx, T>,
895 just_constraint: bool,
896 ) -> FxHashSet<ty::BoundRegionKind>
898 T: TypeFoldable<'tcx>,
900 let mut collector = LateBoundRegionsCollector::new(self, just_constraint);
901 let result = value.as_ref().skip_binder().visit_with(&mut collector);
902 assert!(result.is_continue()); // should never have stopped early
906 /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
907 /// method lookup and a few other places where precise region relationships are not required.
908 pub fn erase_late_bound_regions<T>(self, value: Binder<'tcx, T>) -> T
910 T: TypeFoldable<'tcx>,
912 self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
915 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
916 /// assigned starting at 0 and increasing monotonically in the order traversed
917 /// by the fold operation.
919 /// The chief purpose of this function is to canonicalize regions so that two
920 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
921 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
922 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
923 pub fn anonymize_late_bound_regions<T>(self, sig: Binder<'tcx, T>) -> Binder<'tcx, T>
925 T: TypeFoldable<'tcx>,
929 .replace_late_bound_regions(sig, |_| {
930 let br = ty::BoundRegion {
931 var: ty::BoundVar::from_u32(counter),
932 kind: ty::BrAnon(counter),
934 let r = self.mk_region(ty::ReLateBound(ty::INNERMOST, br));
939 let bound_vars = self.mk_bound_variable_kinds(
940 (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))),
942 Binder::bind_with_vars(inner, bound_vars)
946 pub struct ValidateBoundVars<'tcx> {
947 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
948 binder_index: ty::DebruijnIndex,
949 // We may encounter the same variable at different levels of binding, so
950 // this can't just be `Ty`
951 visited: SsoHashSet<(ty::DebruijnIndex, Ty<'tcx>)>,
954 impl<'tcx> ValidateBoundVars<'tcx> {
955 pub fn new(bound_vars: &'tcx ty::List<ty::BoundVariableKind>) -> Self {
958 binder_index: ty::INNERMOST,
959 visited: SsoHashSet::default(),
964 impl<'tcx> TypeVisitor<'tcx> for ValidateBoundVars<'tcx> {
967 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
968 // Anonymous constants do not contain bound vars in their substs by default.
972 fn visit_binder<T: TypeFoldable<'tcx>>(
975 ) -> ControlFlow<Self::BreakTy> {
976 self.binder_index.shift_in(1);
977 let result = t.super_visit_with(self);
978 self.binder_index.shift_out(1);
982 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
983 if t.outer_exclusive_binder < self.binder_index
984 || !self.visited.insert((self.binder_index, t))
986 return ControlFlow::BREAK;
989 ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
990 if self.bound_vars.len() <= bound_ty.var.as_usize() {
991 bug!("Not enough bound vars: {:?} not found in {:?}", t, self.bound_vars);
993 let list_var = self.bound_vars[bound_ty.var.as_usize()];
995 ty::BoundVariableKind::Ty(kind) => {
996 if kind != bound_ty.kind {
998 "Mismatched type kinds: {:?} doesn't var in list {:?}",
1005 bug!("Mismatched bound variable kinds! Expected type, found {:?}", list_var)
1013 t.super_visit_with(self)
1016 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1018 ty::ReLateBound(index, br) if *index == self.binder_index => {
1019 if self.bound_vars.len() <= br.var.as_usize() {
1020 bug!("Not enough bound vars: {:?} not found in {:?}", *br, self.bound_vars);
1022 let list_var = self.bound_vars[br.var.as_usize()];
1024 ty::BoundVariableKind::Region(kind) => {
1025 if kind != br.kind {
1027 "Mismatched region kinds: {:?} doesn't match var ({:?}) in list ({:?})",
1035 "Mismatched bound variable kinds! Expected region, found {:?}",
1044 r.super_visit_with(self)
1048 ///////////////////////////////////////////////////////////////////////////
1051 // Shifts the De Bruijn indices on all escaping bound vars by a
1052 // fixed amount. Useful in substitution or when otherwise introducing
1053 // a binding level that is not intended to capture the existing bound
1054 // vars. See comment on `shift_vars_through_binders` method in
1055 // `subst.rs` for more details.
1057 struct Shifter<'tcx> {
1059 current_index: ty::DebruijnIndex,
1063 impl<'tcx> Shifter<'tcx> {
1064 pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self {
1065 Shifter { tcx, current_index: ty::INNERMOST, amount }
1069 impl<'tcx> TypeFolder<'tcx> for Shifter<'tcx> {
1070 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1074 fn fold_binder<T: TypeFoldable<'tcx>>(
1076 t: ty::Binder<'tcx, T>,
1077 ) -> ty::Binder<'tcx, T> {
1078 self.current_index.shift_in(1);
1079 let t = t.super_fold_with(self);
1080 self.current_index.shift_out(1);
1084 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1086 ty::ReLateBound(debruijn, br) => {
1087 if self.amount == 0 || debruijn < self.current_index {
1090 let debruijn = debruijn.shifted_in(self.amount);
1091 let shifted = ty::ReLateBound(debruijn, br);
1092 self.tcx.mk_region(shifted)
1099 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1101 ty::Bound(debruijn, bound_ty) => {
1102 if self.amount == 0 || debruijn < self.current_index {
1105 let debruijn = debruijn.shifted_in(self.amount);
1106 self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
1110 _ => ty.super_fold_with(self),
1114 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1115 if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty } = *ct {
1116 if self.amount == 0 || debruijn < self.current_index {
1119 let debruijn = debruijn.shifted_in(self.amount);
1120 self.tcx.mk_const(ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty })
1123 ct.super_fold_with(self)
1128 pub fn shift_region<'tcx>(
1130 region: ty::Region<'tcx>,
1132 ) -> ty::Region<'tcx> {
1134 ty::ReLateBound(debruijn, br) if amount > 0 => {
1135 tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), *br))
1141 pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: T, amount: u32) -> T
1143 T: TypeFoldable<'tcx>,
1145 debug!("shift_vars(value={:?}, amount={})", value, amount);
1147 value.fold_with(&mut Shifter::new(tcx, amount))
1150 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
1151 struct FoundEscapingVars;
1153 /// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a
1154 /// bound region or a bound type.
1156 /// So, for example, consider a type like the following, which has two binders:
1158 /// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
1159 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
1160 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
1162 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
1163 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
1164 /// fn type*, that type has an escaping region: `'a`.
1166 /// Note that what I'm calling an "escaping var" is often just called a "free var". However,
1167 /// we already use the term "free var". It refers to the regions or types that we use to represent
1168 /// bound regions or type params on a fn definition while we are type checking its body.
1170 /// To clarify, conceptually there is no particular difference between
1171 /// an "escaping" var and a "free" var. However, there is a big
1172 /// difference in practice. Basically, when "entering" a binding
1173 /// level, one is generally required to do some sort of processing to
1174 /// a bound var, such as replacing it with a fresh/placeholder
1175 /// var, or making an entry in the environment to represent the
1176 /// scope to which it is attached, etc. An escaping var represents
1177 /// a bound var for which this processing has not yet been done.
1178 struct HasEscapingVarsVisitor {
1179 /// Anything bound by `outer_index` or "above" is escaping.
1180 outer_index: ty::DebruijnIndex,
1183 impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor {
1184 type BreakTy = FoundEscapingVars;
1186 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
1187 // Anonymous constants do not contain bound vars in their substs by default.
1191 fn visit_binder<T: TypeFoldable<'tcx>>(
1193 t: &Binder<'tcx, T>,
1194 ) -> ControlFlow<Self::BreakTy> {
1195 self.outer_index.shift_in(1);
1196 let result = t.super_visit_with(self);
1197 self.outer_index.shift_out(1);
1202 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1203 // If the outer-exclusive-binder is *strictly greater* than
1204 // `outer_index`, that means that `t` contains some content
1205 // bound at `outer_index` or above (because
1206 // `outer_exclusive_binder` is always 1 higher than the
1207 // content in `t`). Therefore, `t` has some escaping vars.
1208 if t.outer_exclusive_binder > self.outer_index {
1209 ControlFlow::Break(FoundEscapingVars)
1211 ControlFlow::CONTINUE
1216 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1217 // If the region is bound by `outer_index` or anything outside
1218 // of outer index, then it escapes the binders we have
1220 if r.bound_at_or_above_binder(self.outer_index) {
1221 ControlFlow::Break(FoundEscapingVars)
1223 ControlFlow::CONTINUE
1227 fn visit_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1228 // we don't have a `visit_infer_const` callback, so we have to
1229 // hook in here to catch this case (annoying...), but
1230 // otherwise we do want to remember to visit the rest of the
1231 // const, as it has types/regions embedded in a lot of other
1234 ty::ConstKind::Bound(debruijn, _) if debruijn >= self.outer_index => {
1235 ControlFlow::Break(FoundEscapingVars)
1237 _ => ct.super_visit_with(self),
1242 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
1243 if predicate.inner.outer_exclusive_binder > self.outer_index {
1244 ControlFlow::Break(FoundEscapingVars)
1246 ControlFlow::CONTINUE
1251 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
1254 // FIXME: Optimize for checking for infer flags
1255 struct HasTypeFlagsVisitor<'tcx> {
1256 tcx: Option<TyCtxt<'tcx>>,
1257 flags: ty::TypeFlags,
1260 impl<'tcx> std::fmt::Debug for HasTypeFlagsVisitor<'tcx> {
1261 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1266 impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor<'tcx> {
1267 type BreakTy = FoundFlags;
1268 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
1269 bug!("we shouldn't call this method as we manually look at ct substs");
1273 #[instrument(level = "trace")]
1274 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1275 let flags = t.flags();
1276 trace!(t.flags=?t.flags());
1277 if flags.intersects(self.flags) {
1278 ControlFlow::Break(FoundFlags)
1280 match flags.intersects(TypeFlags::HAS_UNKNOWN_DEFAULT_CONST_SUBSTS) {
1281 true if self.tcx.is_some() => UnknownConstSubstsVisitor::search(&self, t),
1282 _ => ControlFlow::CONTINUE,
1288 #[instrument(skip(self), level = "trace")]
1289 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1290 let flags = r.type_flags();
1291 trace!(r.flags=?flags);
1292 if flags.intersects(self.flags) {
1293 ControlFlow::Break(FoundFlags)
1295 ControlFlow::CONTINUE
1300 #[instrument(level = "trace")]
1301 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1302 let flags = FlagComputation::for_const(c);
1303 trace!(r.flags=?flags);
1304 if flags.intersects(self.flags) {
1305 ControlFlow::Break(FoundFlags)
1307 match flags.intersects(TypeFlags::HAS_UNKNOWN_DEFAULT_CONST_SUBSTS) {
1308 true if self.tcx.is_some() => UnknownConstSubstsVisitor::search(&self, c),
1309 _ => ControlFlow::CONTINUE,
1315 #[instrument(level = "trace")]
1316 fn visit_unevaluated_const(&mut self, uv: ty::Unevaluated<'tcx>) -> ControlFlow<Self::BreakTy> {
1317 let flags = FlagComputation::for_unevaluated_const(uv);
1318 trace!(r.flags=?flags);
1319 if flags.intersects(self.flags) {
1320 ControlFlow::Break(FoundFlags)
1322 match flags.intersects(TypeFlags::HAS_UNKNOWN_DEFAULT_CONST_SUBSTS) {
1323 true if self.tcx.is_some() => UnknownConstSubstsVisitor::search(&self, uv),
1324 _ => ControlFlow::CONTINUE,
1330 #[instrument(level = "trace")]
1331 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
1332 let flags = predicate.inner.flags;
1333 trace!(predicate.flags=?flags);
1334 if flags.intersects(self.flags) {
1335 ControlFlow::Break(FoundFlags)
1337 match flags.intersects(TypeFlags::HAS_UNKNOWN_DEFAULT_CONST_SUBSTS) {
1338 true if self.tcx.is_some() => UnknownConstSubstsVisitor::search(&self, predicate),
1339 _ => ControlFlow::CONTINUE,
1345 struct UnknownConstSubstsVisitor<'tcx> {
1347 flags: ty::TypeFlags,
1350 impl<'tcx> UnknownConstSubstsVisitor<'tcx> {
1351 /// This is fairly cold and we don't want to
1352 /// bloat the size of the `HasTypeFlagsVisitor`.
1354 pub fn search<T: TypeFoldable<'tcx>>(
1355 visitor: &HasTypeFlagsVisitor<'tcx>,
1357 ) -> ControlFlow<FoundFlags> {
1358 if visitor.flags.intersects(TypeFlags::MAY_NEED_DEFAULT_CONST_SUBSTS) {
1359 v.super_visit_with(&mut UnknownConstSubstsVisitor {
1360 tcx: visitor.tcx.unwrap(),
1361 flags: visitor.flags,
1364 ControlFlow::CONTINUE
1369 impl<'tcx> TypeVisitor<'tcx> for UnknownConstSubstsVisitor<'tcx> {
1370 type BreakTy = FoundFlags;
1371 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
1372 bug!("we shouldn't call this method as we manually look at ct substs");
1375 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1376 if t.flags().intersects(TypeFlags::HAS_UNKNOWN_DEFAULT_CONST_SUBSTS) {
1377 t.super_visit_with(self)
1379 ControlFlow::CONTINUE
1384 fn visit_unevaluated_const(&mut self, uv: ty::Unevaluated<'tcx>) -> ControlFlow<Self::BreakTy> {
1385 if uv.substs_.is_none() {
1387 .default_anon_const_substs(uv.def.did)
1388 .visit_with(&mut HasTypeFlagsVisitor { tcx: Some(self.tcx), flags: self.flags })
1390 ControlFlow::CONTINUE
1395 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
1396 if predicate.inner.flags.intersects(TypeFlags::HAS_UNKNOWN_DEFAULT_CONST_SUBSTS) {
1397 predicate.super_visit_with(self)
1399 ControlFlow::CONTINUE
1404 impl<'tcx> TyCtxt<'tcx> {
1405 /// This is a HACK(const_generics) and should probably not be needed.
1406 /// Might however be perf relevant, so who knows.
1408 /// FIXME(@lcnr): explain this function a bit more
1409 pub fn expose_default_const_substs<T: TypeFoldable<'tcx>>(self, v: T) -> T {
1410 v.fold_with(&mut ExposeDefaultConstSubstsFolder { tcx: self })
1414 struct ExposeDefaultConstSubstsFolder<'tcx> {
1418 impl<'tcx> TypeFolder<'tcx> for ExposeDefaultConstSubstsFolder<'tcx> {
1419 fn tcx(&self) -> TyCtxt<'tcx> {
1423 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1424 if ty.flags().intersects(TypeFlags::HAS_UNKNOWN_DEFAULT_CONST_SUBSTS) {
1425 ty.super_fold_with(self)
1431 fn fold_predicate(&mut self, pred: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
1432 if pred.inner.flags.intersects(TypeFlags::HAS_UNKNOWN_DEFAULT_CONST_SUBSTS) {
1433 pred.super_fold_with(self)
1440 /// Collects all the late-bound regions at the innermost binding level
1441 /// into a hash set.
1442 struct LateBoundRegionsCollector<'tcx> {
1444 current_index: ty::DebruijnIndex,
1445 regions: FxHashSet<ty::BoundRegionKind>,
1447 /// `true` if we only want regions that are known to be
1448 /// "constrained" when you equate this type with another type. In
1449 /// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
1450 /// them constraints `'a == 'b`. But if you have `<&'a u32 as
1451 /// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
1452 /// types may mean that `'a` and `'b` don't appear in the results,
1453 /// so they are not considered *constrained*.
1454 just_constrained: bool,
1457 impl<'tcx> LateBoundRegionsCollector<'tcx> {
1458 fn new(tcx: TyCtxt<'tcx>, just_constrained: bool) -> Self {
1459 LateBoundRegionsCollector {
1461 current_index: ty::INNERMOST,
1462 regions: Default::default(),
1468 impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector<'tcx> {
1469 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
1473 fn visit_binder<T: TypeFoldable<'tcx>>(
1475 t: &Binder<'tcx, T>,
1476 ) -> ControlFlow<Self::BreakTy> {
1477 self.current_index.shift_in(1);
1478 let result = t.super_visit_with(self);
1479 self.current_index.shift_out(1);
1483 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1484 // if we are only looking for "constrained" region, we have to
1485 // ignore the inputs to a projection, as they may not appear
1486 // in the normalized form
1487 if self.just_constrained {
1488 if let ty::Projection(..) | ty::Opaque(..) = t.kind() {
1489 return ControlFlow::CONTINUE;
1493 t.super_visit_with(self)
1496 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1497 // if we are only looking for "constrained" region, we have to
1498 // ignore the inputs of an unevaluated const, as they may not appear
1499 // in the normalized form
1500 if self.just_constrained {
1501 if let ty::ConstKind::Unevaluated(..) = c.val {
1502 return ControlFlow::CONTINUE;
1506 c.super_visit_with(self)
1509 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1510 if let ty::ReLateBound(debruijn, br) = *r {
1511 if debruijn == self.current_index {
1512 self.regions.insert(br.kind);
1515 ControlFlow::CONTINUE