rust-analyzer/crates/ra_assists/src/assists/flip_comma.rs

71 lines
1.9 KiB
Rust
Raw Normal View History

//! FIXME: write short doc here
2019-02-03 18:26:35 +00:00
use hir::db::HirDatabase;
use ra_syntax::{algo::non_trivia_sibling, Direction, T};
2019-01-03 12:08:32 +00:00
use crate::{Assist, AssistCtx, AssistId};
2019-01-03 12:08:32 +00:00
pub(crate) fn flip_comma(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
2019-05-15 12:35:47 +00:00
let comma = ctx.token_at_offset().find(|leaf| leaf.kind() == T![,])?;
2019-07-19 08:24:41 +00:00
let prev = non_trivia_sibling(comma.clone().into(), Direction::Prev)?;
let next = non_trivia_sibling(comma.clone().into(), Direction::Next)?;
2019-07-30 13:33:58 +00:00
// Don't apply a "flip" in case of a last comma
// that typically comes before punctuation
if next.kind().is_punct() {
return None;
}
2019-02-24 10:53:35 +00:00
ctx.add_action(AssistId("flip_comma"), "flip comma", |edit| {
2019-07-20 09:58:27 +00:00
edit.target(comma.text_range());
edit.replace(prev.text_range(), next.to_string());
edit.replace(next.text_range(), prev.to_string());
});
ctx.build()
2019-01-03 12:08:32 +00:00
}
#[cfg(test)]
mod tests {
use super::*;
2019-02-03 18:26:35 +00:00
2019-02-08 23:34:05 +00:00
use crate::helpers::{check_assist, check_assist_target};
2019-01-03 12:08:32 +00:00
#[test]
2019-01-03 15:59:17 +00:00
fn flip_comma_works_for_function_parameters() {
check_assist(
flip_comma,
2019-01-03 12:08:32 +00:00
"fn foo(x: i32,<|> y: Result<(), ()>) {}",
"fn foo(y: Result<(), ()>,<|> x: i32) {}",
)
}
2019-02-08 23:34:05 +00:00
#[test]
fn flip_comma_target() {
check_assist_target(flip_comma, "fn foo(x: i32,<|> y: Result<(), ()>) {}", ",")
}
2019-07-30 13:33:58 +00: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 14:02:29 +00:00
check_assist_target(
flip_comma,
"pub enum Test { \
A,<|> \
}",
",",
);
check_assist_target(
flip_comma,
"pub struct Test { \
foo: usize,<|> \
}",
",",
);
2019-07-30 13:33:58 +00:00
}
2019-01-03 12:08:32 +00:00
}