Open
Description
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 thepub
token was absent. (This should be sufficient to produce only one, meaningful, error message in this situation.) - Detect
pub let
specifically, and suggest eitherlet
orpub 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.