Skip to content

Commit 5391847

Browse files
RajivTScalebcartwright
authored andcommitted
Fix #5488 - prevent shorthand init for tuple struct
Closes #5488 Fix for #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.
1 parent e2996a8 commit 5391847

File tree

3 files changed

+38
-2
lines changed

3 files changed

+38
-2
lines changed

src/expr.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -1723,9 +1723,11 @@ pub(crate) fn rewrite_field(
17231723
let overhead = name.len() + separator.len();
17241724
let expr_shape = shape.offset_left(overhead)?;
17251725
let expr = field.expr.rewrite(context, expr_shape);
1726-
1726+
let is_lit = matches!(field.expr.kind, ast::ExprKind::Lit(_));
17271727
match expr {
1728-
Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1728+
Some(ref e)
1729+
if !is_lit && e.as_str() == name && context.config.use_field_init_shorthand() =>
1730+
{
17291731
Some(attrs_str + name)
17301732
}
17311733
Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),

tests/source/issue-5488.rs

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// rustfmt-use_field_init_shorthand: true
2+
3+
struct MyStruct(u32);
4+
struct AnotherStruct {
5+
a: u32,
6+
}
7+
8+
fn main() {
9+
// Since MyStruct is a tuple struct, it should not be shorthanded to
10+
// MyStruct { 0 } even if use_field_init_shorthand is enabled.
11+
let instance = MyStruct { 0: 0 };
12+
13+
// Since AnotherStruct is not a tuple struct, the shorthand should
14+
// apply.
15+
let a = 10;
16+
let instance = AnotherStruct { a: a };
17+
}

tests/target/issue-5488.rs

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// rustfmt-use_field_init_shorthand: true
2+
3+
struct MyStruct(u32);
4+
struct AnotherStruct {
5+
a: u32,
6+
}
7+
8+
fn main() {
9+
// Since MyStruct is a tuple struct, it should not be shorthanded to
10+
// MyStruct { 0 } even if use_field_init_shorthand is enabled.
11+
let instance = MyStruct { 0: 0 };
12+
13+
// Since AnotherStruct is not a tuple struct, the shorthand should
14+
// apply.
15+
let a = 10;
16+
let instance = AnotherStruct { a };
17+
}

0 commit comments

Comments
 (0)