3294: When joining lines, unwrap trivial diverging blocks r=matklad a=matklad



bors r+
🤖

Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
This commit is contained in:
bors[bot] 2020-02-24 16:18:12 +00:00 committed by GitHub
commit bd4ea87f74
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 53 additions and 8 deletions

View File

@ -43,15 +43,35 @@ pub fn unwrap_trivial_block(block: ast::BlockExpr) -> ast::Expr {
pub fn extract_trivial_expression(block: &ast::BlockExpr) -> Option<ast::Expr> { pub fn extract_trivial_expression(block: &ast::BlockExpr) -> Option<ast::Expr> {
let block = block.block()?; let block = block.block()?;
let expr = block.expr()?; let has_anything_else = |thing: &SyntaxNode| -> bool {
let non_trivial_children = block.syntax().children().filter(|it| match it.kind() { let mut non_trivial_children =
WHITESPACE | T!['{'] | T!['}'] => false, block.syntax().children_with_tokens().filter(|it| match it.kind() {
_ => it != expr.syntax(), WHITESPACE | T!['{'] | T!['}'] => false,
}); _ => it.as_node() != Some(thing),
if non_trivial_children.count() > 0 { });
return None; non_trivial_children.next().is_some()
};
if let Some(expr) = block.expr() {
if has_anything_else(expr.syntax()) {
return None;
}
return Some(expr);
} else {
// Unwrap `{ continue; }`
let (stmt,) = block.statements().next_tuple()?;
if has_anything_else(stmt.syntax()) {
return None;
}
if let ast::Stmt::ExprStmt(expr_stmt) = stmt {
let expr = expr_stmt.expr()?;
match expr.syntax().kind() {
CONTINUE_EXPR | BREAK_EXPR | RETURN_EXPR => return Some(expr),
_ => (),
}
}
} }
Some(expr) None
} }
pub fn compute_ws(left: SyntaxKind, right: SyntaxKind) -> &'static str { pub fn compute_ws(left: SyntaxKind, right: SyntaxKind) -> &'static str {

View File

@ -227,6 +227,31 @@ fn foo() {
); );
} }
#[test]
fn test_join_lines_diverging_block() {
let before = r"
fn foo() {
loop {
match x {
92 => <|>{
continue;
}
}
}
}
";
let after = r"
fn foo() {
loop {
match x {
92 => <|>continue,
}
}
}
";
check_join_lines(before, after);
}
#[test] #[test]
fn join_lines_adds_comma_for_block_in_match_arm() { fn join_lines_adds_comma_for_block_in_match_arm() {
check_join_lines( check_join_lines(