rustfmt
rustfmt copied to clipboard
use_field_init_shorthand option breaks numbered struct field initialization
If I have a struct type with an implicit field such as
struct MyStruct(u64);
And I attempt to initialize it to 0
let instance = MyStruct { 0: 0 };
With the option "use_field_init_shorthand = true", rustfmt will incorrectly shorten the initialization to:
let instance = MyStruct { 0 };
This code will no longer compile after running rustfmt.
Is there any reason in particular you're trying to initialize it that way instead of the more canonical:
let instance = MyStruct(0);
The other way is valid syntax of course and we should probably adjust the rule to handle this, but with a tuple struct you'd typically see the aforementioned syntax instead.
For anyone interested in working on this, think you'll probably want to start around the below. Likely just need to enhance the check to not fall into the shorthand mode if the field name is itself an invalid ident (e.g. 0)
https://github.com/rust-lang/rustfmt/blob/e041c20eed3eecc1f29468c19877d7a05ac576bc/src/expr.rs#L1721-L1723
Is there any reason in particular you're trying to initialize it that way instead of the more canonical:
let instance = MyStruct(0);The other way is valid syntax of course and we should probably adjust the rule to handle this, but with a tuple struct you'd typically see the aforementioned syntax instead.
Ignorance! The syntax I was using worked even though it felt clumsy. Of course there’s a better way and now I know. Glad I could identify the issue though.
No worries, and thanks for bringing it to our attention! It's something we should handle anyway, so better we know than not know and fortunately there's a readily available (and more idiomatic) option for folks in the interim
@rustbot claim
Hi @calebcartwright, just wanted to validate the expectation here before implementing the fix and was hoping you could help. AFAIU if the name of the field is any literal (i.e. numeric values, quoted strings, etc.), we want to avoid falling into the short-hand mode?
If the above is true, I am thinking of validating the ExprKind of P<Expr> contained within ExprField by checking if it is a literal (e.g. 0 in the above example). If it returns true, we do not fall in the short-hand mode, otherwise we follow the current code flow.
Please let me know if I am overcomplicating or have missed something obvious.