]> git.lizzy.rs Git - rust.git/blob - crates/ra_assists/src/handlers/flip_comma.rs
Refactor assists API to be more convenient for adding new assists
[rust.git] / crates / ra_assists / src / handlers / flip_comma.rs
1 use ra_syntax::{algo::non_trivia_sibling, Direction, T};
2
3 use crate::{AssistContext, AssistId, Assists};
4
5 // Assist: flip_comma
6 //
7 // Flips two comma-separated items.
8 //
9 // ```
10 // fn main() {
11 //     ((1, 2),<|> (3, 4));
12 // }
13 // ```
14 // ->
15 // ```
16 // fn main() {
17 //     ((3, 4), (1, 2));
18 // }
19 // ```
20 pub(crate) fn flip_comma(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
21     let comma = ctx.find_token_at_offset(T![,])?;
22     let prev = non_trivia_sibling(comma.clone().into(), Direction::Prev)?;
23     let next = non_trivia_sibling(comma.clone().into(), Direction::Next)?;
24
25     // Don't apply a "flip" in case of a last comma
26     // that typically comes before punctuation
27     if next.kind().is_punct() {
28         return None;
29     }
30
31     acc.add(AssistId("flip_comma"), "Flip comma", comma.text_range(), |edit| {
32         edit.replace(prev.text_range(), next.to_string());
33         edit.replace(next.text_range(), prev.to_string());
34     })
35 }
36
37 #[cfg(test)]
38 mod tests {
39     use super::*;
40
41     use crate::tests::{check_assist, check_assist_target};
42
43     #[test]
44     fn flip_comma_works_for_function_parameters() {
45         check_assist(
46             flip_comma,
47             "fn foo(x: i32,<|> y: Result<(), ()>) {}",
48             "fn foo(y: Result<(), ()>,<|> x: i32) {}",
49         )
50     }
51
52     #[test]
53     fn flip_comma_target() {
54         check_assist_target(flip_comma, "fn foo(x: i32,<|> y: Result<(), ()>) {}", ",")
55     }
56
57     #[test]
58     #[should_panic]
59     fn flip_comma_before_punct() {
60         // See https://github.com/rust-analyzer/rust-analyzer/issues/1619
61         // "Flip comma" assist shouldn't be applicable to the last comma in enum or struct
62         // declaration body.
63         check_assist_target(
64             flip_comma,
65             "pub enum Test { \
66              A,<|> \
67              }",
68             ",",
69         );
70
71         check_assist_target(
72             flip_comma,
73             "pub struct Test { \
74              foo: usize,<|> \
75              }",
76             ",",
77         );
78     }
79 }