Skip to content

Add diagnostic hint when or-ing values which may be missing an equality comparison #128132

Open
@illicitonion

Description

@illicitonion

Code

fn main() {
    let x = 1;
    if x == 1 || 2 {
        println!("Was 1 or 2");
    }
}

Current output

error[E0308]: mismatched types
 --> src/main.rs:3:18
  |
3 |     if x == 1 || 2 {
  |        ------    ^ expected `bool`, found integer
  |        |
  |        expected because this is `bool`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `rustplay` (bin "rustplay") due to 1 previous error

Desired output

error[E0308]: mismatched types
 --> src/main.rs:3:18
  |
3 |     if x == 1 || 2 {
  |        ------    ^ expected `bool`, found integer
  |        |
  |        expected because this is `bool`
  |
  |  note: If you're trying to check whether x is one of several values,
  |        you need to repeat the `x ==` check for each possible value.
  |
  |  hint: Try `if x == 1 || x == 2 {`.

For more information about this error, try `rustc --explain E0308`.
error: could not compile `rustplay` (bin "rustplay") due to 1 previous error

Rationale and extra context

I teach people software engineering who don't have a software engineering background, and have noticed that a surprising number of people try to write this kind of code (perhaps because in their head they're thinking "I need to check if x is 1 or 2" and "||" translates directly to "or", where in reality they need to be thinking "I need to check if x is 1 or x is 2".

This has come up often enough that I think it would be a useful hint to provide - as things stand, I haven't found a really easy way of guiding people to make this realisation themself other than just telling them, so the compiler hinting it to them feels useful.

It feels like this could be useful to trigger in any condition (i.e. place expecting a boolean) where:

  1. There is at least one ||
  2. The first LHS of a || is an == (or possibly != comparison)
  3. Every type on the RHS of a || has a type which is comparable to the LHS of the first == (or perhaps, has the same type as the RHS of the first ==)

Other cases

No response

Rust Version

rustc 1.79.0 (129f3b996 2024-06-10)
binary: rustc
commit-hash: 129f3b9964af4d4a709d1383930ade12dfe7c081
commit-date: 2024-06-10
host: aarch64-apple-darwin
release: 1.79.0
LLVM version: 18.1.7

Anything else?

No response

Metadata

Metadata

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-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