Skip to content

Rust: Apply inherent method prioritization inside type inference loop #19903

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 2 commits into
base: main
Choose a base branch
from

Conversation

hvitved
Copy link
Contributor

@hvitved hvitved commented Jun 27, 2025

Inherent methods are prioritized over trait methods:

trait Trait {
    fn method(&self) -> i32;
}

struct S;

impl S {
    fn method(&self) -> i32 { // <-- inherent method
        0
    }
}

impl Trait for S {
    fn method(&self) -> i32 { // <-- trait method
        0
    }
}

fn f(S s) {
    s.method(); // <-- calls inherent method
}

Previously, this prioritization was applied after the recursive type inference loop, because it involved a negative call to the method resolution (and hence type inference) relation.

However, as the added test case shows, this may lead to an explosion in inferred types, when the type signatures of the inherent/trait methods differ. This PR hence moves the restriction into the type inference loop, but in order to avoid non-monotonic recursion, we formulate the restriction as a monotonic property: A trait method only applies when all potential inherent targets have a receiver type that it not an instance of the impl type (the non-monotonic version is: there is no receiver type that is an instance of the impl type).

@github-actions github-actions bot added the Rust Pull requests that update Rust code label Jun 27, 2025
@hvitved hvitved force-pushed the rust/type-inference-overlap2 branch 2 times, most recently from 69e2f41 to 10a6897 Compare June 27, 2025 12:10
@hvitved hvitved force-pushed the rust/type-inference-overlap2 branch from 10a6897 to 84f3f8c Compare June 27, 2025 12:37
@hvitved hvitved added the no-change-note-required This PR does not need a change note label Jun 30, 2025
@hvitved hvitved marked this pull request as ready for review June 30, 2025 07:20
@Copilot Copilot AI review requested due to automatic review settings June 30, 2025 07:20
@hvitved hvitved requested a review from a team as a code owner June 30, 2025 07:20
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-change-note-required This PR does not need a change note Rust Pull requests that update Rust code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant