rust-lang / rust-lang/rust

do not suggest changing function signature in trait impls when it matches the one from `Trait` itself

Open
#146,519 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Code
struct Keyword<'a>(&'a str);

struct InvalidKeyword;

impl<'a> std::str::FromStr for Keyword<'a> {
    type Err = InvalidKeyword;
    fn from_str<'b>(s: &'b str) -> Result<Self, Self::Err> {
        // ^ Error: lifetime 'b may not live long enough. Consider adding 'b : 'a here.
        if matches!(s, "let" | "fn" | "struct") {
            Ok(Keyword(s))
        } else {
            Err(InvalidKeyword)
        }
    }
}
Current output
error: lifetime may not live long enough
  --> src/lib.rs:10:13
   |
5  | impl<'a> std::str::FromStr for Keyword<'a> {
   |      -- lifetime `'a` defined here
6  |     type Err = InvalidKeyword;
7  |     fn from_str<'b>(s: &'b str) -> Result<Self, Self::Err> {
   |                 -- lifetime `'b` defined here
...
10 |             Ok(Keyword(s))
   |             ^^^^^^^^^^^^^^ associated function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b`
   |
   = help: consider adding the following bound: `'b: 'a`

error: could not compile `playground` (lib) due to 1 previous error
Desired output
The same output but without help: consider adding the following bound: `'b: 'a`.
Rationale and extra context

I think its more important to ensure that impl Trait matches signature defined in trait itself then it is to suggest fix to user's code.

This fix would be always wrong unless trait itself is defined in current crate in which case this suggestion should be applied.

Other cases

Rust Version
rustc 1.91.0-nightly
Anything else?

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by compiling the minimal Rust reproduction from the issue and compare the current diagnostic with the desired output. Trace the compiler diagnostic path that emits the lifetime-bound help for trait implementations, then verify that the suggestion is omitted when the signature comes from the implemented trait while preserving the stated behavior for locally defined traits.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.