Allow omitting commas in enum variant structs

For punctuation-separated sequences, most of the time Rust does not require punctuation when {} is used. For example:

expr; // Semicolon required
{ expr; } // No semicolon required

match expr {
    () => (), // Comma required
    () => {} // No comma required
    _ => {}
}

struct X; // Semicolon required
struct X(i32); // Semicolon required
struct X { x: i32 } // No semicolon required

Therefore I find it somewhat inconsistent that commas are required even when using {} in enum declarations:

enum X {
    A, // Comma required
    B(i32), // Comma required
    C { x: i32 }, // Comma required
    D,
}

This has tripped me up many times recently, and I think it would be nice if the syntax for enums could be brought to be more inline with the rest of the language.

Obviously this has downsides:

  • Churn: if the rustfmt defaults change that would render lots of current Rust code incorrectly formatted. To avoid the churn this could be released as part of 2021 edition.
  • Parsing difficultly: it makes parsing enum declarations harder as not everything is separated by commas.

And I don't know whether this even bothers anyone else other than me, so I'd like to hear your experiences with that.

My default answer is that this is the place for a nice structured suggestion from the compiler, not a grammar change.

It looks like the error message is already

4 |     C { x: i32 }
  |                 -
  |                 |
  |                 help: missing `,`

And there's seemingly a recovery implemented in the parser, as it continues to parse the rest of the file without issue (including errors from the rest of the file).

I'd tweak the "parsing difficulty" bullet a bit. Just supporting this in rustc is no big deal. A more troubling churn from it, though, is that all the proc macros that parse struct definitions would need to start parsing it.

So I overall feel like the change isn't worth it, especially if it has a nice structured suggestion so it's easy to apply even in a not-really-a-full IDE like sublime text (let alone using something fancier like rust-analyzer, which can probably just offer the "you want this fixed right?" essentially as soon as you've started typing the next variant).

EDIT: A related conversation: RFC: Accept semicolons as item-like by Centril · Pull Request #2479 · rust-lang/rfcs · GitHub

11 Likes

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