2 use std::{collections::HashMap, iter::successors};
5 ast::{self, AstNode, HasName, MatchArm, Pat},
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 return 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: &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 if let (Some(Some(current_arm_type)), Some(other_arm_type)) =
105 (current_arm_types.get(&other_arm_type_name), other_arm_type)
107 if other_arm_type.original != current_arm_type.original {
111 // No corresponding field found
119 fn get_arm_types(context: &AssistContext, arm: &MatchArm) -> HashMap<String, Option<TypeInfo>> {
120 let mut mapping: HashMap<String, Option<TypeInfo>> = HashMap::new();
124 map: &mut HashMap<String, Option<TypeInfo>>,
127 if let Some(local_pat) = pat {
129 Some(ast::Pat::TupleStructPat(tuple)) => {
130 for field in tuple.fields() {
131 recurse(&Some(field), map, ctx);
134 Some(ast::Pat::TuplePat(tuple)) => {
135 for field in tuple.fields() {
136 recurse(&Some(field), map, ctx);
139 Some(ast::Pat::RecordPat(record)) => {
140 if let Some(field_list) = record.record_pat_field_list() {
141 for field in field_list.fields() {
142 recurse(&field.pat(), map, ctx);
146 Some(ast::Pat::IdentPat(ident_pat)) => {
147 if let Some(name) = ident_pat.name() {
148 let pat_type = ctx.sema.type_of_pat(local_pat);
149 map.insert(name.text().to_string(), pat_type);
157 recurse(&arm.pat(), &mut mapping, &context);
163 use crate::tests::{check_assist, check_assist_not_applicable};
168 fn merge_match_arms_single_patterns() {
191 X::A | X::B => { 1i32 },
200 fn merge_match_arms_multiple_patterns() {
205 enum X { A, B, C, D, E }
210 X::A | X::B => {$0 1i32 },
211 X::C | X::D => { 1i32 },
218 enum X { A, B, C, D, E }
223 X::A | X::B | X::C | X::D => { 1i32 },
232 fn merge_match_arms_placeholder_pattern() {
237 enum X { A, B, C, D, E }
250 enum X { A, B, C, D, E }
264 fn merges_all_subsequent_arms() {
268 enum X { A, B, C, D, E }
281 enum X { A, B, C, D, E }
285 X::A | X::B | X::C => 92,
295 fn merge_match_arms_rejects_guards() {
296 check_assist_not_applicable(
309 X::A(a) if a > 5 => { $01i32 },
319 fn merge_match_arms_different_type() {
320 check_assist_not_applicable(
322 r#"//- minicore: result
324 match Result::<f64, f32>::Ok(0f64) {
325 Ok(x) => $0x.classify(),
326 Err(x) => x.classify()
334 fn merge_match_arms_different_type_multiple_fields() {
335 check_assist_not_applicable(
337 r#"//- minicore: result
339 match Result::<(f64, f64), (f32, f32)>::Ok((0f64, 0f64)) {
340 Ok(x) => $0x.1.classify(),
341 Err(x) => x.1.classify()
349 fn merge_match_arms_same_type_multiple_fields() {
352 r#"//- minicore: result
354 match Result::<(f64, f64), (f64, f64)>::Ok((0f64, 0f64)) {
355 Ok(x) => $0x.1.classify(),
356 Err(x) => x.1.classify()
362 match Result::<(f64, f64), (f64, f64)>::Ok((0f64, 0f64)) {
363 Ok(x) | Err(x) => x.1.classify(),
371 fn merge_match_arms_same_type_subsequent_arm_with_different_type_in_other() {
383 MyEnum::OptionA(x) => $0x.classify(),
384 MyEnum::OptionB(x) => x.classify(),
385 MyEnum::OptionC(x) => x.classify(),
398 MyEnum::OptionA(x) | MyEnum::OptionB(x) => x.classify(),
399 MyEnum::OptionC(x) => x.classify(),
407 fn merge_match_arms_same_type_skip_arm_with_different_type_in_between() {
408 check_assist_not_applicable(
419 MyEnum::OptionA(x) => $0x.classify(),
420 MyEnum::OptionB(x) => x.classify(),
421 MyEnum::OptionC(x) => x.classify(),
429 fn merge_match_arms_same_type_different_number_of_fields() {
430 check_assist_not_applicable(
432 r#"//- minicore: result
434 match Result::<(f64, f64, f64), (f64, f64)>::Ok((0f64, 0f64, 0f64)) {
435 Ok(x) => $0x.1.classify(),
436 Err(x) => x.1.classify()
444 fn merge_match_same_destructuring_different_types() {
445 check_assist_not_applicable(
454 let p = Point { x: 0, y: 7 };
457 Point { x, y: 0 } => $0"",
458 Point { x: 0, y } => "",
459 Point { x, y } => "",
467 fn merge_match_arms_range() {
486 'a'..='j' | 'c'..='z' => "",
495 fn merge_match_arms_enum_without_field() {
496 check_assist_not_applicable(
506 MyEnum::NoField => $0"",
507 MyEnum::AField(x) => ""
515 fn merge_match_arms_enum_destructuring_different_types() {
516 check_assist_not_applicable(
520 Move { x: i32, y: i32 },
526 MyEnum::Move { x, y } => $0"",
527 MyEnum::Write(text) => "",
535 fn merge_match_arms_enum_destructuring_same_types() {
540 Move { x: i32, y: i32 },
541 Crawl { x: i32, y: i32 }
546 MyEnum::Move { x, y } => $0"",
547 MyEnum::Crawl { x, y } => "",
553 Move { x: i32, y: i32 },
554 Crawl { x: i32, y: i32 }
559 MyEnum::Move { x, y } | MyEnum::Crawl { x, y } => "",
567 fn merge_match_arms_enum_destructuring_same_types_different_name() {
568 check_assist_not_applicable(
572 Move { x: i32, y: i32 },
573 Crawl { a: i32, b: i32 }
578 MyEnum::Move { x, y } => $0"",
579 MyEnum::Crawl { a, b } => "",
587 fn merge_match_arms_enum_nested_pattern_different_names() {
588 check_assist_not_applicable(
598 Move { x: i32, y: i32 },
603 fn main(msg: Message) {
605 Message::ChangeColor(Color::Rgb(r, g, b)) => $0"",
606 Message::ChangeColor(Color::Hsv(h, s, v)) => "",
615 fn merge_match_arms_enum_nested_pattern_same_names() {
626 Move { x: i32, y: i32 },
631 fn main(msg: Message) {
633 Message::ChangeColor(Color::Rgb(a, b, c)) => $0"",
634 Message::ChangeColor(Color::Hsv(a, b, c)) => "",
647 Move { x: i32, y: i32 },
652 fn main(msg: Message) {
654 Message::ChangeColor(Color::Rgb(a, b, c)) | Message::ChangeColor(Color::Hsv(a, b, c)) => "",
663 fn merge_match_arms_enum_destructuring_with_ignore() {
668 Move { x: i32, a: i32 },
669 Crawl { x: i32, b: i32 }
674 MyEnum::Move { x, .. } => $0"",
675 MyEnum::Crawl { x, .. } => "",
681 Move { x: i32, a: i32 },
682 Crawl { x: i32, b: i32 }
687 MyEnum::Move { x, .. } | MyEnum::Crawl { x, .. } => "",
695 fn merge_match_arms_nested_with_conflicting_identifier() {
696 check_assist_not_applicable(
705 Move { x: i32, y: i32 },
706 ChangeColor(u8, Color),
709 fn main(msg: Message) {
711 Message::ChangeColor(x, Color::Rgb(y, b, c)) => $0"",
712 Message::ChangeColor(y, Color::Hsv(x, b, c)) => "",
721 fn merge_match_arms_tuple() {
722 check_assist_not_applicable(