1 use std::iter::{self, Peekable};
4 use hir::{Adt, HasSource, ModuleDef, Semantics};
5 use ide_db::helpers::{mod_path_to_ast, FamousDefs};
6 use ide_db::RootDatabase;
7 use itertools::Itertools;
9 use syntax::ast::{self, make, AstNode, HasName, MatchArm, Pat};
12 utils::{self, render_snippet, Cursor},
13 AssistContext, AssistId, AssistKind, Assists,
16 // Assist: add_missing_match_arms
18 // Adds missing clauses to a `match` expression.
21 // enum Action { Move { distance: u32 }, Stop }
23 // fn handle(action: Action) {
30 // enum Action { Move { distance: u32 }, Stop }
32 // fn handle(action: Action) {
34 // $0Action::Move { distance } => todo!(),
35 // Action::Stop => todo!(),
39 pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
40 let match_expr = ctx.find_node_at_offset_with_descend::<ast::MatchExpr>()?;
41 let match_arm_list = match_expr.match_arm_list()?;
43 let available_range = TextRange::new(
44 ctx.sema.original_range(match_expr.syntax()).range.start(),
45 ctx.sema.original_range(match_arm_list.syntax()).range.start(),
48 let cursor_in_range = available_range.contains_range(ctx.frange.range);
53 let expr = match_expr.expr()?;
55 let mut arms: Vec<MatchArm> = match_arm_list.arms().collect();
56 if let [arm] = arms.as_slice() {
57 if let Some(Pat::WildcardPat(..)) = arm.pat() {
62 let top_lvl_pats: Vec<_> = arms
64 .filter_map(ast::MatchArm::pat)
65 .flat_map(|pat| match pat {
66 // Special case OrPat as separate top-level pats
67 Pat::OrPat(or_pat) => Either::Left(or_pat.pats()),
68 _ => Either::Right(iter::once(pat)),
70 // Exclude top level wildcards so that they are expanded by this assist, retains status quo in #8129.
71 .filter(|pat| !matches!(pat, Pat::WildcardPat(_)))
74 let module = ctx.sema.scope(expr.syntax()).module()?;
76 let mut missing_pats: Peekable<Box<dyn Iterator<Item = ast::Pat>>> = if let Some(enum_def) =
77 resolve_enum_def(&ctx.sema, &expr)
79 let variants = enum_def.variants(ctx.db());
81 let missing_pats = variants
83 .filter_map(|variant| build_pat(ctx.db(), module, variant))
84 .filter(|variant_pat| is_variant_missing(&top_lvl_pats, variant_pat));
87 FamousDefs(&ctx.sema, Some(module.krate())).core_option_Option().map(lift_enum);
88 let missing_pats: Box<dyn Iterator<Item = _>> = if Some(enum_def) == option_enum {
89 // Match `Some` variant first.
90 cov_mark::hit!(option_order);
91 Box::new(missing_pats.rev())
93 Box::new(missing_pats)
95 missing_pats.peekable()
96 } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) {
98 let variants_of_enums: Vec<Vec<ExtendedVariant>> = enum_defs
100 .map(|enum_def| enum_def.variants(ctx.db()))
101 .inspect(|variants| n_arms *= variants.len())
104 // When calculating the match arms for a tuple of enums, we want
105 // to create a match arm for each possible combination of enum
106 // values. The `multi_cartesian_product` method transforms
107 // Vec<Vec<EnumVariant>> into Vec<(EnumVariant, .., EnumVariant)>
108 // where each tuple represents a proposed match arm.
110 // A number of arms grows very fast on even a small tuple of large enums.
111 // We skip the assist beyond an arbitrary threshold.
115 let missing_pats = variants_of_enums
117 .multi_cartesian_product()
118 .inspect(|_| cov_mark::hit!(add_missing_match_arms_lazy_computation))
121 variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant));
122 ast::Pat::from(make::tuple_pat(patterns))
124 .filter(|variant_pat| is_variant_missing(&top_lvl_pats, variant_pat));
125 (Box::new(missing_pats) as Box<dyn Iterator<Item = _>>).peekable()
130 if missing_pats.peek().is_none() {
135 AssistId("add_missing_match_arms", AssistKind::QuickFix),
139 let new_match_arm_list = match_arm_list.clone_for_update();
140 let missing_arms = missing_pats
141 .map(|pat| make::match_arm(iter::once(pat), None, make::ext::expr_todo()))
142 .map(|it| it.clone_for_update());
144 let catch_all_arm = new_match_arm_list
146 .find(|arm| matches!(arm.pat(), Some(ast::Pat::WildcardPat(_))));
147 if let Some(arm) = catch_all_arm {
148 let is_empty_expr = arm.expr().map_or(true, |e| match e {
149 ast::Expr::BlockExpr(b) => {
150 b.statements().next().is_none() && b.tail_expr().is_none()
152 ast::Expr::TupleExpr(t) => t.fields().next().is_none(),
158 cov_mark::hit!(add_missing_match_arms_empty_expr);
161 let mut first_new_arm = None;
162 for arm in missing_arms {
163 first_new_arm.get_or_insert_with(|| arm.clone());
164 new_match_arm_list.add_arm(arm);
167 let old_range = ctx.sema.original_range(match_arm_list.syntax()).range;
168 match (first_new_arm, ctx.config.snippet_cap) {
169 (Some(first_new_arm), Some(cap)) => {
172 match first_new_arm.syntax().descendants().find_map(ast::WildcardPat::cast)
175 extend_lifetime = it.syntax().clone();
176 Cursor::Replace(&extend_lifetime)
178 None => Cursor::Before(first_new_arm.syntax()),
180 let snippet = render_snippet(cap, new_match_arm_list.syntax(), cursor);
181 builder.replace_snippet(cap, old_range, snippet);
183 _ => builder.replace(old_range, new_match_arm_list.to_string()),
189 fn is_variant_missing(existing_pats: &[Pat], var: &Pat) -> bool {
190 !existing_pats.iter().any(|pat| does_pat_match_variant(pat, var))
193 // Fixme: this is still somewhat limited, use hir_ty::diagnostics::match_check?
194 fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
196 (Pat::WildcardPat(_), _) => true,
197 (Pat::TuplePat(tpat), Pat::TuplePat(tvar)) => {
198 tpat.fields().zip(tvar.fields()).all(|(p, v)| does_pat_match_variant(&p, &v))
200 _ => utils::does_pat_match_variant(pat, var),
204 #[derive(Eq, PartialEq, Clone, Copy)]
210 #[derive(Eq, PartialEq, Clone, Copy)]
211 enum ExtendedVariant {
214 Variant(hir::Variant),
217 fn lift_enum(e: hir::Enum) -> ExtendedEnum {
218 ExtendedEnum::Enum(e)
222 fn variants(self, db: &RootDatabase) -> Vec<ExtendedVariant> {
224 ExtendedEnum::Enum(e) => {
225 e.variants(db).into_iter().map(ExtendedVariant::Variant).collect::<Vec<_>>()
227 ExtendedEnum::Bool => {
228 Vec::<ExtendedVariant>::from([ExtendedVariant::True, ExtendedVariant::False])
234 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<ExtendedEnum> {
235 sema.type_of_expr(expr)?.adjusted().autoderef(sema.db).find_map(|ty| match ty.as_adt() {
236 Some(Adt::Enum(e)) => Some(ExtendedEnum::Enum(e)),
237 _ => ty.is_bool().then(|| ExtendedEnum::Bool),
241 fn resolve_tuple_of_enum_def(
242 sema: &Semantics<RootDatabase>,
244 ) -> Option<Vec<ExtendedEnum>> {
245 sema.type_of_expr(expr)?
247 .tuple_fields(sema.db)
250 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
251 Some(Adt::Enum(e)) => Some(lift_enum(e)),
252 // For now we only handle expansion for a tuple of enums. Here
253 // we map non-enum items to None and rely on `collect` to
254 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
255 _ => ty.is_bool().then(|| ExtendedEnum::Bool),
261 fn build_pat(db: &RootDatabase, module: hir::Module, var: ExtendedVariant) -> Option<ast::Pat> {
263 ExtendedVariant::Variant(var) => {
264 let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?);
266 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
267 let pat: ast::Pat = match var.source(db)?.value.kind() {
268 ast::StructKind::Tuple(field_list) => {
270 iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count());
271 make::tuple_struct_pat(path, pats).into()
273 ast::StructKind::Record(field_list) => {
274 let pats = field_list
276 .map(|f| make::ext::simple_ident_pat(f.name().unwrap()).into());
277 make::record_pat(path, pats).into()
279 ast::StructKind::Unit => make::path_pat(path),
284 ExtendedVariant::True => Some(ast::Pat::from(make::literal_pat("true"))),
285 ExtendedVariant::False => Some(ast::Pat::from(make::literal_pat("false"))),
292 check_assist, check_assist_not_applicable, check_assist_target, check_assist_unresolved,
295 use super::add_missing_match_arms;
298 fn all_match_arms_provided() {
299 check_assist_not_applicable(
300 add_missing_match_arms,
304 Bs{x:i32, y:Option<i32>},
305 Cs(i32, Option<i32>),
310 A::Bs{x,y:Some(_)} => {}
311 A::Cs(_, Some(_)) => {}
319 fn not_applicable_outside_of_range_left() {
320 check_assist_not_applicable(
321 add_missing_match_arms,
338 fn not_applicable_outside_of_range_right() {
339 check_assist_not_applicable(
340 add_missing_match_arms,
357 fn all_boolean_match_arms_provided() {
358 check_assist_not_applicable(
359 add_missing_match_arms,
372 fn tuple_of_non_enum() {
373 // for now this case is not handled, although it potentially could be
375 check_assist_not_applicable(
376 add_missing_match_arms,
387 fn add_missing_match_arms_boolean() {
389 add_missing_match_arms,
408 fn partial_fill_boolean() {
410 add_missing_match_arms,
430 fn all_boolean_tuple_arms_provided() {
431 check_assist_not_applicable(
432 add_missing_match_arms,
447 fn fill_boolean_tuple() {
449 add_missing_match_arms,
459 $0(true, true) => todo!(),
460 (true, false) => todo!(),
461 (false, true) => todo!(),
462 (false, false) => todo!(),
470 fn partial_fill_boolean_tuple() {
472 add_missing_match_arms,
484 $0(true, true) => todo!(),
485 (true, false) => todo!(),
486 (false, false) => todo!(),
494 fn partial_fill_record_tuple() {
496 add_missing_match_arms,
500 Bs { x: i32, y: Option<i32> },
501 Cs(i32, Option<i32>),
505 A::Bs { x, y: Some(_) } => {}
506 A::Cs(_, Some(_)) => {}
513 Bs { x: i32, y: Option<i32> },
514 Cs(i32, Option<i32>),
518 A::Bs { x, y: Some(_) } => {}
519 A::Cs(_, Some(_)) => {}
528 fn partial_fill_option() {
530 add_missing_match_arms,
543 Some(${0:_}) => todo!(),
551 fn partial_fill_or_pat() {
553 add_missing_match_arms,
555 enum A { As, Bs, Cs(Option<i32>) }
558 A::Cs(_) | A::Bs => {}
563 enum A { As, Bs, Cs(Option<i32>) }
566 A::Cs(_) | A::Bs => {}
577 add_missing_match_arms,
579 enum A { As, Bs, Cs, Ds(String), Es(B) }
584 A::Ds(_value) => { let x = 1; }
590 enum A { As, Bs, Cs, Ds(String), Es(B) }
595 A::Ds(_value) => { let x = 1; }
606 fn partial_fill_bind_pat() {
608 add_missing_match_arms,
610 enum A { As, Bs, Cs(Option<i32>) }
619 enum A { As, Bs, Cs(Option<i32>) }
624 A::Cs(${0:_}) => todo!(),
632 fn add_missing_match_arms_empty_body() {
634 add_missing_match_arms,
636 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
644 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
652 A::Ds(_, _) => todo!(),
653 A::Es { x, y } => todo!(),
661 fn add_missing_match_arms_tuple_of_enum() {
663 add_missing_match_arms,
682 $0(A::One, B::One) => todo!(),
683 (A::One, B::Two) => todo!(),
684 (A::Two, B::One) => todo!(),
685 (A::Two, B::Two) => todo!(),
693 fn add_missing_match_arms_tuple_of_enum_ref() {
695 add_missing_match_arms,
714 $0(A::One, B::One) => todo!(),
715 (A::One, B::Two) => todo!(),
716 (A::Two, B::One) => todo!(),
717 (A::Two, B::Two) => todo!(),
725 fn add_missing_match_arms_tuple_of_enum_partial() {
727 add_missing_match_arms,
736 (A::Two, B::One) => {}
748 (A::Two, B::One) => {}
749 $0(A::One, B::One) => todo!(),
750 (A::One, B::Two) => todo!(),
751 (A::Two, B::Two) => todo!(),
759 fn add_missing_match_arms_tuple_of_enum_partial_with_wildcards() {
761 add_missing_match_arms,
769 (None, Some(_)) => {}
779 (None, Some(_)) => {}
780 $0(None, None) => todo!(),
788 fn add_missing_match_arms_partial_with_deep_pattern() {
789 // Fixme: cannot handle deep patterns
790 check_assist_not_applicable(
791 add_missing_match_arms,
805 fn add_missing_match_arms_tuple_of_enum_not_applicable() {
806 check_assist_not_applicable(
807 add_missing_match_arms,
816 (A::Two, B::One) => {}
817 (A::One, B::One) => {}
818 (A::One, B::Two) => {}
819 (A::Two, B::Two) => {}
827 fn add_missing_match_arms_single_element_tuple_of_enum() {
829 add_missing_match_arms,
845 $0(A::One,) => todo!(),
846 (A::Two,) => todo!(),
854 fn test_fill_match_arm_refs() {
856 add_missing_match_arms,
877 add_missing_match_arms,
880 Es { x: usize, y: usize }
890 Es { x: usize, y: usize }
895 $0A::Es { x, y } => todo!(),
903 fn add_missing_match_arms_target() {
905 add_missing_match_arms,
918 fn add_missing_match_arms_trivial_arm() {
920 add_missing_match_arms,
944 fn add_missing_match_arms_qualifies_path() {
946 add_missing_match_arms,
948 mod foo { pub enum E { X, Y } }
957 mod foo { pub enum E { X, Y } }
963 foo::E::Y => todo!(),
971 fn add_missing_match_arms_preserves_comments() {
973 add_missing_match_arms,
980 // This is where the rest should be
991 // This is where the rest should be
999 fn add_missing_match_arms_preserves_comments_empty() {
1001 add_missing_match_arms,
1014 $0A::One => todo!(),
1024 fn add_missing_match_arms_placeholder() {
1026 add_missing_match_arms,
1028 enum A { One, Two, }
1036 enum A { One, Two, }
1039 $0A::One => todo!(),
1049 cov_mark::check!(option_order);
1051 add_missing_match_arms,
1053 //- minicore: option
1054 fn foo(opt: Option<i32>) {
1060 fn foo(opt: Option<i32>) {
1062 Some(${0:_}) => todo!(),
1071 fn works_inside_macro_call() {
1073 add_missing_match_arms,
1075 macro_rules! m { ($expr:expr) => {$expr}}
1086 macro_rules! m { ($expr:expr) => {$expr}}
1095 $0Test::A => todo!(),
1104 fn lazy_computation() {
1105 // Computing a single missing arm is enough to determine applicability of the assist.
1106 cov_mark::check_count!(add_missing_match_arms_lazy_computation, 1);
1107 check_assist_unresolved(
1108 add_missing_match_arms,
1110 enum A { One, Two, }
1111 fn foo(tuple: (A, A)) {
1119 fn adds_comma_before_new_arms() {
1121 add_missing_match_arms,
1139 fn does_not_add_extra_comma() {
1141 add_missing_match_arms,
1159 fn does_not_remove_catch_all_with_non_empty_expr() {
1160 cov_mark::check!(add_missing_match_arms_empty_expr);
1162 add_missing_match_arms,