Skip to content

Poor recovery from pub let x = ... #101622

@kpreid

Description

@kpreid

Given the following code:

fn main() {
    pub let x = 123;
}

The current output is:

error: visibility `pub` is not followed by an item
 --> src/main.rs:2:5
  |
2 |     pub let x = 123;
  |     ^^^ the visibility
  |
  = help: you likely meant to define an item, e.g., `pub fn foo() {}`

error: expected expression, found statement (`let`)
 --> src/main.rs:2:9
  |
2 |     pub let x = 123;
  |         ^^^^^^^^^^^
  |
  = note: variable declaration using `let` is a statement

error[E0658]: `let` expressions in this position are unstable
 --> src/main.rs:2:9
  |
2 |     pub let x = 123;
  |         ^^^^^^^^^^^
  |
  = note: see issue #53667 <https://github.com/rust-lang/rust/issues/53667> for more information

The latter two errors are redundant and confusing given the first. It seems like the compiler is trying to recover by parsing the tokens following pub as an expression, thus disallowing let, but there's no obvious reason to do that. whereas parsing them as a statement would be more useful and more analogous to the item syntax.

I propose one or both of the following improvements:

  • After encountering pub not followed by an item, try recovery by parsing as a statement, as if the pub token was absent. (This should be sufficient to produce only one, meaningful, error message in this situation.)
  • Detect pub let specifically, and suggest either let or pub static/const. (This might be part of a general improvement to handling confusion between items and statements — Provide a better error when code is put outside of a function #92615.)

Possible output would be:

error: visibility does not apply to `let` statements
 --> src/main.rs:2:5
  |
2 |     pub let x = 123;
  |     ^^^ the visibility
  |
  = help: remove the `pub`

rustc version: 1.63.0 stable. On nightly, a fourth error related to the let-expression interpretation is emitted.

Metadata

Metadata

Assignees

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