Auto merge of #15857 - Young-Flash:fix, r=Veykril

fix: remove parenthesis should ensure space

close https://github.com/rust-lang/rust-analyzer/issues/15844
This commit is contained in:
bors 2023-11-27 16:14:31 +00:00
commit 4ab67291fa

View File

@ -1,4 +1,4 @@
use syntax::{ast, AstNode};
use syntax::{ast, AstNode, SyntaxKind, T};
use crate::{AssistContext, AssistId, AssistKind, Assists};
@ -39,7 +39,19 @@ pub(crate) fn remove_parentheses(acc: &mut Assists, ctx: &AssistContext<'_>) ->
AssistId("remove_parentheses", AssistKind::Refactor),
"Remove redundant parentheses",
target,
|builder| builder.replace_ast(parens.into(), expr),
|builder| {
let prev_token = parens.syntax().first_token().and_then(|it| it.prev_token());
let need_to_add_ws = match prev_token {
Some(it) => {
let tokens = vec![T![&], T![!], T!['('], T!['['], T!['{']];
it.kind() != SyntaxKind::WHITESPACE && !tokens.contains(&it.kind())
}
None => false,
};
let expr = if need_to_add_ws { format!(" {}", expr) } else { expr.to_string() };
builder.replace(parens.syntax().text_range(), expr)
},
)
}
@ -49,6 +61,15 @@ mod tests {
use super::*;
#[test]
fn remove_parens_space() {
check_assist(
remove_parentheses,
r#"fn f() { match$0(true) {} }"#,
r#"fn f() { match true {} }"#,
);
}
#[test]
fn remove_parens_simple() {
check_assist(remove_parentheses, r#"fn f() { $0(2) + 2; }"#, r#"fn f() { 2 + 2; }"#);
@ -94,8 +115,8 @@ fn remove_parens_precedence() {
check_assist(remove_parentheses, r#"fn f() { f(($02 + 2)); }"#, r#"fn f() { f(2 + 2); }"#);
check_assist(
remove_parentheses,
r#"fn f() { (1<2)&&$0(3>4); }"#,
r#"fn f() { (1<2)&&3>4; }"#,
r#"fn f() { (1<2) &&$0(3>4); }"#,
r#"fn f() { (1<2) && 3>4; }"#,
);
}
@ -164,8 +185,8 @@ fn remove_exprs_let_else_restrictions() {
fn remove_parens_weird_places() {
check_assist(
remove_parentheses,
r#"fn f() { match () { _=>$0(()) } }"#,
r#"fn f() { match () { _=>() } }"#,
r#"fn f() { match () { _ =>$0(()) } }"#,
r#"fn f() { match () { _ => () } }"#,
);
check_assist(