rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
98.51k stars 12.73k forks source link

Look for available `const`s when typoing pattern #132582

Open estebank opened 1 week ago

estebank commented 1 week ago

Code

fn main() {
    let input: i32 = 42;

    const GOOD: i32 = 1;
    const BAD: i32 = 2;

    match input {
        GOD => println!("input was 1"), //~ WARN
        otherwise => println!("input was {otherwise}"),
    }
}

Current output

warning: unreachable pattern
 --> src/main.rs:9:6
  |
8 |         GOD => println!("input was 1"),
  |         --- matches any value
9 |         otherwise => println!("input was {otherwise}"),
  |         ^^^^^^^^^ no value can reach this
  |
  = note: `#[warn(unreachable_patterns)]` on by default

warning: unused variable: `GOD`
 --> src/main.rs:8:6
  |
8 |         GOD => println!("input was 1"),
  |         ^^^ help: if this is intentional, prefix it with an underscore: `_GOD`
  |
  = note: `#[warn(unused_variables)]` on by default

warning: constant `GOOD` is never used
 --> src/main.rs:4:11
  |
4 |     const GOOD: i32 = 1;
  |           ^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: constant `BAD` is never used
 --> src/main.rs:5:11
  |
5 |     const BAD: i32 = 2;
  |           ^^^

warning: variable `GOD` should have a snake case name
 --> src/main.rs:8:6
  |
8 |         GOD => println!("input was 1"),
  |         ^^^ help: convert the identifier to snake case: `god`
  |
  = note: `#[warn(non_snake_case)]` on by default

Desired output

warning: unreachable pattern
 --> src/main.rs:9:6
  |
8 |         GOD => println!("input was 1"),
  |         --- matches any value
9 |         otherwise => println!("input was {otherwise}"),
  |         ^^^^^^^^^ no value can reach this
  |
  = note: `#[warn(unreachable_patterns)]` on by default
note: `GOD` looks similar to constant `GOOD`
  |
4 |     const GOOD: i32 = 1;
  |           ^^^^
help: you might have meant to pattern match on the value of the constant `GOOD`
  |
8 |         GOOD => println!("input was 1"),
  |         ~~~~

Rationale and extra context

No response

Other cases

We should also account for uppercase to lowercase changes, beyond just levenshtein distance.

Rust Version

current

Anything else?

No response

jieyouxu commented 1 week ago

Maybe cc https://github.com/rust-lang/rust/issues/25207, https://github.com/rust-lang/rust/issues/40476, https://github.com/rust-lang/rust/issues/39371 and https://github.com/rust-lang/rust/issues/121704.