|
| 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 | +} |
0 commit comments