1 use std::iter::successors;
9 use crate::{AssistContext, AssistId, AssistKind, Assists, TextRange};
11 // Assist: merge_match_arms
13 // Merges identical match arms.
16 // enum Action { Move { distance: u32 }, Stop }
18 // fn handle(action: Action) {
20 // $0Action::Move(..) => foo(),
21 // Action::Stop => foo(),
27 // enum Action { Move { distance: u32 }, Stop }
29 // fn handle(action: Action) {
31 // Action::Move(..) | Action::Stop => foo(),
35 pub(crate) fn merge_match_arms(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
36 let current_arm = ctx.find_node_at_offset::<ast::MatchArm>()?;
37 // Don't try to handle arms with guards for now - can add support for this later
38 if current_arm.guard().is_some() {
41 let current_expr = current_arm.expr()?;
42 let current_text_range = current_arm.syntax().text_range();
44 // We check if the following match arms match this one. We could, but don't,
45 // compare to the previous match arm as well.
46 let arms_to_merge = successors(Some(current_arm), |it| neighbor(it, Direction::Next))
48 if arm.guard().is_some() {
52 Some(expr) => expr.syntax().text() == current_expr.syntax().text(),
58 if arms_to_merge.len() <= 1 {
63 AssistId("merge_match_arms", AssistKind::RefactorRewrite),
67 let pats = if arms_to_merge.iter().any(contains_placeholder) {
72 .filter_map(ast::MatchArm::pat)
73 .map(|x| x.syntax().to_string())
74 .collect::<Vec<String>>()
78 let arm = format!("{} => {}", pats, current_expr.syntax().text());
80 let start = arms_to_merge.first().unwrap().syntax().text_range().start();
81 let end = arms_to_merge.last().unwrap().syntax().text_range().end();
83 edit.replace(TextRange::new(start, end), arm);
88 fn contains_placeholder(a: &ast::MatchArm) -> bool {
89 matches!(a.pat(), Some(ast::Pat::WildcardPat(..)))
94 use crate::tests::{check_assist, check_assist_not_applicable};
99 fn merge_match_arms_single_patterns() {
122 X::A | X::B => { 1i32 }
131 fn merge_match_arms_multiple_patterns() {
136 enum X { A, B, C, D, E }
141 X::A | X::B => {$0 1i32 },
142 X::C | X::D => { 1i32 },
149 enum X { A, B, C, D, E }
154 X::A | X::B | X::C | X::D => { 1i32 },
163 fn merge_match_arms_placeholder_pattern() {
168 enum X { A, B, C, D, E }
181 enum X { A, B, C, D, E }
195 fn merges_all_subsequent_arms() {
199 enum X { A, B, C, D, E }
212 enum X { A, B, C, D, E }
216 X::A | X::B | X::C => 92,
226 fn merge_match_arms_rejects_guards() {
227 check_assist_not_applicable(
240 X::A(a) if a > 5 => { $01i32 },