Skip to content

Commit

Permalink
Fix rust-lang#5488 - prevent shorthand init for tuple struct
Browse files Browse the repository at this point in the history
Closes rust-lang#5488

Fix for rust-lang#5488. Before applying shorthand initialization for structs,
check if identifier is a literal (e.g. tuple struct). If yes, then do
not apply short hand initialization.

Added test case to validate the changes for the fix.
  • Loading branch information
RajivTS committed Aug 27, 2022
1 parent 38659ec commit 8386bed
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1716,12 +1716,19 @@ pub(crate) fn rewrite_field(
let overhead = name.len() + separator.len();
let expr_shape = shape.offset_left(overhead)?;
let expr = field.expr.rewrite(context, expr_shape);

match expr {
Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
Some(attrs_str + name)
Some(ref e) => {
let is_lit = if let ast::ExprKind::Lit(_) = (*field.expr).kind {
true
} else {
false
};
if !is_lit && e.as_str() == name && context.config.use_field_init_shorthand() {
Some(attrs_str + name)
} else {
Some(format!("{}{}{}{}", attrs_str, name, separator, e))
}
}
Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
None => {
let expr_offset = shape.indent.block_indent(context.config);
let expr = field
Expand Down
11 changes: 11 additions & 0 deletions tests/source/issue-5488.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// rustfmt-use_field_init_shorthand: true
fn main() {
// Since MyStruct is a tuple struct, it should not be shorthanded to
// MyStruct { 0 } even if use_field_init_shorthand is enabled.
let instance = MyStruct { 0: 0 };

// Since AnotherStruct is not a tuple struct, the shorthand should
// apply.
let a = 10;
let instance = AnotherStruct { a: a };
}
11 changes: 11 additions & 0 deletions tests/target/issue-5488.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// rustfmt-use_field_init_shorthand: true
fn main() {
// Since MyStruct is a tuple struct, it should not be shorthanded to
// MyStruct { 0 } even if use_field_init_shorthand is enabled.
let instance = MyStruct { 0: 0 };

// Since AnotherStruct is not a tuple struct, the shorthand should
// apply.
let a = 10;
let instance = AnotherStruct { a };
}

0 comments on commit 8386bed

Please sign in to comment.