diff options
Diffstat (limited to 'crates/ra_assists/src/assists/flip_comma.rs')
-rw-r--r-- | crates/ra_assists/src/assists/flip_comma.rs | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/crates/ra_assists/src/assists/flip_comma.rs b/crates/ra_assists/src/assists/flip_comma.rs new file mode 100644 index 000000000..5ee7561bc --- /dev/null +++ b/crates/ra_assists/src/assists/flip_comma.rs | |||
@@ -0,0 +1,68 @@ | |||
1 | use hir::db::HirDatabase; | ||
2 | use ra_syntax::{algo::non_trivia_sibling, Direction, T}; | ||
3 | |||
4 | use crate::{Assist, AssistCtx, AssistId}; | ||
5 | |||
6 | pub(crate) fn flip_comma(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> { | ||
7 | let comma = ctx.token_at_offset().find(|leaf| leaf.kind() == T![,])?; | ||
8 | let prev = non_trivia_sibling(comma.clone().into(), Direction::Prev)?; | ||
9 | let next = non_trivia_sibling(comma.clone().into(), Direction::Next)?; | ||
10 | |||
11 | // Don't apply a "flip" in case of a last comma | ||
12 | // that typically comes before punctuation | ||
13 | if next.kind().is_punct() { | ||
14 | return None; | ||
15 | } | ||
16 | |||
17 | ctx.add_action(AssistId("flip_comma"), "flip comma", |edit| { | ||
18 | edit.target(comma.text_range()); | ||
19 | edit.replace(prev.text_range(), next.to_string()); | ||
20 | edit.replace(next.text_range(), prev.to_string()); | ||
21 | }); | ||
22 | |||
23 | ctx.build() | ||
24 | } | ||
25 | |||
26 | #[cfg(test)] | ||
27 | mod tests { | ||
28 | use super::*; | ||
29 | |||
30 | use crate::helpers::{check_assist, check_assist_target}; | ||
31 | |||
32 | #[test] | ||
33 | fn flip_comma_works_for_function_parameters() { | ||
34 | check_assist( | ||
35 | flip_comma, | ||
36 | "fn foo(x: i32,<|> y: Result<(), ()>) {}", | ||
37 | "fn foo(y: Result<(), ()>,<|> x: i32) {}", | ||
38 | ) | ||
39 | } | ||
40 | |||
41 | #[test] | ||
42 | fn flip_comma_target() { | ||
43 | check_assist_target(flip_comma, "fn foo(x: i32,<|> y: Result<(), ()>) {}", ",") | ||
44 | } | ||
45 | |||
46 | #[test] | ||
47 | #[should_panic] | ||
48 | fn flip_comma_before_punct() { | ||
49 | // See https://github.com/rust-analyzer/rust-analyzer/issues/1619 | ||
50 | // "Flip comma" assist shouldn't be applicable to the last comma in enum or struct | ||
51 | // declaration body. | ||
52 | check_assist_target( | ||
53 | flip_comma, | ||
54 | "pub enum Test { \ | ||
55 | A,<|> \ | ||
56 | }", | ||
57 | ",", | ||
58 | ); | ||
59 | |||
60 | check_assist_target( | ||
61 | flip_comma, | ||
62 | "pub struct Test { \ | ||
63 | foo: usize,<|> \ | ||
64 | }", | ||
65 | ",", | ||
66 | ); | ||
67 | } | ||
68 | } | ||