Skip to content

Commit f7a4a87

Browse files
lbrandeVeykril
authored andcommitted
De Morgan's Law assist now correctly parenthesizes binary expressions.
1 parent aa38fa1 commit f7a4a87

File tree

3 files changed

+7
-11
lines changed

3 files changed

+7
-11
lines changed

crates/ide_assists/src/handlers/apply_demorgan.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,17 @@ use crate::{utils::invert_boolean_expression, AssistContext, AssistId, AssistKin
77
// Apply https://en.wikipedia.org/wiki/De_Morgan%27s_laws[De Morgan's law].
88
// This transforms expressions of the form `!l || !r` into `!(l && r)`.
99
// This also works with `&&`. This assist can only be applied with the cursor
10-
// on either `||` or `&&`, with both operands being a negation of some kind.
11-
// This means something of the form `!x` or `x != y`.
10+
// on either `||` or `&&`.
1211
//
1312
// ```
1413
// fn main() {
15-
// if x != 4 ||$0 !y {}
14+
// if x != 4 ||$0 y < 3 {}
1615
// }
1716
// ```
1817
// ->
1918
// ```
2019
// fn main() {
21-
// if !(x == 4 && y) {}
20+
// if !(x == 4 && !(y < 3)) {}
2221
// }
2322
// ```
2423
pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {

crates/ide_assists/src/tests/generated.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,12 +147,12 @@ fn doctest_apply_demorgan() {
147147
"apply_demorgan",
148148
r#####"
149149
fn main() {
150-
if x != 4 ||$0 !y {}
150+
if x != 4 ||$0 y < 3 {}
151151
}
152152
"#####,
153153
r#####"
154154
fn main() {
155-
if !(x == 4 && y) {}
155+
if !(x == 4 && !(y < 3)) {}
156156
}
157157
"#####,
158158
)

crates/ide_assists/src/utils.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -217,11 +217,8 @@ fn invert_special_case(expr: &ast::Expr) -> Option<ast::Expr> {
217217
ast::Expr::BinExpr(bin) => match bin.op_kind()? {
218218
ast::BinOp::NegatedEqualityTest => bin.replace_op(T![==]).map(|it| it.into()),
219219
ast::BinOp::EqualityTest => bin.replace_op(T![!=]).map(|it| it.into()),
220-
// Parenthesize composite boolean expressions before prefixing `!`
221-
ast::BinOp::BooleanAnd | ast::BinOp::BooleanOr => {
222-
Some(make::expr_prefix(T![!], make::expr_paren(expr.clone())))
223-
}
224-
_ => None,
220+
// Parenthesize other expressions before prefixing `!`
221+
_ => Some(make::expr_prefix(T![!], make::expr_paren(expr.clone()))),
225222
},
226223
ast::Expr::MethodCallExpr(mce) => {
227224
let receiver = mce.receiver()?;

0 commit comments

Comments
 (0)