From 3a64a85a5279ab0fcd45b2712cb544929e86f2a0 Mon Sep 17 00:00:00 2001 From: Wesley Norris Date: Sat, 26 Oct 2019 16:24:48 -0400 Subject: 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. --- crates/ra_assists/src/assists/flip_trait_bound.rs | 32 +++++++++++++++++++++++ crates/ra_assists/src/lib.rs | 2 ++ 2 files changed, 34 insertions(+) create mode 100644 crates/ra_assists/src/assists/flip_trait_bound.rs (limited to 'crates/ra_assists') diff --git a/crates/ra_assists/src/assists/flip_trait_bound.rs b/crates/ra_assists/src/assists/flip_trait_bound.rs new file mode 100644 index 000000000..a2c954ec5 --- /dev/null +++ b/crates/ra_assists/src/assists/flip_trait_bound.rs @@ -0,0 +1,32 @@ +//! Assist for swapping traits inside of a trait bound list +//! +//! E.g. `A + B` => `B + A` when the cursor is placed by the `+` inside of a +//! trait bound list + +use hir::db::HirDatabase; +use ra_syntax::{algo::non_trivia_sibling, ast::TypeBoundList, Direction, T}; + +use crate::{Assist, AssistCtx, AssistId}; + +/// Flip trait bound assist. +pub(crate) fn flip_trait_bound(mut ctx: AssistCtx) -> Option { + // Make sure we're in a `TypeBoundList` + ctx.node_at_offset::()?; + + // We want to replicate the behavior of `flip_binexpr` by only suggesting + // the assist when the cursor is on a `+` + let plus = ctx.token_at_offset().find(|tkn| tkn.kind() == T![+])?; + + let (before, after) = ( + non_trivia_sibling(plus.clone().into(), Direction::Prev)?, + non_trivia_sibling(plus.clone().into(), Direction::Next)?, + ); + + ctx.add_action(AssistId("flip_trait_bound"), "flip trait bound", |edit| { + edit.target(plus.text_range()); + edit.replace(before.text_range(), after.to_string()); + edit.replace(after.text_range(), before.to_string()); + }); + + ctx.build() +} diff --git a/crates/ra_assists/src/lib.rs b/crates/ra_assists/src/lib.rs index de576324f..871d49960 100644 --- a/crates/ra_assists/src/lib.rs +++ b/crates/ra_assists/src/lib.rs @@ -97,6 +97,7 @@ mod assists { mod apply_demorgan; mod flip_comma; mod flip_binexpr; + mod flip_trait_bound; mod change_visibility; mod fill_match_arms; mod merge_match_arms; @@ -123,6 +124,7 @@ mod assists { merge_match_arms::merge_match_arms, flip_comma::flip_comma, flip_binexpr::flip_binexpr, + flip_trait_bound::flip_trait_bound, introduce_variable::introduce_variable, replace_if_let_with_match::replace_if_let_with_match, split_import::split_import, -- cgit v1.2.3