Skip to content

Commit acd90bc

Browse files
bors[bot]matklad
andcommitted
Merge #482
482: fix code duplication r=matklad a=matklad Co-authored-by: Aleksey Kladov <[email protected]>
2 parents 3990f93 + a0c978c commit acd90bc

File tree

5 files changed

+510
-507
lines changed

5 files changed

+510
-507
lines changed

crates/ra_ide_api_light/src/assists/replace_if_let_with_match.rs

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
use ra_syntax::{
2-
AstNode, SyntaxKind::{L_CURLY, R_CURLY, WHITESPACE},
3-
ast,
4-
};
1+
use ra_syntax::{AstNode, ast};
52

6-
use crate::assists::{AssistCtx, Assist};
3+
use crate::{
4+
assists::{AssistCtx, Assist},
5+
formatting::extract_trivial_expression,
6+
};
77

88
pub fn replace_if_let_with_match(ctx: AssistCtx) -> Option<Assist> {
99
let if_expr: &ast::IfExpr = ctx.node_at_offset()?;
@@ -39,26 +39,12 @@ fn build_match_expr(
3939
}
4040

4141
fn format_arm(block: &ast::Block) -> String {
42-
match extract_expression(block) {
42+
match extract_trivial_expression(block) {
4343
None => block.syntax().text().to_string(),
4444
Some(e) => format!("{},", e.syntax().text()),
4545
}
4646
}
4747

48-
fn extract_expression(block: &ast::Block) -> Option<&ast::Expr> {
49-
let expr = block.expr()?;
50-
let non_trivial_children = block.syntax().children().filter(|it| {
51-
!(it == &expr.syntax()
52-
|| it.kind() == L_CURLY
53-
|| it.kind() == R_CURLY
54-
|| it.kind() == WHITESPACE)
55-
});
56-
if non_trivial_children.count() > 0 {
57-
return None;
58-
}
59-
Some(expr)
60-
}
61-
6248
#[cfg(test)]
6349
mod tests {
6450
use super::*;
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use ra_syntax::{
2+
ast, AstNode,
3+
SyntaxNode, SyntaxKind::*,
4+
};
5+
6+
pub(crate) fn extract_trivial_expression(block: &ast::Block) -> Option<&ast::Expr> {
7+
let expr = block.expr()?;
8+
if expr.syntax().text().contains('\n') {
9+
return None;
10+
}
11+
let non_trivial_children = block.syntax().children().filter(|it| match it.kind() {
12+
WHITESPACE | L_CURLY | R_CURLY => false,
13+
_ => it != &expr.syntax(),
14+
});
15+
if non_trivial_children.count() > 0 {
16+
return None;
17+
}
18+
Some(expr)
19+
}
20+
21+
pub(crate) fn compute_ws(left: &SyntaxNode, right: &SyntaxNode) -> &'static str {
22+
match left.kind() {
23+
L_PAREN | L_BRACK => return "",
24+
L_CURLY => {
25+
if let USE_TREE = right.kind() {
26+
return "";
27+
}
28+
}
29+
_ => (),
30+
}
31+
match right.kind() {
32+
R_PAREN | R_BRACK => return "",
33+
R_CURLY => {
34+
if let USE_TREE = left.kind() {
35+
return "";
36+
}
37+
}
38+
DOT => return "",
39+
_ => (),
40+
}
41+
" "
42+
}

0 commit comments

Comments
 (0)