Skip to content

Anonymize inner binders when checking refining - #165222

Merged
rust-bors[bot] merged 1 commit into
rust-lang:mainfrom
mu001999-contrib:fix-165091
Nov 7, 2026
Merged

rust-bors[bot] merged 1 commit into
rust-lang:mainfrom
mu001999-contrib:fix-165091

Conversation

@mu001999

@mu001999 mu001999 commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Fix #165091

The inner binder is missed.

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Oct 31, 2026
@mu001999
mu001999 marked this pull request as ready for review October 31, 2026 13:47
@rustbot rustbot added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Oct 31, 2026
@rustbot rustbot removed the S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. label Oct 31, 2026
@rustbot

This comment was marked as outdated.

@fmease fmease assigned fmease and unassigned beetrees Nov 3, 2026

@fmease fmease left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this! I got a smallish request :)

View changes since this review

T: TypeFoldable<TyCtxt<'tcx>>,
{
self.tcx.anonymize_bound_vars(t)
self.tcx.anonymize_bound_vars(t.super_fold_with(self))

@fmease fmease Nov 4, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This implementation is obviously correct but it's doing a lot unnecessary walking & work. Of course, this part of the code isn't performance critical & I don't think we have any benchmarks containing RPITITs. Still, IMO we should simplify this, it won't take that much more code.


As you know, anonymize_bound_vars only anonymizes bound vars bound by the current binder & under the hood it's also a TypeFolder (with some TypeFlags and other early returns) meaning in total we rewalk the type a lot if there are several binders.

Moreover, the BoundVarReplacer (a folder) inside anonymize_bound_vars performs a lot of checks to ensure it only replaces bound vars that are bound at the correct level & it has to shift the de-Bruijn indices & re-intern the shifted regions etc. produced by anonymize_bound_vars's BoundVarReplacerDelegate.

However, since the idea of our Anonymize here is to fully anonymize the type, most of these things don't need to be done. Fundamentally we simply we want to replace any Bound{Region,Ty,Const}Kind with Anon keeping the de Bruijn index & the BoundVar (index) fully intact.


So this whole operation could just be a TypeFolder that impls fold_{region,type,const}, returns the argument unchanged if it !_.has_bound_vars() otherwise if it's a ty::{,Re,ConstKind::}Bound return a *Bound with *Kind::Anon.

@fmease fmease Nov 4, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

E.g., for code like

#![deny(refining_impl_trait)]
trait A {
    fn f() -> impl B<for<'a> fn(for<'b> fn(&'a (), &'b ()))>;
}
impl A for () {
    fn f() -> impl B<for<'a> fn(for<'b> fn(&'a (), &'b ()))> {}
}
trait B<T: ?Sized> {}
impl<T: ?Sized, U: ?Sized> B<T> for U {}

the execution trace under your PR looks something like

fold_binder()
    # arg: Binder { value: TraitClause(<Opaque(DefId(0:10 ~ b[656a]::{impl#0}::f::{opaque#0}), []) as B<for<Region(BrNamed(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)))> fn(for<Region(BrNamed(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)))> fn(&'^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)) (), &'^0.Named(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)) ()))>>, polarity:Positive), bound_vars: [] }
    # arg has bound vars; calling super_fold_with()...
    fold_ty()
        # arg: Alias(Yes, Alias { kind: Opaque { def_id: DefId(0:10 ~ b[656a]::{impl#0}::f::{opaque#0}) }, args: [], .. })
        # arg has no bound vars; ret arg as is...
    fold_ty()
        # arg: Binder { value: fn(Binder { value: fn(&'^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)) (), &'^0.Named(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)) ()), bound_vars: [Region(BrNamed(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)))] }), bound_vars: [Region(BrNamed(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)))] }
        # arg has bound vars; calling super_fold_with()...
        fold_binder()
            # arg: Binder { value: FnSigTys { inputs_and_output: [Binder { value: fn(&'^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)) (), &'^0.Named(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)) ()), bound_vars: [Region(BrNamed(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)))] }, ()] }, bound_vars: [Region(BrNamed(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)))] }
            # arg has bound vars; calling super_fold_with()...
            fold_ty()
                # arg: Binder { value: fn(&'^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)) (), &'^0.Named(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)) ()), bound_vars: [Region(BrNamed(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)))] }
                # arg has bound vars; calling super_fold_with()...
                fold_binder()
                    # arg: Binder { value: FnSigTys { inputs_and_output: [&'^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)) (), &'^0.Named(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)) (), ()] }, bound_vars: [Region(BrNamed(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)))] }
                    # arg has bound vars; calling super_fold_with()...
                    fold_ty()
                        # arg: &'^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)) ()
                        # arg has bound vars; calling super_fold_with()...
                        fold_ty()
                            # arg: ()
                            # arg has no bound vars; ret arg as is...
                    fold_ty()
                        # arg: &'^0.Named(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)) ()
                        # arg has bound vars; calling super_fold_with()...
                        fold_ty()
                            # arg: ()
                            # arg has no bound vars; ret arg as is...
                    fold_ty()
                        # arg: ()
                        # arg has no bound vars; ret arg as is...
                    anonymize_bound_vars()
                        # arg: Binder { value: FnSigTys { inputs_and_output: [&'^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)) (), &'^0.Named(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)) (), ()] }, bound_vars: [Region(BrNamed(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)))] }
                        # has esc bound vars; calling arg.fold_with(BVR)...
                            BVR::fold_ty()
                                # arg: &'^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)) ()
                                # has vars bound at/above current index
                                # calling super_fold_with()...
                                BVR::fold_region()
                                    # arg: '^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a))
                                    # not ReBound with matching index; returning arg as is...
                                BVR::fold_ty()
                                    # arg: ()
                                    # no vars bound at/above current index; ret arg as is...
                            BVR::fold_ty()
                                # arg: &'^0.Named(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)) ()
                                # has vars bound at/above current index
                                # calling super_fold_with()...
                                BVR::fold_region()
                                    # arg: '^0.Named(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b))
                                    # is ReBound with matching index
                                    # calling delegate.replace_region(0.Named(DefId(0:7 ~ b[656a]::A::f::{opaque#0}::'b)))...
                                    # ...which yielded '^0
                                    # adjusting the de Bruijn index...
                                    # ...giving us '^0
                                BVR::fold_ty()
                                    # arg: ()
                                    # no vars bound at/above current index; ret arg as is...
                            BVR::fold_ty()
                                # arg: ()
                                # no vars bound at/above current index; ret arg as is...
            fold_ty()
                # arg: ()
                # arg has no bound vars; ret arg as is...
            anonymize_bound_vars()
                # arg: Binder { value: FnSigTys { inputs_and_output: [Binder { value: fn(&'^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)) (), &'^0 ()), bound_vars: [Region(BrAnon)] }, ()] }, bound_vars: [Region(BrNamed(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)))] }
                # has esc bound vars; calling arg.fold_with(BVR)...
                    BVR::fold_ty()
                        # arg: Binder { value: fn(&'^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)) (), &'^0 ()), bound_vars: [Region(BrAnon)] }
                        # has vars bound at/above current index
                        # calling super_fold_with()...
                        BVR::fold_binder()
                            # arg: Binder { value: FnSigTys { inputs_and_output: [&'^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)) (), &'^0 (), ()] }, bound_vars: [Region(BrAnon)] }
                            # calling super_fold_with()...
                            BVR::fold_ty()
                                # arg: &'^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)) ()
                                # has vars bound at/above current index
                                # calling super_fold_with()...
                                BVR::fold_region()
                                    # arg: '^1_0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a))
                                    # is ReBound with matching index
                                    # calling delegate.replace_region(0.Named(DefId(0:6 ~ b[656a]::A::f::{opaque#0}::'a)))...
                                    # ...which yielded '^0
                                    # adjusting the de Bruijn index...
                                    # ...giving us '^1_0
                                BVR::fold_ty()
                                    # arg: ()
                                    # no vars bound at/above current index; ret arg as is...
                            BVR::fold_ty()
                                # arg: &'^0 ()
                                # no vars bound at/above current index; ret arg as is...
                            BVR::fold_ty()
                                # arg: ()
                                # no vars bound at/above current index; ret arg as is...
                    BVR::fold_ty()
                        # arg: ()
                        # no vars bound at/above current index; ret arg as is...
    anonymize_bound_vars()
        # arg: Binder { value: TraitClause(<Opaque(DefId(0:10 ~ b[656a]::{impl#0}::f::{opaque#0}), []) as B<for<Region(BrAnon)> fn(for<Region(BrAnon)> fn(&'^1_0 (), &'^0 ()))>>, polarity:Positive), bound_vars: [] }
        # no esc bound vars; ret arg...

See how it walks into parts of the type just to walk out and reenter parts it's already visited & partially anonymized (but now under different Binder.bound_vars / at a different binder depth)?

@fmease fmease added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Nov 4, 2026
@rustbot

rustbot commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed.

Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers.

@fmease fmease left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for applying my feedback!

We don't need to care about canonical vars here, they shouldn't be reachable in refine. So similar to TyCtxt::anonymize_bound_vars we can just keep them as is which simplifies the folder.

@bors rollup

r=me with the following patch applied (simplifies the code & adds a documentation comment clarifying how this folder is different from anonymize_bound_vars):

diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs
index 12d2576e5df..969a6ae8c30 100644
--- a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs
+++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs
@@ -210,8 +210,8 @@ pub(crate) fn check_refining_return_position_impl_trait_in_trait<'tcx>(
     // Also, We have to anonymize binders in these types because they may contain
     // `BrNamed` bound vars, which contain unique `DefId`s which correspond to syntax
     // locations that we don't care about when checking bound equality.
-    let trait_bounds = FxIndexSet::from_iter(trait_bounds.fold_with(&mut Anonymize { tcx }));
-    let impl_bounds = impl_bounds.fold_with(&mut Anonymize { tcx });
+    let trait_bounds = FxIndexSet::from_iter(trait_bounds.fold_with(&mut FullyAnonymize { tcx }));
+    let impl_bounds = impl_bounds.fold_with(&mut FullyAnonymize { tcx });

     // Find any clauses that are present in the impl's RPITITs that are not
     // present in the trait's RPITITs. This will trigger on trivial predicates,
@@ -415,11 +415,13 @@ fn type_visibility<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<ty::Visibili
     }
 }

-struct Anonymize<'tcx> {
+/// Contrary to [`TyCtxt::anonymize_bound_vars`] this anonymizes *all* binders and bound vars,
+/// not just the `Binder` and its bound vars that was provided as an argument.
+struct FullyAnonymize<'tcx> {
     tcx: TyCtxt<'tcx>,
 }

-impl<'tcx> TypeFolder<TyCtxt<'tcx>> for Anonymize<'tcx> {
+impl<'tcx> TypeFolder<TyCtxt<'tcx>> for FullyAnonymize<'tcx> {
     fn cx(&self) -> TyCtxt<'tcx> {
         self.tcx
     }
@@ -441,15 +443,11 @@ fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
     }

     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
-        let ty::RegionKind::ReBound(index, ty::BoundRegion { var, .. }) = r.kind() else {
-            return r;
-        };
-
-        match index {
-            ty::BoundVarIndexKind::Bound(debruijn) => {
-                ty::Region::new_anon_bound(self.tcx, debruijn, var)
-            }
-            ty::BoundVarIndexKind::Canonical => ty::Region::new_canonical_bound(self.tcx, var),
+        if let ty::RegionKind::ReBound(ty::BoundVarIndexKind::Bound(debruijn), bound_re) = r.kind()
+        {
+            ty::Region::new_anon_bound(self.tcx, debruijn, bound_re.var)
+        } else {
+            r
         }
     }

@@ -457,18 +455,11 @@ fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
         if !t.has_bound_vars() {
             return t;
         }
-
-        let ty::Bound(index, ty::BoundTy { var, .. }) = t.kind() else {
-            return t.super_fold_with(self);
-        };
-
-        match index {
-            ty::BoundVarIndexKind::Bound(debruijn) => Ty::new_bound(
-                self.tcx,
-                *debruijn,
-                ty::BoundTy { var: *var, kind: ty::BoundTyKind::Anon },
-            ),
-            ty::BoundVarIndexKind::Canonical => Ty::new_canonical_bound(self.tcx, *var),
+        if let ty::Bound(ty::BoundVarIndexKind::Bound(debruijn), bound_ty) = *t.kind() {
+            let bound_ty = ty::BoundTy { var: bound_ty.var, kind: ty::BoundTyKind::Anon };
+            Ty::new_bound(self.tcx, debruijn, bound_ty)
+        } else {
+            t.super_fold_with(self)
         }
     }

@@ -476,16 +467,10 @@ fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
         if !c.has_bound_vars() {
             return c;
         }
-
-        let ty::ConstKind::Bound(index, ty::BoundConst { var, .. }) = c.kind() else {
-            return c.super_fold_with(self);
-        };
-
-        match index {
-            ty::BoundVarIndexKind::Bound(debruijn) => {
-                ty::Const::new_anon_bound(self.tcx, debruijn, var)
-            }
-            ty::BoundVarIndexKind::Canonical => ty::Const::new_canonical_bound(self.tcx, var),
+        if let ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(debruijn), bound_ct) = c.kind() {
+            ty::Const::new_anon_bound(self.tcx, debruijn, bound_ct.var)
+        } else {
+            c.super_fold_with(self)
         }
     }
 }

(I can't apply it myself because you haven't granted other maintainers to edit your fork)

View changes since this review

Co-authored-by: León Orell Valerian Liehr <me@fmease.dev>
@mu001999

mu001999 commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

@fmease Thanks for the reviewing and all the explanations!

@bors r=fmease

@rust-bors

rust-bors Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

📌 Commit c08c7c6 has been tentatively approved by fmease

It will be put into the queue for this repository once PR CI succeeds.

@rust-bors rust-bors Bot added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Nov 6, 2026
JonathanBrouwer added a commit to JonathanBrouwer/rust that referenced this pull request Nov 6, 2026
Anonymize inner binders when checking refining

Fix rust-lang#165091

The inner binder is missed.
JonathanBrouwer added a commit to JonathanBrouwer/rust that referenced this pull request Nov 6, 2026
Anonymize inner binders when checking refining

Fix rust-lang#165091

The inner binder is missed.
rust-bors Bot pushed a commit that referenced this pull request Nov 6, 2026
…uwer

Rollup of 19 pull requests

Successful merges:

 - #164784 (Introduce OptimizationObjective and fix the entry shim's size attributes)
 - #165037 (Drop array elements in order after a partial move)
 - #165078 (Use the `2.38` binutils version in CI)
 - #159374 (Lower #[no_mangle] to #[symbol_name]/#[link_name])
 - #163284 (feat(Reborrow): Allow multiple lifetimes)
 - #164775 (Tweak output on misused `const` parameter to provide more context and more accurate suggestion)
 - #165194 (name elided lifetimes in `use<...>` suggestion when `impl Trait` params are present)
 - #165222 (Anonymize inner binders when checking refining)
 - #165335 (Fallible type ops)
 - #165388 (Accept variadic SysV64, Win64, and Aapcs FnAbis in rustc_public)
 - #165448 (Update `Vec::retain_unstable` docs to say that this method is generally faster than `Vec::retain_mut`)
 - #165494 (fix Miri ICE on exit with () return type)
 - #165503 (update Enzyme submodule)
 - #165505 (DFV: Reject `#[non_exhaustive]` on enum variants with default field values)
 - #165512 (Fix warnings for the L4Re targets)
 - #165514 (Remove unused `WhereEqPredicate` and `ScopeId` types)
 - #165518 (style-guide: Remove ABI explicitness prescription for extern items)
 - #165519 (Update books)
 - #165534 (rename MIR_borrow_checking timing scope to less confusing name)
rust-bors Bot pushed a commit that referenced this pull request Nov 7, 2026
Rollup of 15 pull requests

Successful merges:

 - #165037 (Drop array elements in order after a partial move)
 - #165550 (Make `Literal::cstr_value` return a `CString`)
 - #159374 (Lower #[no_mangle] to #[symbol_name]/#[link_name])
 - #163284 (feat(Reborrow): Allow multiple lifetimes)
 - #164775 (Tweak output on misused `const` parameter to provide more context and more accurate suggestion)
 - #165194 (name elided lifetimes in `use<...>` suggestion when `impl Trait` params are present)
 - #165222 (Anonymize inner binders when checking refining)
 - #165335 (Fallible type ops)
 - #165388 (Accept variadic SysV64, Win64, and Aapcs FnAbis in rustc_public)
 - #165448 (Update `Vec::retain_unstable` docs to say that this method is generally faster than `Vec::retain_mut`)
 - #165494 (fix Miri ICE on exit with () return type)
 - #165505 (DFV: Reject `#[non_exhaustive]` on enum variants with default field values)
 - #165512 (Fix warnings for the L4Re targets)
 - #165514 (Remove unused `WhereEqPredicate` and `ScopeId` types)
 - #165518 (style-guide: Remove ABI explicitness prescription for extern items)
@rust-bors
rust-bors Bot merged commit ca85e70 into rust-lang:main Nov 7, 2026
14 checks passed
@rustbot rustbot added this to the 1.101.0 milestone Nov 7, 2026
rust-bors Bot pushed a commit that referenced this pull request Nov 7, 2026
Rollup merge of #165222 - mu001999-contrib:fix-165091, r=fmease

Anonymize inner binders when checking refining

Fix #165091

The inner binder is missed.
RalfJung pushed a commit to JoJoDeveloping/miri that referenced this pull request Nov 8, 2026
Rollup of 15 pull requests

Successful merges:

 - rust-lang/rust#165037 (Drop array elements in order after a partial move)
 - rust-lang/rust#165550 (Make `Literal::cstr_value` return a `CString`)
 - rust-lang/rust#159374 (Lower #[no_mangle] to #[symbol_name]/#[link_name])
 - rust-lang/rust#163284 (feat(Reborrow): Allow multiple lifetimes)
 - rust-lang/rust#164775 (Tweak output on misused `const` parameter to provide more context and more accurate suggestion)
 - rust-lang/rust#165194 (name elided lifetimes in `use<...>` suggestion when `impl Trait` params are present)
 - rust-lang/rust#165222 (Anonymize inner binders when checking refining)
 - rust-lang/rust#165335 (Fallible type ops)
 - rust-lang/rust#165388 (Accept variadic SysV64, Win64, and Aapcs FnAbis in rustc_public)
 - rust-lang/rust#165448 (Update `Vec::retain_unstable` docs to say that this method is generally faster than `Vec::retain_mut`)
 - rust-lang/rust#165494 (fix Miri ICE on exit with () return type)
 - rust-lang/rust#165505 (DFV: Reject `#[non_exhaustive]` on enum variants with default field values)
 - rust-lang/rust#165512 (Fix warnings for the L4Re targets)
 - rust-lang/rust#165514 (Remove unused `WhereEqPredicate` and `ScopeId` types)
 - rust-lang/rust#165518 (style-guide: Remove ABI explicitness prescription for extern items)
@cuviper cuviper modified the milestones: 1.101.0, 1.102.0 Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refining_impl_trait lint false positive when nesting Fn inside impl Future

5 participants