]> git.lizzy.rs Git - rust.git/blob - crates/assists/src/handlers/flip_comma.rs
Better fixture highlight
[rust.git] / crates / assists / src / handlers / flip_comma.rs
1 use syntax::{algo::non_trivia_sibling, Direction, T};
2
3 use 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),$0 (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_syntax_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)]
43 mod 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             r#"fn foo(x: i32,$0 y: Result<(), ()>) {}"#,
53             r#"fn foo(y: Result<(), ()>, x: i32) {}"#,
54         )
55     }
56
57     #[test]
58     fn flip_comma_target() {
59         check_assist_target(flip_comma, r#"fn foo(x: i32,$0 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,$0 \
72              }",
73             ",",
74         );
75
76         check_assist_target(
77             flip_comma,
78             "pub struct Test { \
79              foo: usize,$0 \
80              }",
81             ",",
82         );
83     }
84 }