2019-07-04 15:05:17 -05:00
|
|
|
use ra_syntax::{algo::non_trivia_sibling, Direction, T};
|
2019-01-03 06:08:32 -06:00
|
|
|
|
2019-07-04 15:05:17 -05:00
|
|
|
use crate::{Assist, AssistCtx, AssistId};
|
2019-01-03 06:08:32 -06:00
|
|
|
|
2019-10-26 11:08:13 -05:00
|
|
|
// Assist: flip_comma
|
|
|
|
//
|
|
|
|
// Flips two comma-separated items.
|
|
|
|
//
|
|
|
|
// ```
|
|
|
|
// fn main() {
|
|
|
|
// ((1, 2),<|> (3, 4));
|
|
|
|
// }
|
|
|
|
// ```
|
|
|
|
// ->
|
|
|
|
// ```
|
|
|
|
// fn main() {
|
|
|
|
// ((3, 4), (1, 2));
|
|
|
|
// }
|
|
|
|
// ```
|
2020-02-06 09:58:57 -06:00
|
|
|
pub(crate) fn flip_comma(ctx: AssistCtx) -> Option<Assist> {
|
2019-10-27 03:45:59 -05:00
|
|
|
let comma = ctx.find_token_at_offset(T![,])?;
|
2019-07-19 03:24:41 -05:00
|
|
|
let prev = non_trivia_sibling(comma.clone().into(), Direction::Prev)?;
|
|
|
|
let next = non_trivia_sibling(comma.clone().into(), Direction::Next)?;
|
2019-07-30 08:33:58 -05:00
|
|
|
|
|
|
|
// Don't apply a "flip" in case of a last comma
|
|
|
|
// that typically comes before punctuation
|
|
|
|
if next.kind().is_punct() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
2020-01-14 11:32:26 -06:00
|
|
|
ctx.add_assist(AssistId("flip_comma"), "Flip comma", |edit| {
|
2019-07-20 04:58:27 -05:00
|
|
|
edit.target(comma.text_range());
|
|
|
|
edit.replace(prev.text_range(), next.to_string());
|
|
|
|
edit.replace(next.text_range(), prev.to_string());
|
2019-10-27 09:35:37 -05:00
|
|
|
})
|
2019-01-03 06:08:32 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2019-02-03 12:26:35 -06:00
|
|
|
|
2019-02-08 17:34:05 -06:00
|
|
|
use crate::helpers::{check_assist, check_assist_target};
|
2019-01-03 06:08:32 -06:00
|
|
|
|
|
|
|
#[test]
|
2019-01-03 09:59:17 -06:00
|
|
|
fn flip_comma_works_for_function_parameters() {
|
|
|
|
check_assist(
|
|
|
|
flip_comma,
|
2019-01-03 06:08:32 -06:00
|
|
|
"fn foo(x: i32,<|> y: Result<(), ()>) {}",
|
|
|
|
"fn foo(y: Result<(), ()>,<|> x: i32) {}",
|
|
|
|
)
|
|
|
|
}
|
2019-02-08 17:34:05 -06:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn flip_comma_target() {
|
|
|
|
check_assist_target(flip_comma, "fn foo(x: i32,<|> y: Result<(), ()>) {}", ",")
|
|
|
|
}
|
2019-07-30 08:33:58 -05:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
#[should_panic]
|
|
|
|
fn flip_comma_before_punct() {
|
|
|
|
// See https://github.com/rust-analyzer/rust-analyzer/issues/1619
|
|
|
|
// "Flip comma" assist shouldn't be applicable to the last comma in enum or struct
|
|
|
|
// declaration body.
|
2019-07-30 09:02:29 -05:00
|
|
|
check_assist_target(
|
|
|
|
flip_comma,
|
|
|
|
"pub enum Test { \
|
|
|
|
A,<|> \
|
|
|
|
}",
|
|
|
|
",",
|
|
|
|
);
|
|
|
|
|
|
|
|
check_assist_target(
|
|
|
|
flip_comma,
|
|
|
|
"pub struct Test { \
|
|
|
|
foo: usize,<|> \
|
|
|
|
}",
|
|
|
|
",",
|
|
|
|
);
|
2019-07-30 08:33:58 -05:00
|
|
|
}
|
2019-01-03 06:08:32 -06:00
|
|
|
}
|