2 use std::{collections::HashMap, iter::successors};
5 ast::{self, AstNode, HasName},
9 use crate::{AssistContext, AssistId, AssistKind, Assists, TextRange};
11 // Assist: merge_match_arms
13 // Merges the current match arm with the following if their bodies are identical.
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();
43 let current_arm_types = get_arm_types(&ctx, ¤t_arm);
45 // We check if the following match arms match this one. We could, but don't,
46 // compare to the previous match arm as well.
47 let arms_to_merge = successors(Some(current_arm), |it| neighbor(it, Direction::Next))
48 .take_while(|arm| match arm.expr() {
49 Some(expr) if arm.guard().is_none() => {
50 let same_text = expr.syntax().text() == current_expr.syntax().text();
55 are_same_types(¤t_arm_types, arm, ctx)
61 if arms_to_merge.len() <= 1 {
66 AssistId("merge_match_arms", AssistKind::RefactorRewrite),
70 let pats = if arms_to_merge.iter().any(contains_placeholder) {
75 .filter_map(ast::MatchArm::pat)
76 .map(|x| x.syntax().to_string())
77 .collect::<Vec<String>>()
81 let arm = format!("{} => {},", pats, current_expr.syntax().text());
83 if let [first, .., last] = &*arms_to_merge {
84 let start = first.syntax().text_range().start();
85 let end = last.syntax().text_range().end();
87 edit.replace(TextRange::new(start, end), arm);
93 fn contains_placeholder(a: &ast::MatchArm) -> bool {
94 matches!(a.pat(), Some(ast::Pat::WildcardPat(..)))
98 current_arm_types: &HashMap<String, Option<TypeInfo>>,
102 let arm_types = get_arm_types(&ctx, &arm);
103 for (other_arm_type_name, other_arm_type) in arm_types {
104 match (current_arm_types.get(&other_arm_type_name), other_arm_type) {
105 (Some(Some(current_arm_type)), Some(other_arm_type))
106 if other_arm_type.original == current_arm_type.original =>
118 context: &AssistContext,
120 ) -> HashMap<String, Option<TypeInfo>> {
121 let mut mapping: HashMap<String, Option<TypeInfo>> = HashMap::new();
124 map: &mut HashMap<String, Option<TypeInfo>>,
126 pat: &Option<ast::Pat>,
128 if let Some(local_pat) = pat {
130 Some(ast::Pat::TupleStructPat(tuple)) => {
131 for field in tuple.fields() {
132 recurse(map, ctx, &Some(field));
135 Some(ast::Pat::TuplePat(tuple)) => {
136 for field in tuple.fields() {
137 recurse(map, ctx, &Some(field));
140 Some(ast::Pat::RecordPat(record)) => {
141 if let Some(field_list) = record.record_pat_field_list() {
142 for field in field_list.fields() {
143 recurse(map, ctx, &field.pat());
147 Some(ast::Pat::ParenPat(parentheses)) => {
148 recurse(map, ctx, &parentheses.pat());
150 Some(ast::Pat::SlicePat(slice)) => {
151 for slice_pat in slice.pats() {
152 recurse(map, ctx, &Some(slice_pat));
155 Some(ast::Pat::IdentPat(ident_pat)) => {
156 if let Some(name) = ident_pat.name() {
157 let pat_type = ctx.sema.type_of_pat(local_pat);
158 map.insert(name.text().to_string(), pat_type);
166 recurse(&mut mapping, &context, &arm.pat());
172 use crate::tests::{check_assist, check_assist_not_applicable};
177 fn merge_match_arms_single_patterns() {
200 X::A | X::B => { 1i32 },
209 fn merge_match_arms_multiple_patterns() {
214 enum X { A, B, C, D, E }
219 X::A | X::B => {$0 1i32 },
220 X::C | X::D => { 1i32 },
227 enum X { A, B, C, D, E }
232 X::A | X::B | X::C | X::D => { 1i32 },
241 fn merge_match_arms_placeholder_pattern() {
246 enum X { A, B, C, D, E }
259 enum X { A, B, C, D, E }
273 fn merges_all_subsequent_arms() {
277 enum X { A, B, C, D, E }
290 enum X { A, B, C, D, E }
294 X::A | X::B | X::C => 92,
304 fn merge_match_arms_rejects_guards() {
305 check_assist_not_applicable(
318 X::A(a) if a > 5 => { $01i32 },
328 fn merge_match_arms_different_type() {
329 check_assist_not_applicable(
334 match Result::<f64, f32>::Ok(0f64) {
335 Ok(x) => $0x.classify(),
336 Err(x) => x.classify()
344 fn merge_match_arms_different_type_multiple_fields() {
345 check_assist_not_applicable(
350 match Result::<(f64, f64), (f32, f32)>::Ok((0f64, 0f64)) {
351 Ok(x) => $0x.1.classify(),
352 Err(x) => x.1.classify()
360 fn merge_match_arms_same_type_multiple_fields() {
366 match Result::<(f64, f64), (f64, f64)>::Ok((0f64, 0f64)) {
367 Ok(x) => $0x.1.classify(),
368 Err(x) => x.1.classify()
374 match Result::<(f64, f64), (f64, f64)>::Ok((0f64, 0f64)) {
375 Ok(x) | Err(x) => x.1.classify(),
383 fn merge_match_arms_same_type_subsequent_arm_with_different_type_in_other() {
395 MyEnum::OptionA(x) => $0x.classify(),
396 MyEnum::OptionB(x) => x.classify(),
397 MyEnum::OptionC(x) => x.classify(),
410 MyEnum::OptionA(x) | MyEnum::OptionB(x) => x.classify(),
411 MyEnum::OptionC(x) => x.classify(),
419 fn merge_match_arms_same_type_skip_arm_with_different_type_in_between() {
420 check_assist_not_applicable(
431 MyEnum::OptionA(x) => $0x.classify(),
432 MyEnum::OptionB(x) => x.classify(),
433 MyEnum::OptionC(x) => x.classify(),
441 fn merge_match_arms_same_type_different_number_of_fields() {
442 check_assist_not_applicable(
447 match Result::<(f64, f64, f64), (f64, f64)>::Ok((0f64, 0f64, 0f64)) {
448 Ok(x) => $0x.1.classify(),
449 Err(x) => x.1.classify()
457 fn merge_match_same_destructuring_different_types() {
458 check_assist_not_applicable(
467 let p = Point { x: 0, y: 7 };
470 Point { x, y: 0 } => $0"",
471 Point { x: 0, y } => "",
472 Point { x, y } => "",
480 fn merge_match_arms_range() {
499 'a'..='j' | 'c'..='z' => "",
508 fn merge_match_arms_enum_without_field() {
509 check_assist_not_applicable(
519 MyEnum::NoField => $0"",
520 MyEnum::AField(x) => ""
528 fn merge_match_arms_enum_destructuring_different_types() {
529 check_assist_not_applicable(
533 Move { x: i32, y: i32 },
539 MyEnum::Move { x, y } => $0"",
540 MyEnum::Write(text) => "",
548 fn merge_match_arms_enum_destructuring_same_types() {
553 Move { x: i32, y: i32 },
554 Crawl { x: i32, y: i32 }
559 MyEnum::Move { x, y } => $0"",
560 MyEnum::Crawl { x, y } => "",
566 Move { x: i32, y: i32 },
567 Crawl { x: i32, y: i32 }
572 MyEnum::Move { x, y } | MyEnum::Crawl { x, y } => "",
580 fn merge_match_arms_enum_destructuring_same_types_different_name() {
581 check_assist_not_applicable(
585 Move { x: i32, y: i32 },
586 Crawl { a: i32, b: i32 }
591 MyEnum::Move { x, y } => $0"",
592 MyEnum::Crawl { a, b } => "",
600 fn merge_match_arms_enum_nested_pattern_different_names() {
601 check_assist_not_applicable(
611 Move { x: i32, y: i32 },
616 fn main(msg: Message) {
618 Message::ChangeColor(Color::Rgb(r, g, b)) => $0"",
619 Message::ChangeColor(Color::Hsv(h, s, v)) => "",
628 fn merge_match_arms_enum_nested_pattern_same_names() {
639 Move { x: i32, y: i32 },
644 fn main(msg: Message) {
646 Message::ChangeColor(Color::Rgb(a, b, c)) => $0"",
647 Message::ChangeColor(Color::Hsv(a, b, c)) => "",
660 Move { x: i32, y: i32 },
665 fn main(msg: Message) {
667 Message::ChangeColor(Color::Rgb(a, b, c)) | Message::ChangeColor(Color::Hsv(a, b, c)) => "",
676 fn merge_match_arms_enum_destructuring_with_ignore() {
681 Move { x: i32, a: i32 },
682 Crawl { x: i32, b: i32 }
687 MyEnum::Move { x, .. } => $0"",
688 MyEnum::Crawl { x, .. } => "",
694 Move { x: i32, a: i32 },
695 Crawl { x: i32, b: i32 }
700 MyEnum::Move { x, .. } | MyEnum::Crawl { x, .. } => "",
708 fn merge_match_arms_nested_with_conflicting_identifier() {
709 check_assist_not_applicable(
718 Move { x: i32, y: i32 },
719 ChangeColor(u8, Color),
722 fn main(msg: Message) {
724 Message::ChangeColor(x, Color::Rgb(y, b, c)) => $0"",
725 Message::ChangeColor(y, Color::Hsv(x, b, c)) => "",
734 fn merge_match_arms_tuple() {
735 check_assist_not_applicable(
749 fn merge_match_arms_parentheses() {
750 check_assist_not_applicable(
757 ((((variable)))) => "",
766 fn merge_match_arms_refpat() {
767 check_assist_not_applicable(
771 let name = Some(String::from(""));
772 let n = String::from("");
784 fn merge_match_arms_slice() {
785 check_assist_not_applicable(
788 fn func(binary: &[u8]) {
791 [0x7f, b'E', b'L', b'F', ..] => $0"",
801 fn merge_match_arms_slice_identical() {
805 fn func(binary: &[u8]) {
808 [space, 5u8] => $0"",
815 fn func(binary: &[u8]) {
818 [space, 5u8] | [space] => "",