2 use std::{iter::successors, collections::HashMap};
5 ast::{self, AstNode, Pat, MatchArm, 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 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_entry in arm_types {
104 let current_arm_type = current_arm_types.get_key_value(&other_arm_type_entry.0);
105 if current_arm_type.is_none() {
109 let unwrapped_current_arm_type = current_arm_type.unwrap().1;
111 if let (Some(other_arm_type), Some(current_arm_type)) = (other_arm_type_entry.1, unwrapped_current_arm_type) {
112 if other_arm_type.original != current_arm_type.original {
121 fn get_arm_types(context: &AssistContext, arm: &MatchArm) -> HashMap<String, Option<TypeInfo>> {
122 let mut mapping: HashMap<String, Option<TypeInfo>> = HashMap::new();
124 fn recurse(pat: &Option<Pat>, map: &mut HashMap<String, Option<TypeInfo>>, ctx: &AssistContext) {
125 if let Some(local_pat) = pat {
127 Some(ast::Pat::TupleStructPat(tuple)) => {
128 for field in tuple.fields() {
129 recurse(&Some(field), map, ctx);
132 Some(ast::Pat::RecordPat(record)) => {
133 if let Some(field_list) = record.record_pat_field_list() {
134 for field in field_list.fields() {
135 recurse(&field.pat(), map, ctx);
139 Some(ast::Pat::IdentPat(ident_pat)) => {
140 if let Some(name) = ident_pat.name() {
141 let pat_type = ctx.sema.type_of_pat(local_pat);
142 map.insert(name.text().to_string(), pat_type);
150 recurse(&arm.pat(), &mut mapping, &context);
156 use crate::tests::{check_assist, check_assist_not_applicable};
161 fn merge_match_arms_single_patterns() {
184 X::A | X::B => { 1i32 },
193 fn merge_match_arms_multiple_patterns() {
198 enum X { A, B, C, D, E }
203 X::A | X::B => {$0 1i32 },
204 X::C | X::D => { 1i32 },
211 enum X { A, B, C, D, E }
216 X::A | X::B | X::C | X::D => { 1i32 },
225 fn merge_match_arms_placeholder_pattern() {
230 enum X { A, B, C, D, E }
243 enum X { A, B, C, D, E }
257 fn merges_all_subsequent_arms() {
261 enum X { A, B, C, D, E }
274 enum X { A, B, C, D, E }
278 X::A | X::B | X::C => 92,
288 fn merge_match_arms_rejects_guards() {
289 check_assist_not_applicable(
302 X::A(a) if a > 5 => { $01i32 },
312 fn merge_match_arms_different_type() {
313 check_assist_not_applicable(
315 r#"//- minicore: result
317 match Result::<f64, f32>::Ok(0f64) {
318 Ok(x) => $0x.classify(),
319 Err(x) => x.classify()
327 fn merge_match_arms_different_type_multiple_fields() {
328 check_assist_not_applicable(
330 r#"//- minicore: result
332 match Result::<(f64, f64), (f32, f32)>::Ok((0f64, 0f64)) {
333 Ok(x) => $0x.1.classify(),
334 Err(x) => x.1.classify()
342 fn merge_match_arms_same_type_multiple_fields() {
345 r#"//- minicore: result
347 match Result::<(f64, f64), (f64, f64)>::Ok((0f64, 0f64)) {
348 Ok(x) => $0x.1.classify(),
349 Err(x) => x.1.classify()
355 match Result::<(f64, f64), (f64, f64)>::Ok((0f64, 0f64)) {
356 Ok(x) | Err(x) => x.1.classify(),
364 fn merge_match_arms_same_type_subsequent_arm_with_different_type_in_other() {
376 MyEnum::OptionA(x) => $0x.classify(),
377 MyEnum::OptionB(x) => x.classify(),
378 MyEnum::OptionC(x) => x.classify(),
391 MyEnum::OptionA(x) | MyEnum::OptionB(x) => x.classify(),
392 MyEnum::OptionC(x) => x.classify(),
400 fn merge_match_arms_same_type_skip_arm_with_different_type_in_between() {
401 check_assist_not_applicable(
412 MyEnum::OptionA(x) => $0x.classify(),
413 MyEnum::OptionB(x) => x.classify(),
414 MyEnum::OptionC(x) => x.classify(),
422 fn merge_match_arms_same_type_different_number_of_fields() {
423 check_assist_not_applicable(
425 r#"//- minicore: result
427 match Result::<(f64, f64, f64), (f64, f64)>::Ok((0f64, 0f64, 0f64)) {
428 Ok(x) => $0x.1.classify(),
429 Err(x) => x.1.classify()
437 fn merge_match_same_destructuring_different_types() {
438 check_assist_not_applicable(
447 let p = Point { x: 0, y: 7 };
450 Point { x, y: 0 } => $0"",
451 Point { x: 0, y } => "",
452 Point { x, y } => "",
460 fn merge_match_arms_range() {
479 'a'..='j' | 'c'..='z' => "",
488 fn merge_match_arms_enum_without_field() {
489 check_assist_not_applicable(
499 MyEnum::NoField => $0"",
500 MyEnum::AField(x) => ""
508 fn merge_match_arms_enum_destructuring_different_types() {
509 check_assist_not_applicable(
513 Move { x: i32, y: i32 },
519 MyEnum::Move { x, y } => $0"",
520 MyEnum::Write(text) => "",
528 fn merge_match_arms_enum_destructuring_same_types() {
533 Move { x: i32, y: i32 },
534 Crawl { x: i32, y: i32 }
539 MyEnum::Move { x, y } => $0"",
540 MyEnum::Crawl { x, y } => "",
546 Move { x: i32, y: i32 },
547 Crawl { x: i32, y: i32 }
552 MyEnum::Move { x, y } | MyEnum::Crawl { x, y } => "",
560 fn merge_match_arms_enum_destructuring_same_types_different_name() {
561 check_assist_not_applicable(
565 Move { x: i32, y: i32 },
566 Crawl { a: i32, b: i32 }
571 MyEnum::Move { x, y } => $0"",
572 MyEnum::Crawl { a, b } => "",
580 fn merge_match_arms_enum_nested_pattern_different_names() {
581 check_assist_not_applicable(
591 Move { x: i32, y: i32 },
596 fn main(msg: Message) {
598 Message::ChangeColor(Color::Rgb(r, g, b)) => $0"",
599 Message::ChangeColor(Color::Hsv(h, s, v)) => "",
608 fn merge_match_arms_enum_nested_pattern_same_names() {
619 Move { x: i32, y: i32 },
624 fn main(msg: Message) {
626 Message::ChangeColor(Color::Rgb(a, b, c)) => $0"",
627 Message::ChangeColor(Color::Hsv(a, b, c)) => "",
640 Move { x: i32, y: i32 },
645 fn main(msg: Message) {
647 Message::ChangeColor(Color::Rgb(a, b, c)) | Message::ChangeColor(Color::Hsv(a, b, c)) => "",
656 fn merge_match_arms_enum_destructuring_with_ignore() {
661 Move { x: i32, a: i32 },
662 Crawl { x: i32, b: i32 }
667 MyEnum::Move { x, .. } => $0"",
668 MyEnum::Crawl { x, .. } => "",
674 Move { x: i32, a: i32 },
675 Crawl { x: i32, b: i32 }
680 MyEnum::Move { x, .. } | MyEnum::Crawl { x, .. } => "",
688 fn merge_match_arms_nested_with_conflicting_identifier() {
689 check_assist_not_applicable(
698 Move { x: i32, y: i32 },
699 ChangeColor(u8, Color),
702 fn main(msg: Message) {
704 Message::ChangeColor(x, Color::Rgb(y, b, c)) => $0"",
705 Message::ChangeColor(y, Color::Hsv(x, b, c)) => "",