]> git.lizzy.rs Git - rust.git/blob - crates/ra_assists/src/assists/invert_if.rs
initial invert_if
[rust.git] / crates / ra_assists / src / assists / invert_if.rs
1 use hir::db::HirDatabase;
2 use ra_syntax::ast::{self, AstNode};
3 use ra_syntax::{TextRange, TextUnit};
4
5 use crate::{Assist, AssistCtx, AssistId};
6 use super::apply_demorgan::undo_negation;
7
8 // Assist: invert_if
9 //
10 // Apply invert_if
11 // This transforms if expressions of the form `if !x {A} else {B}` into `if x {B} else {A}`
12 // This also works with `!=`. This assist can only be applied with the cursor
13 // on `if`.
14 //
15 // ```
16 // fn main() {
17 //     if<|> !y {A} else {B}
18 // }
19 // ```
20 // ->
21 // ```
22 // fn main() {
23 //     if y {B} else {A}
24 // }
25 // ```
26
27
28 pub(crate) fn invert_if(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
29     let expr = ctx.find_node_at_offset::<ast::IfExpr>()?;
30     let expr_range = expr.syntax().text_range();
31     let if_range = TextRange::offset_len(expr_range.start(), TextUnit::from_usize(2));
32     let cursor_in_range = ctx.frange.range.is_subrange(&if_range);
33     if !cursor_in_range {
34         return None;
35     }
36
37     let cond = expr.condition()?.expr()?.syntax().clone();
38     let then_node = expr.then_branch()?.syntax().clone();
39
40     if let ast::ElseBranch::Block(else_block) = expr.else_branch()? {
41         let flip_cond = undo_negation(cond.clone())?;
42         let cond_range = cond.text_range();
43         let else_node = else_block.syntax();
44         let else_range = else_node.text_range();
45         let then_range = then_node.text_range();
46         ctx.add_assist(AssistId("invert_if"), "invert if branches", |edit| {
47             edit.target(if_range);
48             edit.replace(cond_range, flip_cond);
49             edit.replace(else_range, then_node.text());
50             edit.replace(then_range, else_node.text());
51         })
52
53     } else {
54         None
55     }
56
57
58 }
59
60 #[cfg(test)]
61 mod tests {
62     use super::*;
63
64     use crate::helpers::{check_assist, check_assist_not_applicable};
65
66     #[test]
67     fn invert_if_remove_inequality() {
68         check_assist(invert_if, "fn f() { i<|>f x != 3 {1} else {3 + 2} }", "fn f() { i<|>f x == 3 {3 + 2} else {1} }")
69     }
70
71     #[test]
72     fn invert_if_remove_not() {
73         check_assist(invert_if, "fn f() { <|>if !cond {3 * 2} else {1} }", "fn f() { <|>if cond {1} else {3 * 2} }")
74     }
75
76     #[test]
77     fn invert_if_doesnt_apply_with_cursor_not_on_if() {
78         check_assist_not_applicable(invert_if, "fn f() { if !<|>cond {3 * 2} else {1} }")
79     }
80
81     #[test]
82     fn invert_if_doesnt_apply_without_negated() {
83         check_assist_not_applicable(invert_if, "fn f() { i<|>f cond {3 * 2} else {1} }")
84     }
85 }