Skip to content

Diagnostic for CandidateSource::Trait take receiver as first arg mistakely #119775

Closed
@Young-Flash

Description

@Young-Flash

Code

struct A {}

trait M {
    fn new(a: Self);
}
impl M for A {
    fn new(a: Self) {
        todo!()
    }
}

fn main() {
    let a = A {};
    a.new();
}

Current output

error[E0599]: no method named `new` found for struct `A` in the current scope
  --> src/main.rs:28:7
   |
15 | struct A {}
   | -------- method `new` not found for this struct
...
28 |     a.new();
   |     --^^^--
   |     | |
   |     | this is an associated function, not a method
   |     help: use associated function syntax instead: `A::new()`
   |
   = note: found the following associated functions; to be used as methods, functions must have a `self` parameter
note: the candidate is defined in the trait `M`
  --> src/main.rs:18:5
   |
18 |     fn new(a: Self);
   |     ^^^^^^^^^^^^^^^^
   = help: items from traits can only be used if the trait is implemented and in scope

Desired output

A::new(a)

Rationale and extra context

We had solved CandidateSource::Impl case in #118502, could do the same for CandidateSource::Trait

let first_arg = if let Some(CandidateSource::Impl(impl_did)) = static_candidates.get(0)
&& let Some(assoc) = self.associated_value(*impl_did, item_name)
&& assoc.kind == ty::AssocKind::Fn
{
let sig = self.tcx.fn_sig(assoc.def_id).instantiate_identity();
sig.inputs().skip_binder().get(0).and_then(|first| {
let impl_ty = self.tcx.type_of(*impl_did).instantiate_identity();
// if the type of first arg is the same as the current impl type, we should take the first arg into assoc function
if first.peel_refs() == impl_ty {
Some(first.ref_mutability().map_or("", |mutbl| mutbl.ref_prefix_str()))
} else {
None
}
})
} else {
None
};

Other cases

No response

Rust Version

rustc 1.76.0-nightly (ba7c7a301 2023-11-13)
binary: rustc
commit-hash: ba7c7a301984967c8c13adb580ef9b86ba706a83
commit-date: 2023-11-13
host: x86_64-unknown-linux-gnu
release: 1.76.0-nightly
LLVM version: 17.0.4

Anything else?

No response

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions