Error message when definining enum using struct syntax

Although I know enums take to form of:

enum VecOrMap{
    Vec(Vec<usize>),
    Map(HashMap<String,usize>)
}

I sometimes find myself accidentally defining them as I would a struct:

enum VecOrMap{
    vec: Vec<usize>,
    map: HashMap<String,usize>
}

in these cases, the error of

expected one of `(`, `,`, `=`, `{`, or `}`, found `:`

always takes more than a few seconds to parse and then realize my mistake. Is it possible to change this to something like:

Looks like you are trying to define and enum using struct syntax, change `vec: Vec<usize>` to `Vec(Vec<usize>)`

Hopefully this type of feedback is useful!

edit: formatting

5 Likes

This is definitely a form which the compiler could recognize to provide a better error for. Please open a GitHub issue — there's a template and category specifically for error message quality that this would fit perfectly in :slight_smile:

12 Likes

Definitely file bugs when you hit things like this.

Personally, I think that whenever there's an "expected one of" message without a help: message, it's a good bug, as a great place for a quick syntax reminder. Sketch:

error: expected one of `(`, `,`, `=`, `{`, or `}`, found `:`
 --> src/lib.rs:2:8
  |
2 |     vec: Vec<usize>,
  |        ^ expected one of `(`, `,`, `=`, `{`, or `}`
  |
  | help: enum variants are either `Variant(Type)` or `Variant { field: Type }`
1 Like

I wonder if instead of these fairly opaque "error: expected <tokens>, found <token>" messages, the parser could print some representation of the full list of productions it is trying to match, something like:

error: expected one of
    vec
    vec = <integer>
    vec(...)
    vec { ... }

I guess finding a good balance between user-friendliness, terseness and precision would be tricky. Full EBNF would of course be the most precise, but verbose and possibly unfamiliar to many.

3 Likes

Thanks all for the discussion, I'm including a link to the github issue for convenience https://github.com/rust-lang/rust/issues/103869

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.