Skip to content

Better diagnostics for missing iterator in for-loop #78537

Closed
@jyn514

Description

@jyn514

Spot the bug:

fn f() -> usize {
    for i in {
        println!("{}", i);
    }
    1
}

Unfortunately, instead of pointing to the missing iterator, rust points to the 1:

error: expected `{`, found `1`
 --> src/lib.rs:5:5
  |
5 |     1
  |     ^
  |     |
  |     expected `{`
  |     help: try placing this code inside a block: `{ 1 }`

I'd love it to instead say 'missing iterator for loop':

error: expected iterator, found block
 --> src/lib.rs
  |
2 |    for i in {
  |             ^ this starts a block expression ...
5 |     1
  |     ^ ... so there is no body for the loop
  =     help: try adding an iterator to the for-loop: `for i in iter {`

Other variants of this with less than ideal errors:

fn f() {
    for i in {
        println!("{}", i);
    }
}
error: expected `{`, found `}`
 --> src/lib.rs:5:1
  |
5 | }
  | ^ expected `{`
fn f() -> usize {
    for i in {
        println!("{}", i);
    }
    return 1;
}
error: expected `{`, found keyword `return`
 --> src/lib.rs:5:5
  |
5 |     return 1;
  |     ^^^^^^---
  |     |
  |     expected `{`
  |     help: try placing this code inside a block: `{ return 1; }`

Metadata

Metadata

Assignees

Labels

A-control-flowArea: Control flowA-diagnosticsArea: Messages for errors, warnings, and lintsA-parserArea: The lexing & parsing of Rust source code to an ASTC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-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