Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 28 additions & 7 deletions crates/ide-assists/src/handlers/apply_demorgan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use ide_db::{
syntax_helpers::node_ext::{for_each_tail_expr, walk_expr},
};
use syntax::{
SyntaxKind, T,
NodeOrToken, SyntaxKind, T,
ast::{
self, AstNode,
Expr::BinExpr,
Expand Down Expand Up @@ -38,15 +38,27 @@ use crate::{AssistContext, AssistId, Assists, utils::invert_boolean_expression};
// }
// ```
pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
let mut bin_expr = ctx.find_node_at_offset::<ast::BinExpr>()?;
let mut bin_expr = if let Some(not) = ctx.find_token_syntax_at_offset(T![!])
&& let Some(NodeOrToken::Node(next)) = not.next_sibling_or_token()
&& let Some(paren) = ast::ParenExpr::cast(next)
&& let Some(ast::Expr::BinExpr(bin_expr)) = paren.expr()
{
bin_expr
} else {
let bin_expr = ctx.find_node_at_offset::<ast::BinExpr>()?;
let op_range = bin_expr.op_token()?.text_range();

// Is the cursor on the expression's logical operator?
if !op_range.contains_range(ctx.selection_trimmed()) {
return None;
}

bin_expr
};

let op = bin_expr.op_kind()?;
let op_range = bin_expr.op_token()?.text_range();

// Is the cursor on the expression's logical operator?
if !op_range.contains_range(ctx.selection_trimmed()) {
return None;
}

// Walk up the tree while we have the same binary operator
while let Some(parent_expr) = bin_expr.syntax().parent().and_then(ast::BinExpr::cast) {
match parent_expr.op_kind() {
Expand Down Expand Up @@ -366,6 +378,15 @@ fn f() { !(S <= S || S < S) }
)
}

#[test]
fn demorgan_on_not() {
check_assist(
apply_demorgan,
"fn f() { $0!(1 || 3 && 4 || 5) }",
"fn f() { !1 && !(3 && 4) && !5 }",
)
}

#[test]
fn demorgan_keep_pars_for_op_precedence() {
check_assist(
Expand Down
Loading