aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/flip_comma.rs
blob: a9b1081117aa1fb3beb00ccc9077782d005aac86 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use hir::db::HirDatabase;
use ra_syntax::{
    Direction,
    SyntaxKind::COMMA,
    algo::non_trivia_sibling,
};

use crate::{AssistCtx, Assist, AssistId};

pub(crate) fn flip_comma(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
    let comma = ctx.token_at_offset().find(|leaf| leaf.kind() == COMMA)?;
    let prev = non_trivia_sibling(comma.into(), Direction::Prev)?;
    let next = non_trivia_sibling(comma.into(), Direction::Next)?;
    ctx.add_action(AssistId("flip_comma"), "flip comma", |edit| {
        edit.target(comma.range());
        edit.replace(prev.range(), next.to_string());
        edit.replace(next.range(), prev.to_string());
    });

    ctx.build()
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::helpers::{check_assist, check_assist_target};

    #[test]
    fn flip_comma_works_for_function_parameters() {
        check_assist(
            flip_comma,
            "fn foo(x: i32,<|> y: Result<(), ()>) {}",
            "fn foo(y: Result<(), ()>,<|> x: i32) {}",
        )
    }

    #[test]
    fn flip_comma_target() {
        check_assist_target(flip_comma, "fn foo(x: i32,<|> y: Result<(), ()>) {}", ",")
    }
}