Skip to content

Commit

Permalink
Preserve comments in empty statements (#4180)
Browse files Browse the repository at this point in the history
* Preserve comments in empty statements

Closes #4018

* fixup! Preserve comments in empty statements
  • Loading branch information
ayazhafiz authored and calebcartwright committed Oct 24, 2020
1 parent e70343a commit 6a78247
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 5 deletions.
4 changes: 4 additions & 0 deletions src/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ impl<'a> Stmt<'a> {
result
}

pub(crate) fn is_empty(&self) -> bool {
matches!(self.inner.kind, ast::StmtKind::Empty)
}

fn is_last_expr(&self) -> bool {
if !self.is_last {
return false;
Expand Down
22 changes: 17 additions & 5 deletions src/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use crate::stmt::Stmt;
use crate::syntux::session::ParseSess;
use crate::utils::{
self, contains_skip, count_newlines, depr_skip_annotation, format_unsafety, inner_attributes,
last_line_width, mk_sp, ptr_vec_to_ref_vec, rewrite_ident, stmt_expr,
last_line_width, mk_sp, ptr_vec_to_ref_vec, rewrite_ident, starts_with_newline, stmt_expr,
};
use crate::{ErrorKind, FormatReport, FormattingError};

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

// https://github.com/rust-lang/rust/issues/63679.
let is_all_semicolons =
|snippet: &str| snippet.chars().all(|c| c.is_whitespace() || c == ';');
if is_all_semicolons(&self.snippet(stmt.span())) {
if stmt.is_empty() {
// If the statement is empty, just skip over it. Before that, make sure any comment
// snippet preceding the semicolon is picked up.
let snippet = self.snippet(mk_sp(self.last_pos, stmt.span().lo()));
let original_starts_with_newline = snippet
.find(|c| c != ' ')
.map_or(false, |i| starts_with_newline(&snippet[i..]));
let snippet = snippet.trim();
if !snippet.is_empty() {
if original_starts_with_newline {
self.push_str("\n");
}
self.push_str(&self.block_indent.to_string(self.config));
self.push_str(snippet);
}

self.last_pos = stmt.span().hi();
return;
}
Expand Down
13 changes: 13 additions & 0 deletions tests/source/issue-4018.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
fn main() {
;
/* extra comment */ ;
}

fn main() {
println!("");
// comment 1
// comment 2
// comment 3
// comment 4
;
}
11 changes: 11 additions & 0 deletions tests/target/issue-4018.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
fn main() {
/* extra comment */
}

fn main() {
println!("");
// comment 1
// comment 2
// comment 3
// comment 4
}

0 comments on commit 6a78247

Please sign in to comment.