Skip to content

Misleading error message in case of ambiguous if blocks #51311

Closed
@vandenheuvel

Description

@vandenheuvel

For the following code, the compiler generates error E0423 on both stable and nightly in the playground:

fn main() {
    let x = MyType { y: 1, };
    
    // Fails
    if x == MyType { y: 1, } {
    }
    // Is ok
    if x == (MyType { y: 1, }) {
    }
}

#[derive(Eq, PartialEq)]
struct MyType {
    y: u64,
}
error: expected type, found `1`
 --> src/main.rs:5:25
  |
5 |     if x == MyType { y: 1, } {
  |                         ^ expecting a type here because of type ascription

error[E0423]: expected value, found struct `MyType`
 --> src/main.rs:5:13
  |
5 |     if x == MyType { y: 1, } {
  |             ^^^^^^ did you mean `MyType { /* fields */ }`?

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0423`.

I learned that there is a parsing ambiguity in the if-statement which fails to compile. But rather than producing an error message explaining this ambiguity, the compiler seems to assume one of the possibilities ("the first accolade belongs to the if-statement") and proceeds, encounting the error E0423 which it then displays.

It seems preferable for the compiler to stop at the point of encounting the ambiguity, with an error message explaining the problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions