aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/flip_eq_operands.rs
diff options
context:
space:
mode:
authorMarco Groppo <[email protected]>2019-03-24 13:31:44 +0000
committerMarco Groppo <[email protected]>2019-03-24 13:42:11 +0000
commit481d3f56cf012789741d5d238f587b87b427a0f4 (patch)
tree9dd514418ff843ab84f14af3a9850af5a5012aa9 /crates/ra_assists/src/flip_eq_operands.rs
parent18a8f48039fbfcbbf58e1dadcc95465fe9503691 (diff)
Assist to flip equality (==) and negative equality (!=) operands.
Diffstat (limited to 'crates/ra_assists/src/flip_eq_operands.rs')
-rw-r--r--crates/ra_assists/src/flip_eq_operands.rs87
1 files changed, 87 insertions, 0 deletions
diff --git a/crates/ra_assists/src/flip_eq_operands.rs b/crates/ra_assists/src/flip_eq_operands.rs
new file mode 100644
index 000000000..22494a7c7
--- /dev/null
+++ b/crates/ra_assists/src/flip_eq_operands.rs
@@ -0,0 +1,87 @@
1use hir::db::HirDatabase;
2use ra_syntax::{
3 ast::{AstNode, BinExpr, BinOp}
4};
5
6use crate::{AssistCtx, Assist, AssistId};
7
8pub(crate) fn flip_eq_operands(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
9 let expr = ctx.node_at_offset::<BinExpr>()?;
10 let allowed_ops = [BinOp::EqualityTest, BinOp::NegatedEqualityTest];
11 let expr_op = expr.op()?;
12 if ! allowed_ops.iter().any(|o| *o == expr_op) {
13 return None;
14 }
15 let node = expr.syntax();
16 let prev = node.first_child()?;
17 let next = node.last_child()?;
18 ctx.add_action(AssistId("flip_eq_operands"), "flip equality operands", |edit| {
19 edit.target(node.range());
20 edit.replace(prev.range(), next.text());
21 edit.replace(next.range(), prev.text());
22 });
23
24 ctx.build()
25}
26
27#[cfg(test)]
28mod tests {
29 use super::*;
30
31 use crate::helpers::{check_assist, check_assist_target};
32
33 #[test]
34 fn flip_eq_operands_for_simple_stmt() {
35 check_assist(
36 flip_eq_operands,
37 "fn f() { let res = 1 ==<|> 2; }",
38 "fn f() { let res = 2 ==<|> 1; }",
39 )
40 }
41
42 #[test]
43 fn flip_neq_operands_for_simple_stmt() {
44 check_assist(
45 flip_eq_operands,
46 "fn f() { let res = 1 !=<|> 2; }",
47 "fn f() { let res = 2 !=<|> 1; }",
48 )
49 }
50
51 #[test]
52 fn flip_eq_operands_for_complex_stmt() {
53 check_assist(
54 flip_eq_operands,
55 "fn f() { let res = (1 + 1) ==<|> (2 + 2); }",
56 "fn f() { let res = (2 + 2) ==<|> (1 + 1); }",
57 )
58 }
59
60 #[test]
61 fn flip_eq_operands_in_match_expr() {
62 check_assist(
63 flip_eq_operands,
64 r#"
65 fn dyn_eq(&self, other: &dyn Diagnostic) -> bool {
66 match other.downcast_ref::<Self>() {
67 None => false,
68 Some(it) => it ==<|> self,
69 }
70 }
71 "#,
72 r#"
73 fn dyn_eq(&self, other: &dyn Diagnostic) -> bool {
74 match other.downcast_ref::<Self>() {
75 None => false,
76 Some(it) => self ==<|> it,
77 }
78 }
79 "#,
80 )
81 }
82
83 #[test]
84 fn flip_eq_operands_target() {
85 check_assist_target(flip_eq_operands, "fn f() { let res = 1 ==<|> 2; }", "1 == 2")
86 }
87}