aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/handlers/flip_comma.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/handlers/flip_comma.rs')
-rw-r--r--crates/ra_assists/src/handlers/flip_comma.rs80
1 files changed, 80 insertions, 0 deletions
diff --git a/crates/ra_assists/src/handlers/flip_comma.rs b/crates/ra_assists/src/handlers/flip_comma.rs
new file mode 100644
index 000000000..1dacf29f8
--- /dev/null
+++ b/crates/ra_assists/src/handlers/flip_comma.rs
@@ -0,0 +1,80 @@
1use ra_syntax::{algo::non_trivia_sibling, Direction, T};
2
3use crate::{Assist, AssistCtx, AssistId};
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// ```
20pub(crate) fn flip_comma(ctx: AssistCtx) -> Option<Assist> {
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 ctx.add_assist(AssistId("flip_comma"), "Flip comma", |edit| {
32 edit.target(comma.text_range());
33 edit.replace(prev.text_range(), next.to_string());
34 edit.replace(next.text_range(), prev.to_string());
35 })
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41
42 use crate::helpers::{check_assist, check_assist_target};
43
44 #[test]
45 fn flip_comma_works_for_function_parameters() {
46 check_assist(
47 flip_comma,
48 "fn foo(x: i32,<|> y: Result<(), ()>) {}",
49 "fn foo(y: Result<(), ()>,<|> x: i32) {}",
50 )
51 }
52
53 #[test]
54 fn flip_comma_target() {
55 check_assist_target(flip_comma, "fn foo(x: i32,<|> y: Result<(), ()>) {}", ",")
56 }
57
58 #[test]
59 #[should_panic]
60 fn flip_comma_before_punct() {
61 // See https://github.com/rust-analyzer/rust-analyzer/issues/1619
62 // "Flip comma" assist shouldn't be applicable to the last comma in enum or struct
63 // declaration body.
64 check_assist_target(
65 flip_comma,
66 "pub enum Test { \
67 A,<|> \
68 }",
69 ",",
70 );
71
72 check_assist_target(
73 flip_comma,
74 "pub struct Test { \
75 foo: usize,<|> \
76 }",
77 ",",
78 );
79 }
80}