Skip to content

Commit 8225a0d

Browse files
committed
Preserve comments in empty statements
Closes #4018
1 parent e44a71c commit 8225a0d

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

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

Lines changed: 16 additions & 1 deletion
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};
@@ -124,6 +124,21 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
124124
let is_all_semicolons =
125125
|snippet: &str| snippet.chars().all(|c| c.is_whitespace() || c == ';');
126126
if is_all_semicolons(&self.snippet(stmt.span())) {
127+
// If the statement is all semicolons, just skip over it. Before that, make sure any
128+
// comment snippet preceding the semicolon is picked up.
129+
let snippet = self.snippet(mk_sp(self.last_pos, stmt.span().lo()));
130+
let original_starts_with_newline = snippet
131+
.find(|c| c != ' ')
132+
.map_or(false, |i| starts_with_newline(&snippet[i..]));
133+
let snippet = snippet.trim();
134+
if !snippet.is_empty() {
135+
if original_starts_with_newline {
136+
self.push_str("\n");
137+
}
138+
self.push_str(&self.block_indent.to_string(self.config));
139+
self.push_str(snippet);
140+
}
141+
127142
self.last_pos = stmt.span().hi();
128143
return;
129144
}

0 commit comments

Comments
 (0)