From e41329ce87409df929ecfa191297f944472cc999 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Sun, 20 Mar 2022 13:21:44 -0400 Subject: [PATCH] Search for struct body span after any generic arguments Fixes 5273 Previously, rustfmt searched for the start of a struct body after the opening `{`. In most cases this works just fine, but const values can also be defined between `{ }`, which lead to issues when rewriting the struct body. Now, rustfmt will search for the `{` after the generic argument list to guarantee that the `{` it finds is the start of the struct body. --- src/items.rs | 8 +++++++- tests/target/issue_5273.rs | 3 +++ 2 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 tests/target/issue_5273.rs diff --git a/src/items.rs b/src/items.rs index 9b35d28f1195..92f423bbb627 100644 --- a/src/items.rs +++ b/src/items.rs @@ -1273,7 +1273,13 @@ pub(crate) fn format_struct_struct( result.push_str(&header_str); let header_hi = struct_parts.ident.span.hi(); - let body_lo = context.snippet_provider.span_after(span, "{"); + let body_lo = if let Some(generics) = struct_parts.generics { + // Adjust the span to start at the end of the generic arguments before searching for the '{' + let span = span.with_lo(generics.span.hi()); + context.snippet_provider.span_after(span, "{") + } else { + context.snippet_provider.span_after(span, "{") + }; let generics_str = match struct_parts.generics { Some(g) => format_generics( diff --git a/tests/target/issue_5273.rs b/tests/target/issue_5273.rs new file mode 100644 index 000000000000..3bb9048a5fd3 --- /dev/null +++ b/tests/target/issue_5273.rs @@ -0,0 +1,3 @@ +struct Example { + // +}