aboutsummaryrefslogtreecommitdiff
path: root/crates/ide_assists/src/handlers/flip_binexpr.rs
blob: 209e5d43c246f7b5e80bb669fba140984716e655 (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
use syntax::ast::{AstNode, BinExpr, BinOp};

use crate::{AssistContext, AssistId, AssistKind, Assists};

// Assist: flip_binexpr
//
// Flips operands of a binary expression.
//
// ```
// fn main() {
//     let _ = 90 +$0 2;
// }
// ```
// ->
// ```
// fn main() {
//     let _ = 2 + 90;
// }
// ```
pub(crate) fn flip_binexpr(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
    let expr = ctx.find_node_at_offset::<BinExpr>()?;
    let lhs = expr.lhs()?.syntax().clone();
    let rhs = expr.rhs()?.syntax().clone();
    let op_range = expr.op_token()?.text_range();
    // The assist should be applied only if the cursor is on the operator
    let cursor_in_range = op_range.contains_range(ctx.frange.range);
    if !cursor_in_range {
        return None;
    }
    let action: FlipAction = expr.op_kind()?.into();
    // The assist should not be applied for certain operators
    if let FlipAction::DontFlip = action {
        return None;
    }

    acc.add(
        AssistId("flip_binexpr", AssistKind::RefactorRewrite),
        "Flip binary expression",
        op_range,
        |edit| {
            if let FlipAction::FlipAndReplaceOp(new_op) = action {
                edit.replace(op_range, new_op);
            }
            edit.replace(lhs.text_range(), rhs.text());
            edit.replace(rhs.text_range(), lhs.text());
        },
    )
}

enum FlipAction {
    // Flip the expression
    Flip,
    // Flip the expression and replace the operator with this string
    FlipAndReplaceOp(&'static str),
    // Do not flip the expression
    DontFlip,
}

impl From<BinOp> for FlipAction {
    fn from(op_kind: BinOp) -> Self {
        match op_kind {
            kind if kind.is_assignment() => FlipAction::DontFlip,
            BinOp::GreaterTest => FlipAction::FlipAndReplaceOp("<"),
            BinOp::GreaterEqualTest => FlipAction::FlipAndReplaceOp("<="),
            BinOp::LesserTest => FlipAction::FlipAndReplaceOp(">"),
            BinOp::LesserEqualTest => FlipAction::FlipAndReplaceOp(">="),
            _ => FlipAction::Flip,
        }
    }
}

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

    use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};

    #[test]
    fn flip_binexpr_target_is_the_op() {
        check_assist_target(flip_binexpr, "fn f() { let res = 1 ==$0 2; }", "==")
    }

    #[test]
    fn flip_binexpr_not_applicable_for_assignment() {
        check_assist_not_applicable(flip_binexpr, "fn f() { let mut _x = 1; _x +=$0 2 }")
    }

    #[test]
    fn flip_binexpr_works_for_eq() {
        check_assist(flip_binexpr, "fn f() { let res = 1 ==$0 2; }", "fn f() { let res = 2 == 1; }")
    }

    #[test]
    fn flip_binexpr_works_for_gt() {
        check_assist(flip_binexpr, "fn f() { let res = 1 >$0 2; }", "fn f() { let res = 2 < 1; }")
    }

    #[test]
    fn flip_binexpr_works_for_lteq() {
        check_assist(flip_binexpr, "fn f() { let res = 1 <=$0 2; }", "fn f() { let res = 2 >= 1; }")
    }

    #[test]
    fn flip_binexpr_works_for_complex_expr() {
        check_assist(
            flip_binexpr,
            "fn f() { let res = (1 + 1) ==$0 (2 + 2); }",
            "fn f() { let res = (2 + 2) == (1 + 1); }",
        )
    }

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