Skip to content

Commit 0f42a71

Browse files
committed
Parenthesize composite if condition before inverting in invert-if assist
1 parent 8cba423 commit 0f42a71

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

crates/assists/src/handlers/invert_if.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,15 @@ mod tests {
6868

6969
use crate::tests::{check_assist, check_assist_not_applicable};
7070

71+
#[test]
72+
fn invert_if_composite_condition() {
73+
check_assist(
74+
invert_if,
75+
"fn f() { i<|>f x == 3 || x == 4 || x == 5 { 1 } else { 3 * 2 } }",
76+
"fn f() { if !(x == 3 || x == 4 || x == 5) { 3 * 2 } else { 1 } }",
77+
)
78+
}
79+
7180
#[test]
7281
fn invert_if_remove_inequality() {
7382
check_assist(

crates/assists/src/utils.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,10 @@ fn invert_special_case(expr: &ast::Expr) -> Option<ast::Expr> {
212212
ast::Expr::BinExpr(bin) => match bin.op_kind()? {
213213
ast::BinOp::NegatedEqualityTest => bin.replace_op(T![==]).map(|it| it.into()),
214214
ast::BinOp::EqualityTest => bin.replace_op(T![!=]).map(|it| it.into()),
215+
// Parenthesize composite boolean expressions before prefixing `!`
216+
ast::BinOp::BooleanAnd | ast::BinOp::BooleanOr => {
217+
Some(make::expr_prefix(T![!], make::expr_paren(expr.clone())))
218+
}
215219
_ => None,
216220
},
217221
ast::Expr::MethodCallExpr(mce) => {

crates/syntax/src/ast/make.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,9 @@ pub fn expr_method_call(receiver: ast::Expr, method: &str, arg_list: ast::ArgLis
196196
pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
197197
expr_from_text(&if exclusive { format!("&mut {}", expr) } else { format!("&{}", expr) })
198198
}
199+
pub fn expr_paren(expr: ast::Expr) -> ast::Expr {
200+
expr_from_text(&format!("({})", expr))
201+
}
199202
fn expr_from_text(text: &str) -> ast::Expr {
200203
ast_from_text(&format!("const C: () = {};", text))
201204
}

0 commit comments

Comments
 (0)