Skip to content

Compiler should offer suggestions from other implemented traits when methods aren't found #7643

Closed
@chris-morgan

Description

@chris-morgan

Explanation of the problem

Here is some sample code:

struct Foo;

impl Foo {
    fn foo(&mut self, buf: &[u8]) {
        self.write(buf);
    }
}

impl std::rt::io::Writer for Foo {
    fn write(&mut self, buf: &[u8]) {
    }

    fn flush(&mut self) {
    }
}

fn main() {
}

Expected (by me) behaviour: code should compile happily.

Actual behaviour: well, here is the compiler's opinion of this code:

foo.rs:5:8: 5:24 error: type `&mut Foo` does not implement any method in scope named `write`
foo.rs:5         self.write(buf);
                 ^~~~~~~~~~~~~~~~
error: aborting due to previous error

First thought: huh? But I implemented that method just there, see?

If I add use std::rt::io::Writer; to the top of the file, it will work. This is, as I now realise, because only traits used in the current scope are searched for a matching method; this is a necessary evil, lest such things as conflicts arise, yet it need not be this evil, where it gives no real indication of the problem (sure, the "in scope" bit hints obliquely at the problem, but not at all clearly).

Now, what should be done

In such a case, where a method is not found in the current scope, the compiler should scan all impl blocks that it knows about for that type and see if it can find any that matches the description, and then suggest them (hopefully it).

For example, the error message might then read

error: type &mut Foo does not implement any method in scope named write; you probably want to use std::rt::io::Writer;

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-trait-systemArea: Trait systemE-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions