aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/flip_eq_operands.rs
blob: 22494a7c748f28e4c6f6038aa05dc8821f37bb64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use hir::db::HirDatabase;
use ra_syntax::{
    ast::{AstNode, BinExpr, BinOp}
};

use crate::{AssistCtx, Assist, AssistId};

pub(crate) fn flip_eq_operands(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
    let expr = ctx.node_at_offset::<BinExpr>()?;
    let allowed_ops = [BinOp::EqualityTest, BinOp::NegatedEqualityTest];
    let expr_op = expr.op()?;
    if ! allowed_ops.iter().any(|o| *o == expr_op) {
        return None;
    }
    let node = expr.syntax();
    let prev = node.first_child()?;
    let next = node.last_child()?;
    ctx.add_action(AssistId("flip_eq_operands"), "flip equality operands", |edit| {
        edit.target(node.range());
        edit.replace(prev.range(), next.text());
        edit.replace(next.range(), prev.text());
    });

    ctx.build()
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::helpers::{check_assist, check_assist_target};

    #[test]
    fn flip_eq_operands_for_simple_stmt() {
        check_assist(
            flip_eq_operands,
            "fn f() { let res = 1 ==<|> 2; }",
            "fn f() { let res = 2 ==<|> 1; }",
        )
    }

    #[test]
    fn flip_neq_operands_for_simple_stmt() {
        check_assist(
            flip_eq_operands,
            "fn f() { let res = 1 !=<|> 2; }",
            "fn f() { let res = 2 !=<|> 1; }",
        )
    }

    #[test]
    fn flip_eq_operands_for_complex_stmt() {
        check_assist(
            flip_eq_operands,
            "fn f() { let res = (1 + 1) ==<|> (2 + 2); }",
            "fn f() { let res = (2 + 2) ==<|> (1 + 1); }",
        )
    }

    #[test]
    fn flip_eq_operands_in_match_expr() {
        check_assist(
            flip_eq_operands,
            r#"
            fn dyn_eq(&self, other: &dyn Diagnostic) -> bool {
                match other.downcast_ref::<Self>() {
                    None => false,
                    Some(it) => it ==<|> self,
                }
            }
            "#,
            r#"
            fn dyn_eq(&self, other: &dyn Diagnostic) -> bool {
                match other.downcast_ref::<Self>() {
                    None => false,
                    Some(it) => self ==<|> it,
                }
            }
            "#,
        )
    }

    #[test]
    fn flip_eq_operands_target() {
        check_assist_target(flip_eq_operands, "fn f() { let res = 1 ==<|> 2; }", "1 == 2")
    }
}