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