rust-lang / rust-lang/rust-analyzer

Wrong `try_into` for enum variant if `Result` is shadowed

Open
#16,504 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-assists C-bug
Dominant language
Rust
Stars
16.9k
Forks
2.2k
Avg merge
1d 12h
Merged PRs (30d)
72

Description

If std::result::Result is shadowed, the "Generate a try_into_ method for this enum variant" code action produces a wrong return type.

Setup

There is a Result type which shadows the std::result::Result from the prelude.

The "Generate a try_into_ method for this enum variant" code action produces wrong code, because it uses the Result type instead of StdResult.

The "Implement missing members" code action for the FromStr trait does correctly use StdResult.

use std::{result::Result as StdResult, str::FromStr};

pub type Result<T> = StdResult<T, ()>;

enum A {
    B(String),
}

// --- code below is generated ---

impl A {
    fn try_into_b(self) -> Result<String, Self> {
        if let Self::B(v) = self {
            Ok(v)
        } else {
            Err(self)
        }
    }
}

impl FromStr for A {
    type Err;

    fn from_str(s: &str) -> StdResult<Self, Self::Err> {
        todo!()
    }
}

Versions

rust-analyzer version: 0.3.1831-standalone

rustc version: rustc 1.75.0 (82e1608df 2023-12-21)

relevant settings: none


Thanks to @japaric for finding.

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 locating the implementation of the “Generate a try_into_ method for this enum variant” code action and compare it with the FromStr “Implement missing members” action described in the issue. Reproduce the shadowed-Result example, then verify that the generated return type remains the standard Result and add regression coverage for the case.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.