Skip to content

"if may be missing an else clause" sometimes reverses expectations #102397

Closed
@nox

Description

@nox

Given the following code:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5a939f14b1d92d9d4b3a3edbbb46f5c0

fn missing_else(x: i32) -> i32 {
    if true {
        return 1
    }
}

fn missing_else_nested(x: i32) -> i32 {
    if x < 0 {
        0
    } else {
        if true {
            return 1
        }
    }
}

The current output is:

error[E0317]: `if` may be missing an `else` clause
 --> src/lib.rs:2:5
  |
1 |   fn missing_else(x: i32) -> i32 {
  |                              --- expected `i32` because of this return type
2 | /     if true {
3 | |         return 1
4 | |     }
  | |_____^ expected `i32`, found `()`
  |
  = note: `if` expressions without `else` evaluate to `()`
  = help: consider adding an `else` block that evaluates to the expected type

error[E0317]: `if` may be missing an `else` clause
  --> src/lib.rs:11:9
   |
11 | /         if true {
12 | |             return 1
   | |             -------- found here
13 | |         }
   | |_________^ expected `()`, found `i32`
   |
   = note: `if` expressions without `else` evaluate to `()`
   = help: consider adding an `else` block that evaluates to the expected type

Note how the expected and found types are reversed for the missing_else_nested error and how the note about the function's return type is gone, compared to the missing_else error.

Ideally the output for the missing_else_nested error should be similar to the error for missing_else:

error[E0317]: `if` may be missing an `else` clause
  --> src/lib.rs:11:9
  |
7 |   fn missing_else_nested(x: i32) -> i32 {
  |                                     --- expected `i32` because of this return type
   |
11 | /         if true {
12 | |             return 1
   | |             -------- found here
13 | |         }
   | |_________^ expected `i32`, found `()`
   |
   = note: `if` expressions without `else` evaluate to `()`
   = help: consider adding an `else` block that evaluates to the expected type

This kinda duplicates #78656, but @estebank asked me to file a new issue on Twitter.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsD-papercutDiagnostics: An error or lint that needs small tweaks.T-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