1 use ide_db::syntax_helpers::node_ext::is_pattern_cond;
8 assist_context::{AssistContext, Assists},
9 utils::invert_boolean_expression,
15 // This transforms if expressions of the form `if !x {A} else {B}` into `if x {B} else {A}`
16 // This also works with `!=`. This assist can only be applied with the cursor on `if`.
20 // if$0 !y { A } else { B }
26 // if y { B } else { A }
29 pub(crate) fn invert_if(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
30 let if_keyword = ctx.find_token_syntax_at_offset(T![if])?;
31 let expr = ast::IfExpr::cast(if_keyword.parent()?)?;
32 let if_range = if_keyword.text_range();
33 let cursor_in_range = if_range.contains_range(ctx.selection_trimmed());
38 let cond = expr.condition()?;
39 // This assist should not apply for if-let.
40 if is_pattern_cond(cond.clone()) {
44 let then_node = expr.then_branch()?.syntax().clone();
45 let else_block = match expr.else_branch()? {
46 ast::ElseBranch::Block(it) => it,
47 ast::ElseBranch::IfExpr(_) => return None,
50 acc.add(AssistId("invert_if", AssistKind::RefactorRewrite), "Invert if", if_range, |edit| {
51 let flip_cond = invert_boolean_expression(cond.clone());
52 edit.replace_ast(cond, flip_cond);
54 let else_node = else_block.syntax();
55 let else_range = else_node.text_range();
56 let then_range = then_node.text_range();
58 edit.replace(else_range, then_node.text());
59 edit.replace(then_range, else_node.text());
67 use crate::tests::{check_assist, check_assist_not_applicable};
70 fn invert_if_composite_condition() {
73 "fn f() { i$0f x == 3 || x == 4 || x == 5 { 1 } else { 3 * 2 } }",
74 "fn f() { if !(x == 3 || x == 4 || x == 5) { 3 * 2 } else { 1 } }",
79 fn invert_if_remove_not_parentheses() {
82 "fn f() { i$0f !(x == 3 || x == 4 || x == 5) { 3 * 2 } else { 1 } }",
83 "fn f() { if x == 3 || x == 4 || x == 5 { 1 } else { 3 * 2 } }",
88 fn invert_if_remove_inequality() {
91 "fn f() { i$0f x != 3 { 1 } else { 3 + 2 } }",
92 "fn f() { if x == 3 { 3 + 2 } else { 1 } }",
97 fn invert_if_remove_not() {
100 "fn f() { $0if !cond { 3 * 2 } else { 1 } }",
101 "fn f() { if cond { 1 } else { 3 * 2 } }",
106 fn invert_if_general_case() {
109 "fn f() { i$0f cond { 3 * 2 } else { 1 } }",
110 "fn f() { if !cond { 1 } else { 3 * 2 } }",
115 fn invert_if_doesnt_apply_with_cursor_not_on_if() {
116 check_assist_not_applicable(invert_if, "fn f() { if !$0cond { 3 * 2 } else { 1 } }")
120 fn invert_if_doesnt_apply_with_if_let() {
121 check_assist_not_applicable(
123 "fn f() { i$0f let Some(_) = Some(1) { 1 } else { 0 } }",
128 fn invert_if_option_case() {
131 "fn f() { if$0 doc_style.is_some() { Class::DocComment } else { Class::Comment } }",
132 "fn f() { if doc_style.is_none() { Class::Comment } else { Class::DocComment } }",
137 fn invert_if_result_case() {
140 "fn f() { i$0f doc_style.is_err() { Class::Err } else { Class::Ok } }",
141 "fn f() { if doc_style.is_ok() { Class::Ok } else { Class::Err } }",