Skip to main content

ide_assists/handlers/
invert_if.rs

1use ide_db::syntax_helpers::node_ext::is_pattern_cond;
2use syntax::{
3    T,
4    ast::{self, AstNode, syntax_factory::SyntaxFactory},
5};
6
7use crate::{
8    AssistId,
9    assist_context::{AssistContext, Assists},
10    utils::invert_boolean_expression,
11};
12
13// Assist: invert_if
14//
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`.
17//
18// ```
19// fn main() {
20//     if$0 !y { A } else { B }
21// }
22// ```
23// ->
24// ```
25// fn main() {
26//     if y { B } else { A }
27// }
28// ```
29pub(crate) fn invert_if(acc: &mut Assists, ctx: &AssistContext<'_, '_>) -> Option<()> {
30    let if_keyword = ctx
31        .find_token_syntax_at_offset(T![if])
32        .or_else(|| ctx.find_token_syntax_at_offset(T![else]))?;
33    let expr = ast::IfExpr::cast(if_keyword.parent()?)?;
34    let if_range = if_keyword.text_range();
35    let cursor_in_range = if_range.contains_range(ctx.selection_trimmed());
36    if !cursor_in_range {
37        return None;
38    }
39
40    let cond = expr.condition()?;
41    // This assist should not apply for if-let.
42    if is_pattern_cond(cond.clone()) {
43        return None;
44    }
45
46    let then_node = expr.then_branch()?.syntax().clone();
47    let else_block = match expr.else_branch()? {
48        ast::ElseBranch::Block(it) => it,
49        ast::ElseBranch::IfExpr(_) => return None,
50    };
51
52    acc.add(AssistId::refactor_rewrite("invert_if"), "Invert if", if_range, |edit| {
53        let make = SyntaxFactory::without_mappings();
54        let flip_cond = invert_boolean_expression(&make, cond.clone());
55        edit.replace_ast(cond, flip_cond);
56
57        let else_node = else_block.syntax();
58        let else_range = else_node.text_range();
59        let then_range = then_node.text_range();
60
61        edit.replace(else_range, then_node.text());
62        edit.replace(then_range, else_node.text());
63    })
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    use crate::tests::{check_assist, check_assist_not_applicable};
71
72    #[test]
73    fn invert_if_composite_condition() {
74        check_assist(
75            invert_if,
76            "fn f() { i$0f x == 3 || x == 4 || x == 5 { 1 } else { 3 * 2 } }",
77            "fn f() { if !(x == 3 || x == 4 || x == 5) { 3 * 2 } else { 1 } }",
78        )
79    }
80
81    #[test]
82    fn invert_if_remove_not_parentheses() {
83        check_assist(
84            invert_if,
85            "fn f() { i$0f !(x == 3 || x == 4 || x == 5) { 3 * 2 } else { 1 } }",
86            "fn f() { if x == 3 || x == 4 || x == 5 { 1 } else { 3 * 2 } }",
87        )
88    }
89
90    #[test]
91    fn invert_if_remove_inequality() {
92        check_assist(
93            invert_if,
94            "fn f() { i$0f x != 3 { 1 } else { 3 + 2 } }",
95            "fn f() { if x == 3 { 3 + 2 } else { 1 } }",
96        )
97    }
98
99    #[test]
100    fn invert_if_remove_not() {
101        check_assist(
102            invert_if,
103            "fn f() { $0if !cond { 3 * 2 } else { 1 } }",
104            "fn f() { if cond { 1 } else { 3 * 2 } }",
105        )
106    }
107
108    #[test]
109    fn invert_if_general_case() {
110        check_assist(
111            invert_if,
112            "fn f() { i$0f cond { 3 * 2 } else { 1 } }",
113            "fn f() { if !cond { 1 } else { 3 * 2 } }",
114        )
115    }
116
117    #[test]
118    fn invert_if_on_else_keyword() {
119        check_assist(
120            invert_if,
121            "fn f() { if cond { 3 * 2 } e$0lse { 1 } }",
122            "fn f() { if !cond { 1 } else { 3 * 2 } }",
123        )
124    }
125
126    #[test]
127    fn invert_if_doesnt_apply_with_cursor_not_on_if() {
128        check_assist_not_applicable(invert_if, "fn f() { if !$0cond { 3 * 2 } else { 1 } }")
129    }
130
131    #[test]
132    fn invert_if_doesnt_apply_with_if_let() {
133        check_assist_not_applicable(
134            invert_if,
135            "fn f() { i$0f let Some(_) = Some(1) { 1 } else { 0 } }",
136        )
137    }
138
139    #[test]
140    fn invert_if_doesnt_apply_with_if_let_chain() {
141        check_assist_not_applicable(
142            invert_if,
143            "fn f() { i$0f x && let Some(_) = Some(1) { 1 } else { 0 } }",
144        );
145        check_assist_not_applicable(
146            invert_if,
147            "fn f() { i$0f let Some(_) = Some(1) && x { 1 } else { 0 } }",
148        );
149    }
150
151    #[test]
152    fn invert_if_option_case() {
153        check_assist(
154            invert_if,
155            "fn f() { if$0 doc_style.is_some() { Class::DocComment } else { Class::Comment } }",
156            "fn f() { if doc_style.is_none() { Class::Comment } else { Class::DocComment } }",
157        )
158    }
159
160    #[test]
161    fn invert_if_result_case() {
162        check_assist(
163            invert_if,
164            "fn f() { i$0f doc_style.is_err() { Class::Err } else { Class::Ok } }",
165            "fn f() { if doc_style.is_ok() { Class::Ok } else { Class::Err } }",
166        )
167    }
168}