Skip to content

Commit

Permalink
formatting empty where clauses when there are return types
Browse files Browse the repository at this point in the history
  • Loading branch information
mu001999 committed May 20, 2024
1 parent d5f1200 commit cc9b52d
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 20 deletions.
49 changes: 29 additions & 20 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2559,29 +2559,38 @@ fn rewrite_fn_base(
}

// Comment between return type and the end of the decl.
let snippet_lo = fd.output.span().hi();
if where_clause.predicates.is_empty() {
let snippet_lo = fd.output.span().hi();
let snippet_hi = span.hi();
let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
// Try to preserve the layout of the original snippet.
let original_starts_with_newline = snippet
.find(|c| c != ' ')
.map_or(false, |i| starts_with_newline(&snippet[i..]));
let original_ends_with_newline = snippet
.rfind(|c| c != ' ')
.map_or(false, |i| snippet[i..].ends_with('\n'));
let snippet = snippet.trim();
if !snippet.is_empty() {
result.push(if original_starts_with_newline {
'\n'
} else {
' '
});
result.push_str(snippet);
if original_ends_with_newline {
force_new_line_for_brace = true;

let mut deal_snippet = |snippet: &str| {
// Try to preserve the layout of the original snippet.
let original_starts_with_newline = snippet
.find(|c| c != ' ')
.map_or(false, |i| starts_with_newline(&snippet[i..]));
let original_ends_with_newline = snippet
.rfind(|c| c != ' ')
.map_or(false, |i| snippet[i..].ends_with('\n'));
let snippet = snippet.trim();
if !snippet.is_empty() {
result.push(if original_starts_with_newline {
'\n'
} else {
' '
});
result.push_str(snippet);
if original_ends_with_newline {
force_new_line_for_brace = true;
}
}
}
};

if context.config.version() == Version::Two && where_clause.has_where_token {
deal_snippet(context.snippet(mk_sp(snippet_lo, where_clause.span.lo())));
deal_snippet(context.snippet(mk_sp(where_clause.span.hi(), snippet_hi)));
} else {
deal_snippet(context.snippet(mk_sp(snippet_lo, snippet_hi)));
};
}
}

Expand Down
6 changes: 6 additions & 0 deletions tests/source/empty-where-clauses.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// rustfmt-version: Two

fn foo() -> () where {}
fn bar() -> () /* comment */ where {}
fn baz() -> () where /* comment */ {}
fn qux() -> () /* comment */ where /* comment */ {}
6 changes: 6 additions & 0 deletions tests/target/empty-where-clauses.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// rustfmt-version: Two

fn foo() -> () {}
fn bar() -> () /* comment */ {}
fn baz() -> () /* comment */ {}
fn qux() -> () /* comment */ /* comment */ {}

0 comments on commit cc9b52d

Please sign in to comment.