7 assist_context::{AssistContext, Assists},
8 utils::invert_boolean_expression,
14 // This transforms if expressions of the form `if !x {A} else {B}` into `if x {B} else {A}`
15 // This also works with `!=`. This assist can only be applied with the cursor on `if`.
19 // if$0 !y { A } else { B }
25 // if y { B } else { A }
28 pub(crate) fn invert_if(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
29 let if_keyword = ctx.find_token_syntax_at_offset(T![if])?;
30 let expr = ast::IfExpr::cast(if_keyword.parent()?)?;
31 let if_range = if_keyword.text_range();
32 let cursor_in_range = if_range.contains_range(ctx.selection_trimmed());
37 // This assist should not apply for if-let.
38 if expr.condition()?.is_pattern_cond() {
42 let cond = expr.condition()?.expr()?;
43 let then_node = expr.then_branch()?.syntax().clone();
44 let else_block = match expr.else_branch()? {
45 ast::ElseBranch::Block(it) => it,
46 ast::ElseBranch::IfExpr(_) => return None,
49 acc.add(AssistId("invert_if", AssistKind::RefactorRewrite), "Invert if", if_range, |edit| {
50 let flip_cond = invert_boolean_expression(cond.clone());
51 edit.replace_ast(cond, flip_cond);
53 let else_node = else_block.syntax();
54 let else_range = else_node.text_range();
55 let then_range = then_node.text_range();
57 edit.replace(else_range, then_node.text());
58 edit.replace(then_range, else_node.text());
66 use crate::tests::{check_assist, check_assist_not_applicable};
69 fn invert_if_composite_condition() {
72 "fn f() { i$0f x == 3 || x == 4 || x == 5 { 1 } else { 3 * 2 } }",
73 "fn f() { if !(x == 3 || x == 4 || x == 5) { 3 * 2 } else { 1 } }",
78 fn invert_if_remove_not_parentheses() {
81 "fn f() { i$0f !(x == 3 || x == 4 || x == 5) { 3 * 2 } else { 1 } }",
82 "fn f() { if x == 3 || x == 4 || x == 5 { 1 } else { 3 * 2 } }",
87 fn invert_if_remove_inequality() {
90 "fn f() { i$0f x != 3 { 1 } else { 3 + 2 } }",
91 "fn f() { if x == 3 { 3 + 2 } else { 1 } }",
96 fn invert_if_remove_not() {
99 "fn f() { $0if !cond { 3 * 2 } else { 1 } }",
100 "fn f() { if cond { 1 } else { 3 * 2 } }",
105 fn invert_if_general_case() {
108 "fn f() { i$0f cond { 3 * 2 } else { 1 } }",
109 "fn f() { if !cond { 1 } else { 3 * 2 } }",
114 fn invert_if_doesnt_apply_with_cursor_not_on_if() {
115 check_assist_not_applicable(invert_if, "fn f() { if !$0cond { 3 * 2 } else { 1 } }")
119 fn invert_if_doesnt_apply_with_if_let() {
120 check_assist_not_applicable(
122 "fn f() { i$0f let Some(_) = Some(1) { 1 } else { 0 } }",
127 fn invert_if_option_case() {
130 "fn f() { if$0 doc_style.is_some() { Class::DocComment } else { Class::Comment } }",
131 "fn f() { if doc_style.is_none() { Class::Comment } else { Class::DocComment } }",
136 fn invert_if_result_case() {
139 "fn f() { i$0f doc_style.is_err() { Class::Err } else { Class::Ok } }",
140 "fn f() { if doc_style.is_ok() { Class::Ok } else { Class::Err } }",