Skip to content

Commit bd4ea87

Browse files
bors[bot]matklad
andauthored
Merge #3294
3294: When joining lines, unwrap trivial diverging blocks r=matklad a=matklad bors r+ 🤖 Co-authored-by: Aleksey Kladov <[email protected]>
2 parents 49b9c8a + f551e50 commit bd4ea87

File tree

2 files changed

+53
-8
lines changed

2 files changed

+53
-8
lines changed

crates/ra_fmt/src/lib.rs

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,35 @@ pub fn unwrap_trivial_block(block: ast::BlockExpr) -> ast::Expr {
4343

4444
pub fn extract_trivial_expression(block: &ast::BlockExpr) -> Option<ast::Expr> {
4545
let block = block.block()?;
46-
let expr = block.expr()?;
47-
let non_trivial_children = block.syntax().children().filter(|it| match it.kind() {
48-
WHITESPACE | T!['{'] | T!['}'] => false,
49-
_ => it != expr.syntax(),
50-
});
51-
if non_trivial_children.count() > 0 {
52-
return None;
46+
let has_anything_else = |thing: &SyntaxNode| -> bool {
47+
let mut non_trivial_children =
48+
block.syntax().children_with_tokens().filter(|it| match it.kind() {
49+
WHITESPACE | T!['{'] | T!['}'] => false,
50+
_ => it.as_node() != Some(thing),
51+
});
52+
non_trivial_children.next().is_some()
53+
};
54+
55+
if let Some(expr) = block.expr() {
56+
if has_anything_else(expr.syntax()) {
57+
return None;
58+
}
59+
return Some(expr);
60+
} else {
61+
// Unwrap `{ continue; }`
62+
let (stmt,) = block.statements().next_tuple()?;
63+
if has_anything_else(stmt.syntax()) {
64+
return None;
65+
}
66+
if let ast::Stmt::ExprStmt(expr_stmt) = stmt {
67+
let expr = expr_stmt.expr()?;
68+
match expr.syntax().kind() {
69+
CONTINUE_EXPR | BREAK_EXPR | RETURN_EXPR => return Some(expr),
70+
_ => (),
71+
}
72+
}
5373
}
54-
Some(expr)
74+
None
5575
}
5676

5777
pub fn compute_ws(left: SyntaxKind, right: SyntaxKind) -> &'static str {

crates/ra_ide/src/join_lines.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,31 @@ fn foo() {
227227
);
228228
}
229229

230+
#[test]
231+
fn test_join_lines_diverging_block() {
232+
let before = r"
233+
fn foo() {
234+
loop {
235+
match x {
236+
92 => <|>{
237+
continue;
238+
}
239+
}
240+
}
241+
}
242+
";
243+
let after = r"
244+
fn foo() {
245+
loop {
246+
match x {
247+
92 => <|>continue,
248+
}
249+
}
250+
}
251+
";
252+
check_join_lines(before, after);
253+
}
254+
230255
#[test]
231256
fn join_lines_adds_comma_for_block_in_match_arm() {
232257
check_join_lines(

0 commit comments

Comments
 (0)