1 use std::collections::VecDeque;
3 use syntax::ast::{self, AstNode};
5 use crate::{utils::invert_boolean_expression, AssistContext, AssistId, AssistKind, Assists};
7 // Assist: apply_demorgan
9 // Apply https://en.wikipedia.org/wiki/De_Morgan%27s_laws[De Morgan's law].
10 // This transforms expressions of the form `!l || !r` into `!(l && r)`.
11 // This also works with `&&`. This assist can only be applied with the cursor
12 // on either `||` or `&&`.
16 // if x != 4 ||$0 y < 3.14 {}
22 // if !(x == 4 && y >= 3.14) {}
25 pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
26 let expr = ctx.find_node_at_offset::<ast::BinExpr>()?;
27 let op = expr.op_kind()?;
28 let op_range = expr.op_token()?.text_range();
30 let opposite_op = match op {
31 ast::BinaryOp::LogicOp(ast::LogicOp::And) => "||",
32 ast::BinaryOp::LogicOp(ast::LogicOp::Or) => "&&",
36 let cursor_in_range = op_range.contains_range(ctx.selection_trimmed());
43 // Walk up the tree while we have the same binary operator
44 while let Some(parent_expr) = expr.syntax().parent().and_then(ast::BinExpr::cast) {
45 match expr.op_kind() {
46 Some(parent_op) if parent_op == op => {
53 let mut expr_stack = vec![expr.clone()];
54 let mut terms = Vec::new();
55 let mut op_ranges = Vec::new();
57 // Find all the children with the same binary operator
58 while let Some(expr) = expr_stack.pop() {
59 let mut traverse_bin_expr_arm = |expr| {
60 if let ast::Expr::BinExpr(bin_expr) = expr {
61 if let Some(expr_op) = bin_expr.op_kind() {
63 expr_stack.push(bin_expr);
65 terms.push(ast::Expr::BinExpr(bin_expr));
68 terms.push(ast::Expr::BinExpr(bin_expr));
75 op_ranges.extend(expr.op_token().map(|t| t.text_range()));
76 traverse_bin_expr_arm(expr.lhs()?);
77 traverse_bin_expr_arm(expr.rhs()?);
81 AssistId("apply_demorgan", AssistKind::RefactorRewrite),
82 "Apply De Morgan's law",
85 terms.sort_by_key(|t| t.syntax().text_range().start());
86 let mut terms = VecDeque::from(terms);
88 let paren_expr = expr.syntax().parent().and_then(ast::ParenExpr::cast);
90 let neg_expr = paren_expr
92 .and_then(|paren_expr| paren_expr.syntax().parent())
93 .and_then(ast::PrefixExpr::cast)
94 .and_then(|prefix_expr| {
95 if prefix_expr.op_kind().unwrap() == ast::UnaryOp::Not {
102 for op_range in op_ranges {
103 edit.replace(op_range, opposite_op);
106 if let Some(paren_expr) = paren_expr {
108 let range = term.syntax().text_range();
109 let not_term = invert_boolean_expression(term);
111 edit.replace(range, not_term.syntax().text());
114 if let Some(neg_expr) = neg_expr {
115 cov_mark::hit!(demorgan_double_negation);
116 edit.replace(neg_expr.op_token().unwrap().text_range(), "");
118 cov_mark::hit!(demorgan_double_parens);
119 edit.replace(paren_expr.l_paren_token().unwrap().text_range(), "!(");
122 if let Some(lhs) = terms.pop_front() {
123 let lhs_range = lhs.syntax().text_range();
124 let not_lhs = invert_boolean_expression(lhs);
126 edit.replace(lhs_range, format!("!({not_lhs}"));
129 if let Some(rhs) = terms.pop_back() {
130 let rhs_range = rhs.syntax().text_range();
131 let not_rhs = invert_boolean_expression(rhs);
133 edit.replace(rhs_range, format!("{not_rhs})"));
137 let term_range = term.syntax().text_range();
138 let not_term = invert_boolean_expression(term);
139 edit.replace(term_range, not_term.to_string());
148 use crate::tests::{check_assist, check_assist_not_applicable};
153 fn demorgan_handles_leq() {
158 fn f() { S < S &&$0 S <= S }
162 fn f() { !(S >= S || S > S) }
168 fn demorgan_handles_geq() {
173 fn f() { S > S &&$0 S >= S }
177 fn f() { !(S <= S || S < S) }
183 fn demorgan_turns_and_into_or() {
184 check_assist(apply_demorgan, "fn f() { !x &&$0 !x }", "fn f() { !(x || x) }")
188 fn demorgan_turns_or_into_and() {
189 check_assist(apply_demorgan, "fn f() { !x ||$0 !x }", "fn f() { !(x && x) }")
193 fn demorgan_removes_inequality() {
194 check_assist(apply_demorgan, "fn f() { x != x ||$0 !x }", "fn f() { !(x == x && x) }")
198 fn demorgan_general_case() {
199 check_assist(apply_demorgan, "fn f() { x ||$0 x }", "fn f() { !(!x && !x) }")
203 fn demorgan_multiple_terms() {
204 check_assist(apply_demorgan, "fn f() { x ||$0 y || z }", "fn f() { !(!x && !y && !z) }");
205 check_assist(apply_demorgan, "fn f() { x || y ||$0 z }", "fn f() { !(!x && !y && !z) }");
209 fn demorgan_doesnt_apply_with_cursor_not_on_op() {
210 check_assist_not_applicable(apply_demorgan, "fn f() { $0 !x || !x }")
214 fn demorgan_doesnt_double_negation() {
215 cov_mark::check!(demorgan_double_negation);
216 check_assist(apply_demorgan, "fn f() { !(x ||$0 x) }", "fn f() { (!x && !x) }")
220 fn demorgan_doesnt_double_parens() {
221 cov_mark::check!(demorgan_double_parens);
222 check_assist(apply_demorgan, "fn f() { (x ||$0 x) }", "fn f() { !(!x && !x) }")
225 // https://github.com/rust-lang/rust-analyzer/issues/10963
227 fn demorgan_doesnt_hang() {
230 "fn f() { 1 || 3 &&$0 4 || 5 }",
231 "fn f() { !(!1 || !3 || !4) || 5 }",