Skip to content

Commit 3a64a85

Browse files
repnopmatklad
authored andcommitted
Fixes #2054.
This adds the `flip_trait_bound` assist which allows for the swapping of two trait bounds in a trait list that are next to each other.
1 parent e46c73d commit 3a64a85

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//! Assist for swapping traits inside of a trait bound list
2+
//!
3+
//! E.g. `A + B` => `B + A` when the cursor is placed by the `+` inside of a
4+
//! trait bound list
5+
6+
use hir::db::HirDatabase;
7+
use ra_syntax::{algo::non_trivia_sibling, ast::TypeBoundList, Direction, T};
8+
9+
use crate::{Assist, AssistCtx, AssistId};
10+
11+
/// Flip trait bound assist.
12+
pub(crate) fn flip_trait_bound(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
13+
// Make sure we're in a `TypeBoundList`
14+
ctx.node_at_offset::<TypeBoundList>()?;
15+
16+
// We want to replicate the behavior of `flip_binexpr` by only suggesting
17+
// the assist when the cursor is on a `+`
18+
let plus = ctx.token_at_offset().find(|tkn| tkn.kind() == T![+])?;
19+
20+
let (before, after) = (
21+
non_trivia_sibling(plus.clone().into(), Direction::Prev)?,
22+
non_trivia_sibling(plus.clone().into(), Direction::Next)?,
23+
);
24+
25+
ctx.add_action(AssistId("flip_trait_bound"), "flip trait bound", |edit| {
26+
edit.target(plus.text_range());
27+
edit.replace(before.text_range(), after.to_string());
28+
edit.replace(after.text_range(), before.to_string());
29+
});
30+
31+
ctx.build()
32+
}

crates/ra_assists/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ mod assists {
9797
mod apply_demorgan;
9898
mod flip_comma;
9999
mod flip_binexpr;
100+
mod flip_trait_bound;
100101
mod change_visibility;
101102
mod fill_match_arms;
102103
mod merge_match_arms;
@@ -123,6 +124,7 @@ mod assists {
123124
merge_match_arms::merge_match_arms,
124125
flip_comma::flip_comma,
125126
flip_binexpr::flip_binexpr,
127+
flip_trait_bound::flip_trait_bound,
126128
introduce_variable::introduce_variable,
127129
replace_if_let_with_match::replace_if_let_with_match,
128130
split_import::split_import,

0 commit comments

Comments
 (0)