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>>,
100 ctx: &AssistContext<'_>,
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 => {}
115 context: &AssistContext<'_>,
117 ) -> HashMap<String, Option<TypeInfo>> {
118 let mut mapping: HashMap<String, Option<TypeInfo>> = HashMap::new();
121 map: &mut HashMap<String, Option<TypeInfo>>,
122 ctx: &AssistContext<'_>,
123 pat: &Option<ast::Pat>,
125 if let Some(local_pat) = pat {
127 Some(ast::Pat::TupleStructPat(tuple)) => {
128 for field in tuple.fields() {
129 recurse(map, ctx, &Some(field));
132 Some(ast::Pat::TuplePat(tuple)) => {
133 for field in tuple.fields() {
134 recurse(map, ctx, &Some(field));
137 Some(ast::Pat::RecordPat(record)) => {
138 if let Some(field_list) = record.record_pat_field_list() {
139 for field in field_list.fields() {
140 recurse(map, ctx, &field.pat());
144 Some(ast::Pat::ParenPat(parentheses)) => {
145 recurse(map, ctx, &parentheses.pat());
147 Some(ast::Pat::SlicePat(slice)) => {
148 for slice_pat in slice.pats() {
149 recurse(map, ctx, &Some(slice_pat));
152 Some(ast::Pat::IdentPat(ident_pat)) => {
153 if let Some(name) = ident_pat.name() {
154 let pat_type = ctx.sema.type_of_pat(local_pat);
155 map.insert(name.text().to_string(), pat_type);
163 recurse(&mut mapping, context, &arm.pat());
169 use crate::tests::{check_assist, check_assist_not_applicable};
174 fn merge_match_arms_single_patterns() {
197 X::A | X::B => { 1i32 },
206 fn merge_match_arms_multiple_patterns() {
211 enum X { A, B, C, D, E }
216 X::A | X::B => {$0 1i32 },
217 X::C | X::D => { 1i32 },
224 enum X { A, B, C, D, E }
229 X::A | X::B | X::C | X::D => { 1i32 },
238 fn merge_match_arms_placeholder_pattern() {
243 enum X { A, B, C, D, E }
256 enum X { A, B, C, D, E }
270 fn merges_all_subsequent_arms() {
274 enum X { A, B, C, D, E }
287 enum X { A, B, C, D, E }
291 X::A | X::B | X::C => 92,
301 fn merge_match_arms_rejects_guards() {
302 check_assist_not_applicable(
315 X::A(a) if a > 5 => { $01i32 },
325 fn merge_match_arms_different_type() {
326 check_assist_not_applicable(
331 match Result::<f64, f32>::Ok(0f64) {
332 Ok(x) => $0x.classify(),
333 Err(x) => x.classify()
341 fn merge_match_arms_different_type_multiple_fields() {
342 check_assist_not_applicable(
347 match Result::<(f64, f64), (f32, f32)>::Ok((0f64, 0f64)) {
348 Ok(x) => $0x.1.classify(),
349 Err(x) => x.1.classify()
357 fn merge_match_arms_same_type_multiple_fields() {
363 match Result::<(f64, f64), (f64, f64)>::Ok((0f64, 0f64)) {
364 Ok(x) => $0x.1.classify(),
365 Err(x) => x.1.classify()
371 match Result::<(f64, f64), (f64, f64)>::Ok((0f64, 0f64)) {
372 Ok(x) | Err(x) => x.1.classify(),
380 fn merge_match_arms_same_type_subsequent_arm_with_different_type_in_other() {
392 MyEnum::OptionA(x) => $0x.classify(),
393 MyEnum::OptionB(x) => x.classify(),
394 MyEnum::OptionC(x) => x.classify(),
407 MyEnum::OptionA(x) | MyEnum::OptionB(x) => x.classify(),
408 MyEnum::OptionC(x) => x.classify(),
416 fn merge_match_arms_same_type_skip_arm_with_different_type_in_between() {
417 check_assist_not_applicable(
428 MyEnum::OptionA(x) => $0x.classify(),
429 MyEnum::OptionB(x) => x.classify(),
430 MyEnum::OptionC(x) => x.classify(),
438 fn merge_match_arms_same_type_different_number_of_fields() {
439 check_assist_not_applicable(
444 match Result::<(f64, f64, f64), (f64, f64)>::Ok((0f64, 0f64, 0f64)) {
445 Ok(x) => $0x.1.classify(),
446 Err(x) => x.1.classify()
454 fn merge_match_same_destructuring_different_types() {
455 check_assist_not_applicable(
464 let p = Point { x: 0, y: 7 };
467 Point { x, y: 0 } => $0"",
468 Point { x: 0, y } => "",
469 Point { x, y } => "",
477 fn merge_match_arms_range() {
496 'a'..='j' | 'c'..='z' => "",
505 fn merge_match_arms_enum_without_field() {
506 check_assist_not_applicable(
516 MyEnum::NoField => $0"",
517 MyEnum::AField(x) => ""
525 fn merge_match_arms_enum_destructuring_different_types() {
526 check_assist_not_applicable(
530 Move { x: i32, y: i32 },
536 MyEnum::Move { x, y } => $0"",
537 MyEnum::Write(text) => "",
545 fn merge_match_arms_enum_destructuring_same_types() {
550 Move { x: i32, y: i32 },
551 Crawl { x: i32, y: i32 }
556 MyEnum::Move { x, y } => $0"",
557 MyEnum::Crawl { x, y } => "",
563 Move { x: i32, y: i32 },
564 Crawl { x: i32, y: i32 }
569 MyEnum::Move { x, y } | MyEnum::Crawl { x, y } => "",
577 fn merge_match_arms_enum_destructuring_same_types_different_name() {
578 check_assist_not_applicable(
582 Move { x: i32, y: i32 },
583 Crawl { a: i32, b: i32 }
588 MyEnum::Move { x, y } => $0"",
589 MyEnum::Crawl { a, b } => "",
597 fn merge_match_arms_enum_nested_pattern_different_names() {
598 check_assist_not_applicable(
608 Move { x: i32, y: i32 },
613 fn main(msg: Message) {
615 Message::ChangeColor(Color::Rgb(r, g, b)) => $0"",
616 Message::ChangeColor(Color::Hsv(h, s, v)) => "",
625 fn merge_match_arms_enum_nested_pattern_same_names() {
636 Move { x: i32, y: i32 },
641 fn main(msg: Message) {
643 Message::ChangeColor(Color::Rgb(a, b, c)) => $0"",
644 Message::ChangeColor(Color::Hsv(a, b, c)) => "",
657 Move { x: i32, y: i32 },
662 fn main(msg: Message) {
664 Message::ChangeColor(Color::Rgb(a, b, c)) | Message::ChangeColor(Color::Hsv(a, b, c)) => "",
673 fn merge_match_arms_enum_destructuring_with_ignore() {
678 Move { x: i32, a: i32 },
679 Crawl { x: i32, b: i32 }
684 MyEnum::Move { x, .. } => $0"",
685 MyEnum::Crawl { x, .. } => "",
691 Move { x: i32, a: i32 },
692 Crawl { x: i32, b: i32 }
697 MyEnum::Move { x, .. } | MyEnum::Crawl { x, .. } => "",
705 fn merge_match_arms_nested_with_conflicting_identifier() {
706 check_assist_not_applicable(
715 Move { x: i32, y: i32 },
716 ChangeColor(u8, Color),
719 fn main(msg: Message) {
721 Message::ChangeColor(x, Color::Rgb(y, b, c)) => $0"",
722 Message::ChangeColor(y, Color::Hsv(x, b, c)) => "",
731 fn merge_match_arms_tuple() {
732 check_assist_not_applicable(
746 fn merge_match_arms_parentheses() {
747 check_assist_not_applicable(
754 ((((variable)))) => "",
763 fn merge_match_arms_refpat() {
764 check_assist_not_applicable(
768 let name = Some(String::from(""));
769 let n = String::from("");
781 fn merge_match_arms_slice() {
782 check_assist_not_applicable(
785 fn func(binary: &[u8]) {
788 [0x7f, b'E', b'L', b'F', ..] => $0"",
798 fn merge_match_arms_slice_identical() {
802 fn func(binary: &[u8]) {
805 [space, 5u8] => $0"",
812 fn func(binary: &[u8]) {
815 [space, 5u8] | [space] => "",