Skip to content

Commit 45895dc

Browse files
authored
Preserve comments in empty statements (#4180)
* Preserve comments in empty statements Closes #4018 * fixup! Preserve comments in empty statements
1 parent e44a71c commit 45895dc

File tree

4 files changed

+45
-5
lines changed

4 files changed

+45
-5
lines changed

rustfmt-core/rustfmt-lib/src/formatting/stmt.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ impl<'a> Stmt<'a> {
5353
result
5454
}
5555

56+
pub(crate) fn is_empty(&self) -> bool {
57+
matches!(self.inner.kind, ast::StmtKind::Empty)
58+
}
59+
5660
fn is_last_expr(&self) -> bool {
5761
if !self.is_last {
5862
return false;

rustfmt-core/rustfmt-lib/src/formatting/visitor.rs

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use crate::formatting::{
2525
utils::{
2626
self, contains_skip, count_newlines, depr_skip_annotation, inner_attributes,
2727
last_line_contains_single_line_comment, last_line_width, mk_sp, ptr_vec_to_ref_vec,
28-
rewrite_ident, stmt_expr,
28+
rewrite_ident, starts_with_newline, stmt_expr,
2929
},
3030
};
3131
use crate::result::{ErrorKind, FormatError};
@@ -120,10 +120,22 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
120120
self.parse_sess.span_to_debug_info(stmt.span())
121121
);
122122

123-
// https://github.com/rust-lang/rust/issues/63679.
124-
let is_all_semicolons =
125-
|snippet: &str| snippet.chars().all(|c| c.is_whitespace() || c == ';');
126-
if is_all_semicolons(&self.snippet(stmt.span())) {
123+
if stmt.is_empty() {
124+
// If the statement is empty, just skip over it. Before that, make sure any comment
125+
// snippet preceding the semicolon is picked up.
126+
let snippet = self.snippet(mk_sp(self.last_pos, stmt.span().lo()));
127+
let original_starts_with_newline = snippet
128+
.find(|c| c != ' ')
129+
.map_or(false, |i| starts_with_newline(&snippet[i..]));
130+
let snippet = snippet.trim();
131+
if !snippet.is_empty() {
132+
if original_starts_with_newline {
133+
self.push_str("\n");
134+
}
135+
self.push_str(&self.block_indent.to_string(self.config));
136+
self.push_str(snippet);
137+
}
138+
127139
self.last_pos = stmt.span().hi();
128140
return;
129141
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
fn main() {
2+
;
3+
/* extra comment */ ;
4+
}
5+
6+
fn main() {
7+
println!("");
8+
// comment 1
9+
// comment 2
10+
// comment 3
11+
// comment 4
12+
;
13+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
fn main() {
2+
/* extra comment */
3+
}
4+
5+
fn main() {
6+
println!("");
7+
// comment 1
8+
// comment 2
9+
// comment 3
10+
// comment 4
11+
}

0 commit comments

Comments
 (0)