Skip to content

Commit c0479ba

Browse files
committed
Improve handling of trailing comments for the consequence of if statements.
1 parent 18f6334 commit c0479ba

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

crates/oxc_formatter/src/write/utils/statement_body.rs

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use crate::{
1111
trivia::FormatTrailingComments,
1212
},
1313
generated::ast_nodes::{AstNode, AstNodes},
14+
utils::format_node_without_trailing_comments::FormatNodeWithoutTrailingComments,
1415
write,
1516
write::FormatWrite,
1617
};
@@ -50,24 +51,28 @@ impl<'a> Format<'a> for FormatStatementBody<'a, '_> {
5051
[indent(&format_args!(
5152
&soft_line_break_or_space(),
5253
&format_once(|f| {
54+
// ```js
55+
// if (condition)
56+
// statement; // comment1
57+
// // comment2
58+
// else {}
59+
// ```
60+
// The following logic is to ensure that `comment1` is printed as a trailing comment of the
61+
// statement, and leave `comment2` to be printed in the IfStatement's alternate.
62+
63+
let body_span = self.body.span();
5364
let is_consequent_of_if_statement_parent = matches!(
5465
self.body.parent,
5566
AstNodes::IfStatement(if_stmt)
56-
if if_stmt.consequent.span() == self.body.span() && if_stmt.alternate.is_some()
67+
if if_stmt.consequent.span() == body_span && if_stmt.alternate.is_some()
5768
);
58-
if is_consequent_of_if_statement_parent
59-
&& let AstNodes::ExpressionStatement(expression) =
60-
self.body.as_ast_nodes()
61-
{
62-
expression.format_leading_comments(f)?;
63-
expression.write(f)?;
64-
let comments = f
65-
.context()
66-
.comments()
67-
.comments_before_character(expression.span.end, b'\n');
69+
if is_consequent_of_if_statement_parent {
70+
write!(f, FormatNodeWithoutTrailingComments(self.body))?;
71+
let comments =
72+
f.context().comments().end_of_line_comments_after(body_span.end);
6873
FormatTrailingComments::Comments(comments).fmt(f)
6974
} else {
70-
self.body.fmt(f)
75+
write!(f, self.body)
7176
}
7277
})
7378
))]

0 commit comments

Comments
 (0)