Skip to content

Make sure to treat only param where clauses as inherent #145262

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

compiler-errors
Copy link
Member

@compiler-errors compiler-errors commented Aug 11, 2025

See the description in the test file.

This PR fixes a bug introduced by #141333, where we considered non-Param where clauses to be "inherent" for the purpose of method probing, which leads to both changes in method ambiguity (see test) and also import usage linting (and thus fixes #145185).

r? @lcnr

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Aug 11, 2025
@@ -1945,6 +1945,29 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
);
(xform_self_ty, xform_ret_ty) =
self.xform_self_ty(probe.item, trait_ref.self_ty(), trait_ref.args);

if matches!(probe.kind, WhereClauseCandidate(_)) {
Copy link
Member Author

Choose a reason for hiding this comment

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

We could fast path this for the old trait solver, since we expect things to be normalized always.

Copy link
Contributor

@lcnr lcnr Aug 12, 2025

Choose a reason for hiding this comment

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

hm 🤔

so what's going on is:

  • if the normalized self type is a param we assemble_inherent_candidates_from_param
  • this uses fast-reject in an attempt to filter to where-clauses which only apply for the self type
    • doesn't handle unnormalized where-clauses or alias self types

We can't normalize in assembly because it doesn't use a probe, so we instead do it here. This totally makes sense to me, r=me on this impl

Can you add a comment to assemble_inherent_candidates_from_param that we only filter the bounds as an fast-path optimization and we properly reject non-param self type where-clauses in consider_probe?

Copy link
Contributor

Choose a reason for hiding this comment

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

actually, move this structurally_normalize_ty above the xform and then use the normalized ty in xform_self_ty? This should avoid some work given that this change seems to actually impact perf in the new solver

@compiler-errors
Copy link
Member Author

@bors2 try @rust-timer queue

I also want to crater this since it may cause some code to fail due to new ambiguity and missing imports.

@rust-timer

This comment has been minimized.

@rust-bors

This comment has been minimized.

rust-bors bot added a commit that referenced this pull request Aug 11, 2025
Make sure to treat only param where clauses as inherent
@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Aug 11, 2025
@rust-bors
Copy link

rust-bors bot commented Aug 11, 2025

☀️ Try build successful (CI)
Build commit: 987a165 (987a165cfab916796a8315782b83ac460a651ce2, parent: fce0e74720d199eb7839fdb51af35ac5226da178)

@rust-timer

This comment has been minimized.

@rust-timer
Copy link
Collaborator

Finished benchmarking commit (987a165): comparison URL.

Overall result: ❌✅ regressions and improvements - please read the text below

Benchmarking this pull request means it may be perf-sensitive – we'll automatically label it not fit for rolling up. You can override this, but we strongly advise not to, due to possible changes in compiler perf.

Next Steps: If you can justify the regressions found in this try perf run, please do so in sufficient writing along with @rustbot label: +perf-regression-triaged. If not, please fix the regressions and do another perf run. If its results are neutral or positive, the label will be automatically removed.

@bors rollup=never
@rustbot label: -S-waiting-on-perf +perf-regression

Instruction count

Our most reliable metric. Used to determine the overall result above. However, even this metric can be noisy.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
0.0% [0.0%, 0.0%] 1
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-0.9% [-1.6%, -0.1%] 5
All ❌✅ (primary) - - 0

Max RSS (memory usage)

Results (primary 1.2%, secondary -2.6%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
1.2% [1.2%, 1.2%] 1
Regressions ❌
(secondary)
2.0% [2.0%, 2.0%] 1
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-3.8% [-4.5%, -2.6%] 4
All ❌✅ (primary) 1.2% [1.2%, 1.2%] 1

Cycles

Results (secondary 3.6%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
6.7% [6.2%, 7.1%] 2
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-2.6% [-2.6%, -2.6%] 1
All ❌✅ (primary) - - 0

Binary size

This benchmark run did not return any relevant results for this metric.

Bootstrap: 464.993s -> 463.982s (-0.22%)
Artifact size: 377.36 MiB -> 377.47 MiB (0.03%)

@rustbot rustbot added perf-regression Performance regression. and removed S-waiting-on-perf Status: Waiting on a perf run to be completed. labels Aug 11, 2025
@compiler-errors
Copy link
Member Author

@craterbot check

@craterbot
Copy link
Collaborator

👌 Experiment pr-145262 created and queued.
🤖 Automatically detected try build 987a165
🔍 You can check out the queue and this experiment's details.

ℹ️ Crater is a tool to run experiments across parts of the Rust ecosystem. Learn more

@craterbot craterbot added S-waiting-on-crater Status: Waiting on a crater run to be completed. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Aug 11, 2025
@compiler-errors
Copy link
Member Author

0.0% perf regression is definitely important good job perfbot 👍

@theemathas
Copy link
Contributor

This code compiles on 1.89.0. But it doesn't compile on 1.88.0, and doesn't compile with this PR. Is this intended? I don't think the test checks for this case properly.

pub mod module {
    pub trait Trait {
        fn method(&self);
    }
}

// No import of Trait
use std::ops::Deref;

pub fn foo(x: impl Deref<Target: module::Trait>) {
    x.method();
}

@compiler-errors
Copy link
Member Author

compiler-errors commented Aug 12, 2025

This code compiles on 1.89.0. But it doesn't compile on 1.88.0, and doesn't compile with this PR. Is this intended?

Yes, this is intended breakage.

The whole point of this PR is that there was a regression in 1.89 where we were accepting code that we shouldn't have. As a side effect, this regression also affects how we compute the lint for unused imports, but that's kinda the least important part of this PR.

This is the whole point of the crater run I started. I'd like to ensure that nobody is relying on this behavior.

I don't think the test checks for this case properly.

The test I included is effectively equivalent to that one, since they are both originating from the same root cause around how we treat where clauses from param types specially in method selection. Both the test I included and the one you've shared go from fail (1.88) -> pass (1.89) -> fail (this PR).

@traviscross traviscross added T-lang Relevant to the language team and removed T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Aug 12, 2025
@traviscross
Copy link
Contributor

traviscross commented Aug 12, 2025

Given that there was an accidental stabilization here and that we'll be accepting a breaking change to take it back, let's go ahead and nominate for review.

@rustbot labels +I-lang-nominated

It hasn't been out there long, but it is particularly the kind of thing that would be easy for people to unknowingly rely on.

In fact, I'm going to go ahead kick off the proposed FCP because I don't suspect the crater run is going to tell us very much. The release has been out for less than a week. Most of the people who are going to accidentally rely on this probably haven't done so yet1 -- they'll do it after we land this but before we release it and they adopt that release.

@rfcbot fcp merge

Footnotes

  1. And if they have, they probably haven't released it yet.

@rfcbot
Copy link
Collaborator

rfcbot commented Aug 12, 2025

Team member @traviscross has proposed to merge this. The next step is review by the rest of the tagged team members:

No concerns currently listed.

Once a majority of reviewers approve (and at most 2 approvals are outstanding), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up!

cc @rust-lang/lang-advisors: FCP proposed for lang, please feel free to register concerns.
See this document for info about what commands tagged team members can give me.

@rfcbot rfcbot added the proposed-final-comment-period Proposed to merge/close by relevant subteam, see T-<team> label. Will enter FCP once signed off. label Aug 12, 2025
@rustbot rustbot added the I-lang-nominated Nominated for discussion during a lang team meeting. label Aug 12, 2025
@rfcbot rfcbot added the disposition-merge This issue / PR is in PFCP or FCP with a disposition to merge it. label Aug 12, 2025
@traviscross traviscross added the needs-fcp This change is insta-stable, or significant enough to need a team FCP to proceed. label Aug 12, 2025
@traviscross
Copy link
Contributor

Interestingly, the accidental stabilization didn't cause all non-param WCs to be treated as "inherent". I'd be curious to know what defined the exact edges of this. E.g.:

use core::ops::Deref;
mod m {
    pub trait TrA { fn f(&self); }
}

fn g1<T: Deref<Target: m::TrA> + Deref<Target = U>, U>(x: &T::Target) {
    x.f(); //~ OK
}

fn g2<T: Deref<Target: m::TrA>>(x: &T::Target) {
    x.f();//~ ERROR
}

fn g3<T: Deref<Target: m::TrA> + Deref<Target = U>, U>(x: T) {
    x.f(); //~ OK
}

fn g4<T: Deref<Target: m::TrA>>(x: T) {
    x.f(); //[v1.89]~ OK
}

One would kind of expect g2 to be accepted under the same reasoning that g4 is, but it's not.

@compiler-errors
Copy link
Member Author

compiler-errors commented Aug 12, 2025

It's just autoderefs that start from param types that are treated as inherent. In g2, we do not start with a param type and deref it.

In g1 and g3, those are both inherent because we end up just with a bound on U.

@traviscross
Copy link
Contributor

Thanks, makes sense.

Neither here nor there as far as this issue goes, but it made me contemplate that one can induce inherent treatment of a trait method (in any version) with an irrelevant use of APIT, e.g.:

use core::ops::Deref;
trait Any {}
impl<T: ?Sized> Any for T {}
mod m { pub trait TrA { fn f(&self); } }
fn g5<T: Deref<Target: m::TrA> + Deref<Target = impl Any>>(x: &T::Target) {
    x.f(); //~ OK
}

I understand why that is, but it's pretty odd. It's been on my mind to maybe try to do something about this sort of thing, e.g. by indeed expanding our "inherent" treatment to non-param WC bounds. But, of course, if we do, we should do so intentionally.

@traviscross traviscross added the P-lang-drag-0 Lang team prioritization drag level 0.https://rust-lang.zulipchat.com/#narrow/channel/410516-t-lang. label Aug 12, 2025
Copy link
Contributor

@lcnr lcnr left a comment

Choose a reason for hiding this comment

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

This code compiles on 1.89.0. But it doesn't compile on 1.88.0, and doesn't compile with this PR. Is this intended? I don't think the test checks for this case properly.

pub mod module {
    pub trait Trait {
        fn method(&self);
    }
}

// No import of Trait
use std::ops::Deref;

pub fn foo(x: impl Deref<Target: module::Trait>) {
    x.method();
}

I would personally like to see this test in our test suite as well. It feels clearer to me what this is testing compared to relying on preference between candidates 🤔

// an "extension" candidate like `<T as Deref>::Target: Trait2` even though it holds.
// This is problematic, since it causes ambiguities to be broken somewhat arbitrarily.
// And as a side-effect, it also caused our computation of "used" traits to be miscalculated
// since inherent candidates don't count as an import usage.
Copy link
Contributor

Choose a reason for hiding this comment

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

also test with new solver?

@@ -1945,6 +1945,29 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
);
(xform_self_ty, xform_ret_ty) =
self.xform_self_ty(probe.item, trait_ref.self_ty(), trait_ref.args);

if matches!(probe.kind, WhereClauseCandidate(_)) {
Copy link
Contributor

@lcnr lcnr Aug 12, 2025

Choose a reason for hiding this comment

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

hm 🤔

so what's going on is:

  • if the normalized self type is a param we assemble_inherent_candidates_from_param
  • this uses fast-reject in an attempt to filter to where-clauses which only apply for the self type
    • doesn't handle unnormalized where-clauses or alias self types

We can't normalize in assembly because it doesn't use a probe, so we instead do it here. This totally makes sense to me, r=me on this impl

Can you add a comment to assemble_inherent_candidates_from_param that we only filter the bounds as an fast-path optimization and we properly reject non-param self type where-clauses in consider_probe?

@lcnr lcnr added the T-types Relevant to the types team, which will review and decide on the PR/issue. label Aug 12, 2025
@lcnr
Copy link
Contributor

lcnr commented Aug 12, 2025

As a procedural comment, I believe the types team should have been involved in the FCP.

I personally would have liked to have it be fully the responsibility of the types team given that it's a subtle detail/bug of the method selection/type checking. But it does feel user facing enough that I think T-lang also being involved is correct.

I don't think this change is significant or contentious enough to necessarily require a new FCP, so this comment only serves as a "I don't want the T-types to lose ownership of method selection going forward".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
disposition-merge This issue / PR is in PFCP or FCP with a disposition to merge it. I-lang-nominated Nominated for discussion during a lang team meeting. needs-fcp This change is insta-stable, or significant enough to need a team FCP to proceed. P-lang-drag-0 Lang team prioritization drag level 0.https://rust-lang.zulipchat.com/#narrow/channel/410516-t-lang. perf-regression Performance regression. proposed-final-comment-period Proposed to merge/close by relevant subteam, see T-<team> label. Will enter FCP once signed off. S-waiting-on-crater Status: Waiting on a crater run to be completed. T-lang Relevant to the language team T-types Relevant to the types team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Latest rustc tags unused_imports on trait imports spuriously
8 participants