Skip to content

Commit be62e0b

Browse files
committed
fix: remove parenthesis should ensure space
1 parent 6943228 commit be62e0b

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed

crates/ide-assists/src/handlers/remove_parentheses.rs

+30-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use syntax::{ast, AstNode};
1+
use syntax::{ast, AstNode, SyntaxKind, T};
22

33
use crate::{AssistContext, AssistId, AssistKind, Assists};
44

@@ -34,12 +34,27 @@ pub(crate) fn remove_parentheses(acc: &mut Assists, ctx: &AssistContext<'_>) ->
3434
return None;
3535
}
3636

37+
// we should use `find_node_at_offset` at `SourceFile` level to get expectant `Between`
38+
let token_at_offset = ctx
39+
.find_node_at_offset::<ast::SourceFile>()?
40+
.syntax()
41+
.token_at_offset(parens.syntax().text_range().start());
42+
let need_to_add_ws = match token_at_offset {
43+
syntax::TokenAtOffset::Between(before, _after) => {
44+
// anyother `SyntaxKind` we missing here?
45+
let tokens = vec![T![&], T![!], T!['('], T!['['], T!['{']];
46+
before.kind() != SyntaxKind::WHITESPACE && !tokens.contains(&before.kind())
47+
}
48+
_ => false,
49+
};
50+
let expr = if need_to_add_ws { format!(" {}", expr) } else { expr.to_string() };
51+
3752
let target = parens.syntax().text_range();
3853
acc.add(
3954
AssistId("remove_parentheses", AssistKind::Refactor),
4055
"Remove redundant parentheses",
4156
target,
42-
|builder| builder.replace_ast(parens.into(), expr),
57+
|builder| builder.replace(parens.syntax().text_range(), expr),
4358
)
4459
}
4560

@@ -49,6 +64,15 @@ mod tests {
4964

5065
use super::*;
5166

67+
#[test]
68+
fn remove_parens_space() {
69+
check_assist(
70+
remove_parentheses,
71+
r#"fn f() { match$0(true) {} }"#,
72+
r#"fn f() { match true {} }"#,
73+
);
74+
}
75+
5276
#[test]
5377
fn remove_parens_simple() {
5478
check_assist(remove_parentheses, r#"fn f() { $0(2) + 2; }"#, r#"fn f() { 2 + 2; }"#);
@@ -94,8 +118,8 @@ mod tests {
94118
check_assist(remove_parentheses, r#"fn f() { f(($02 + 2)); }"#, r#"fn f() { f(2 + 2); }"#);
95119
check_assist(
96120
remove_parentheses,
97-
r#"fn f() { (1<2)&&$0(3>4); }"#,
98-
r#"fn f() { (1<2)&&3>4; }"#,
121+
r#"fn f() { (1<2) &&$0(3>4); }"#,
122+
r#"fn f() { (1<2) && 3>4; }"#,
99123
);
100124
}
101125

@@ -164,8 +188,8 @@ mod tests {
164188
fn remove_parens_weird_places() {
165189
check_assist(
166190
remove_parentheses,
167-
r#"fn f() { match () { _=>$0(()) } }"#,
168-
r#"fn f() { match () { _=>() } }"#,
191+
r#"fn f() { match () { _ =>$0(()) } }"#,
192+
r#"fn f() { match () { _ => () } }"#,
169193
);
170194

171195
check_assist(

0 commit comments

Comments
 (0)