Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: remove parenthesis should ensure space #15857

Merged
merged 2 commits into from
Nov 27, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 27 additions & 6 deletions crates/ide-assists/src/handlers/remove_parentheses.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use syntax::{ast, AstNode};
use syntax::{ast, AstNode, SyntaxKind, T};

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

Expand Down Expand Up @@ -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)
},
)
}

Expand All @@ -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; }"#);
Expand Down Expand Up @@ -94,8 +115,8 @@ mod tests {
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; }"#,
);
}

Expand Down Expand Up @@ -164,8 +185,8 @@ mod tests {
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(
Expand Down