Skip to content

Commit 6a78247

Browse files
ayazhafizcalebcartwright
authored andcommitted
Preserve comments in empty statements (rust-lang#4180)
* Preserve comments in empty statements Closes rust-lang#4018 * fixup! Preserve comments in empty statements
1 parent e70343a commit 6a78247

File tree

4 files changed

+45
-5
lines changed

4 files changed

+45
-5
lines changed

src/stmt.rs

+4
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,10 @@ impl<'a> Stmt<'a> {
5252
result
5353
}
5454

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

src/visitor.rs

+17-5
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use crate::stmt::Stmt;
2525
use crate::syntux::session::ParseSess;
2626
use crate::utils::{
2727
self, contains_skip, count_newlines, depr_skip_annotation, format_unsafety, inner_attributes,
28-
last_line_width, mk_sp, ptr_vec_to_ref_vec, rewrite_ident, stmt_expr,
28+
last_line_width, mk_sp, ptr_vec_to_ref_vec, rewrite_ident, starts_with_newline, stmt_expr,
2929
};
3030
use crate::{ErrorKind, FormatReport, FormattingError};
3131

@@ -117,10 +117,22 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
117117
self.parse_sess.span_to_debug_info(stmt.span())
118118
);
119119

120-
// https://github.com/rust-lang/rust/issues/63679.
121-
let is_all_semicolons =
122-
|snippet: &str| snippet.chars().all(|c| c.is_whitespace() || c == ';');
123-
if is_all_semicolons(&self.snippet(stmt.span())) {
120+
if stmt.is_empty() {
121+
// If the statement is empty, just skip over it. Before that, make sure any comment
122+
// snippet preceding the semicolon is picked up.
123+
let snippet = self.snippet(mk_sp(self.last_pos, stmt.span().lo()));
124+
let original_starts_with_newline = snippet
125+
.find(|c| c != ' ')
126+
.map_or(false, |i| starts_with_newline(&snippet[i..]));
127+
let snippet = snippet.trim();
128+
if !snippet.is_empty() {
129+
if original_starts_with_newline {
130+
self.push_str("\n");
131+
}
132+
self.push_str(&self.block_indent.to_string(self.config));
133+
self.push_str(snippet);
134+
}
135+
124136
self.last_pos = stmt.span().hi();
125137
return;
126138
}

tests/source/issue-4018.rs

+13
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+
}

tests/target/issue-4018.rs

+11
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)