1 use ra_syntax::ast::{self, AstNode};
3 use crate::{utils::invert_boolean_expression, Assist, AssistCtx, AssistId};
5 // Assist: apply_demorgan
7 // Apply [De Morgan's law](https://en.wikipedia.org/wiki/De_Morgan%27s_laws).
8 // This transforms expressions of the form `!l || !r` into `!(l && r)`.
9 // 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`.
15 // if x != 4 ||<|> !y {}
21 // if !(x == 4 && y) {}
24 pub(crate) fn apply_demorgan(ctx: AssistCtx) -> Option<Assist> {
25 let expr = ctx.find_node_at_offset::<ast::BinExpr>()?;
26 let op = expr.op_kind()?;
27 let op_range = expr.op_token()?.text_range();
28 let opposite_op = opposite_logic_op(op)?;
29 let cursor_in_range = op_range.contains_range(ctx.frange.range);
34 let lhs = expr.lhs()?;
35 let lhs_range = lhs.syntax().text_range();
36 let not_lhs = invert_boolean_expression(lhs);
38 let rhs = expr.rhs()?;
39 let rhs_range = rhs.syntax().text_range();
40 let not_rhs = invert_boolean_expression(rhs);
42 ctx.add_assist(AssistId("apply_demorgan"), "Apply De Morgan's law", op_range, |edit| {
43 edit.replace(op_range, opposite_op);
44 edit.replace(lhs_range, format!("!({}", not_lhs.syntax().text()));
45 edit.replace(rhs_range, format!("{})", not_rhs.syntax().text()));
49 // Return the opposite text for a given logical operator, if it makes sense
50 fn opposite_logic_op(kind: ast::BinOp) -> Option<&'static str> {
52 ast::BinOp::BooleanOr => Some("&&"),
53 ast::BinOp::BooleanAnd => Some("||"),
62 use crate::tests::{check_assist, check_assist_not_applicable};
65 fn demorgan_turns_and_into_or() {
66 check_assist(apply_demorgan, "fn f() { !x &&<|> !x }", "fn f() { !(x ||<|> x) }")
70 fn demorgan_turns_or_into_and() {
71 check_assist(apply_demorgan, "fn f() { !x ||<|> !x }", "fn f() { !(x &&<|> x) }")
75 fn demorgan_removes_inequality() {
76 check_assist(apply_demorgan, "fn f() { x != x ||<|> !x }", "fn f() { !(x == x &&<|> x) }")
80 fn demorgan_general_case() {
81 check_assist(apply_demorgan, "fn f() { x ||<|> x }", "fn f() { !(!x &&<|> !x) }")
85 fn demorgan_doesnt_apply_with_cursor_not_on_op() {
86 check_assist_not_applicable(apply_demorgan, "fn f() { <|> !x || !x }")