From 5b4de6678f1c3b6de8078b6fd3286051006755ca Mon Sep 17 00:00:00 2001 From: Ary Borenszweig Date: Tue, 11 Mar 2025 09:54:55 -0300 Subject: [PATCH] fix: correctly format let followed by comment before unsafe --- tooling/nargo_fmt/src/formatter/statement.rs | 38 +++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/tooling/nargo_fmt/src/formatter/statement.rs b/tooling/nargo_fmt/src/formatter/statement.rs index d70778ae5d1..472816ca052 100644 --- a/tooling/nargo_fmt/src/formatter/statement.rs +++ b/tooling/nargo_fmt/src/formatter/statement.rs @@ -135,17 +135,38 @@ impl ChunkFormatter<'_, '_> { })); if let Some(value) = value { + // If there's a line comment right before the value we'll put + // the comment and the value in the next line, both indented. + let mut has_comment_before_value = false; + group.text(self.chunk(|formatter| { formatter.write_space(); formatter.write_token(Token::Assign); - formatter.write_space(); + formatter.skip_whitespace(); + if matches!(formatter.token, Token::LineComment(..)) { + has_comment_before_value = true; + } else { + formatter.write_space(); + } })); + if has_comment_before_value { + group.increase_indentation(); + group.line(); + group.trailing_comment(self.chunk(|formatter| { + formatter.skip_comments_and_whitespace(); + })); + } + let mut value_group = ChunkGroup::new(); value_group.kind = GroupKind::AssignValue; self.format_expression(value, &mut value_group); value_group.semicolon(self); group.group(value_group); + + if has_comment_before_value { + group.decrease_indentation(); + } } else { group.semicolon(self); } @@ -433,6 +454,21 @@ mod tests { assert_format(src, expected); } + #[test] + fn format_let_statement_with_unsafe_comment_right_before_unsafe() { + let src = " fn foo() { + + let x = // Safety: some comment + unsafe { 1 } ; } "; + let expected = "fn foo() { + let x = + // Safety: some comment + unsafe { 1 }; +} +"; + assert_format(src, expected); + } + #[test] fn format_assign() { let src = " fn foo() { x = 2 ; } ";