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;
8 use syntax::ast::{self, make, AstNode, MatchArm, NameOwner, Pat};
11 utils::{self, render_snippet, Cursor},
12 AssistContext, AssistId, AssistKind, Assists,
15 // Assist: fill_match_arms
17 // Adds missing clauses to a `match` expression.
20 // enum Action { Move { distance: u32 }, Stop }
22 // 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 fill_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 expr = match_expr.expr()?;
45 let mut arms: Vec<MatchArm> = match_arm_list.arms().collect();
47 if let Some(Pat::WildcardPat(..)) = arms[0].pat() {
52 let top_lvl_pats: Vec<_> = arms
54 .filter_map(ast::MatchArm::pat)
55 .flat_map(|pat| match pat {
56 // Special case OrPat as separate top-level pats
57 Pat::OrPat(or_pat) => Either::Left(or_pat.pats()),
58 _ => Either::Right(iter::once(pat)),
60 // Exclude top level wildcards so that they are expanded by this assist, retains status quo in #8129.
61 .filter(|pat| !matches!(pat, Pat::WildcardPat(_)))
64 let module = ctx.sema.scope(expr.syntax()).module()?;
66 let mut missing_pats: Peekable<Box<dyn Iterator<Item = ast::Pat>>> = if let Some(enum_def) =
67 resolve_enum_def(&ctx.sema, &expr)
69 let variants = enum_def.variants(ctx.db());
71 let missing_pats = variants
73 .filter_map(|variant| build_pat(ctx.db(), module, variant))
74 .filter(|variant_pat| is_variant_missing(&top_lvl_pats, variant_pat));
76 let missing_pats: Box<dyn Iterator<Item = _>> = if Some(enum_def)
77 == FamousDefs(&ctx.sema, Some(module.krate())).core_option_Option().map(lift_enum)
79 // Match `Some` variant first.
80 cov_mark::hit!(option_order);
81 Box::new(missing_pats.rev())
83 Box::new(missing_pats)
85 missing_pats.peekable()
86 } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) {
88 let variants_of_enums: Vec<Vec<ExtendedVariant>> = enum_defs
90 .map(|enum_def| enum_def.variants(ctx.db()))
91 .inspect(|variants| n_arms *= variants.len())
94 // When calculating the match arms for a tuple of enums, we want
95 // to create a match arm for each possible combination of enum
96 // values. The `multi_cartesian_product` method transforms
97 // Vec<Vec<EnumVariant>> into Vec<(EnumVariant, .., EnumVariant)>
98 // where each tuple represents a proposed match arm.
100 // A number of arms grows very fast on even a small tuple of large enums.
101 // We skip the assist beyond an arbitrary threshold.
105 let missing_pats = variants_of_enums
107 .multi_cartesian_product()
108 .inspect(|_| cov_mark::hit!(fill_match_arms_lazy_computation))
111 variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant));
112 ast::Pat::from(make::tuple_pat(patterns))
114 .filter(|variant_pat| is_variant_missing(&top_lvl_pats, variant_pat));
115 (Box::new(missing_pats) as Box<dyn Iterator<Item = _>>).peekable()
120 if missing_pats.peek().is_none() {
124 let target = ctx.sema.original_range(match_expr.syntax()).range;
126 AssistId("fill_match_arms", AssistKind::QuickFix),
130 let new_match_arm_list = match_arm_list.clone_for_update();
131 let missing_arms = missing_pats
132 .map(|pat| make::match_arm(iter::once(pat), make::ext::expr_todo()))
133 .map(|it| it.clone_for_update());
135 let catch_all_arm = new_match_arm_list
137 .find(|arm| matches!(arm.pat(), Some(ast::Pat::WildcardPat(_))));
138 if let Some(arm) = catch_all_arm {
141 let mut first_new_arm = None;
142 for arm in missing_arms {
143 first_new_arm.get_or_insert_with(|| arm.clone());
144 new_match_arm_list.add_arm(arm);
147 let old_range = ctx.sema.original_range(match_arm_list.syntax()).range;
148 match (first_new_arm, ctx.config.snippet_cap) {
149 (Some(first_new_arm), Some(cap)) => {
152 match first_new_arm.syntax().descendants().find_map(ast::WildcardPat::cast)
155 extend_lifetime = it.syntax().clone();
156 Cursor::Replace(&extend_lifetime)
158 None => Cursor::Before(first_new_arm.syntax()),
160 let snippet = render_snippet(cap, new_match_arm_list.syntax(), cursor);
161 builder.replace_snippet(cap, old_range, snippet);
163 _ => builder.replace(old_range, new_match_arm_list.to_string()),
169 fn is_variant_missing(existing_pats: &[Pat], var: &Pat) -> bool {
170 !existing_pats.iter().any(|pat| does_pat_match_variant(pat, var))
173 // Fixme: this is still somewhat limited, use hir_ty::diagnostics::match_check?
174 fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
176 (Pat::WildcardPat(_), _) => true,
177 (Pat::TuplePat(tpat), Pat::TuplePat(tvar)) => {
178 tpat.fields().zip(tvar.fields()).all(|(p, v)| does_pat_match_variant(&p, &v))
180 _ => utils::does_pat_match_variant(pat, var),
184 #[derive(Eq, PartialEq, Clone, Copy)]
190 #[derive(Eq, PartialEq, Clone, Copy)]
191 enum ExtendedVariant {
194 Variant(hir::Variant),
197 fn lift_enum(e: hir::Enum) -> ExtendedEnum {
198 ExtendedEnum::Enum(e)
202 fn variants(self, db: &RootDatabase) -> Vec<ExtendedVariant> {
204 ExtendedEnum::Enum(e) => {
205 e.variants(db).into_iter().map(|x| ExtendedVariant::Variant(x)).collect::<Vec<_>>()
207 ExtendedEnum::Bool => {
208 Vec::<ExtendedVariant>::from([ExtendedVariant::True, ExtendedVariant::False])
214 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<ExtendedEnum> {
215 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
216 Some(Adt::Enum(e)) => Some(ExtendedEnum::Enum(e)),
219 Some(ExtendedEnum::Bool)
227 fn resolve_tuple_of_enum_def(
228 sema: &Semantics<RootDatabase>,
230 ) -> Option<Vec<ExtendedEnum>> {
231 sema.type_of_expr(&expr)?
232 .tuple_fields(sema.db)
235 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
236 Some(Adt::Enum(e)) => Some(lift_enum(e)),
237 // For now we only handle expansion for a tuple of enums. Here
238 // we map non-enum items to None and rely on `collect` to
239 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
242 Some(ExtendedEnum::Bool)
252 fn build_pat(db: &RootDatabase, module: hir::Module, var: ExtendedVariant) -> Option<ast::Pat> {
254 ExtendedVariant::Variant(var) => {
255 let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?);
257 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
258 let pat: ast::Pat = match var.source(db)?.value.kind() {
259 ast::StructKind::Tuple(field_list) => {
261 iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count());
262 make::tuple_struct_pat(path, pats).into()
264 ast::StructKind::Record(field_list) => {
266 field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into());
267 make::record_pat(path, pats).into()
269 ast::StructKind::Unit => make::path_pat(path),
274 ExtendedVariant::True => Some(ast::Pat::from(make::literal_pat("true"))),
275 ExtendedVariant::False => Some(ast::Pat::from(make::literal_pat("false"))),
281 use ide_db::helpers::FamousDefs;
284 check_assist, check_assist_not_applicable, check_assist_target, check_assist_unresolved,
287 use super::fill_match_arms;
290 fn all_match_arms_provided() {
291 check_assist_not_applicable(
296 Bs{x:i32, y:Option<i32>},
297 Cs(i32, Option<i32>),
302 A::Bs{x,y:Some(_)} => {}
303 A::Cs(_, Some(_)) => {}
311 fn all_boolean_match_arms_provided() {
312 check_assist_not_applicable(
326 fn tuple_of_non_enum() {
327 // for now this case is not handled, although it potentially could be
329 check_assist_not_applicable(
341 fn fill_match_arms_boolean() {
362 fn partial_fill_boolean() {
384 fn all_boolean_tuple_arms_provided() {
385 check_assist_not_applicable(
401 fn fill_boolean_tuple() {
413 $0(true, true) => todo!(),
414 (true, false) => todo!(),
415 (false, true) => todo!(),
416 (false, false) => todo!(),
424 fn partial_fill_boolean_tuple() {
438 $0(true, true) => todo!(),
439 (true, false) => todo!(),
440 (false, false) => todo!(),
448 fn partial_fill_record_tuple() {
454 Bs { x: i32, y: Option<i32> },
455 Cs(i32, Option<i32>),
459 A::Bs { x, y: Some(_) } => {}
460 A::Cs(_, Some(_)) => {}
467 Bs { x: i32, y: Option<i32> },
468 Cs(i32, Option<i32>),
472 A::Bs { x, y: Some(_) } => {}
473 A::Cs(_, Some(_)) => {}
482 fn partial_fill_option() {
486 enum Option<T> { Some(T), None }
496 enum Option<T> { Some(T), None }
502 Some(${0:_}) => todo!(),
510 fn partial_fill_or_pat() {
514 enum A { As, Bs, Cs(Option<i32>) }
517 A::Cs(_) | A::Bs => {}
522 enum A { As, Bs, Cs(Option<i32>) }
525 A::Cs(_) | A::Bs => {}
538 enum A { As, Bs, Cs, Ds(String), Es(B) }
543 A::Ds(_value) => { let x = 1; }
549 enum A { As, Bs, Cs, Ds(String), Es(B) }
554 A::Ds(_value) => { let x = 1; }
565 fn partial_fill_bind_pat() {
569 enum A { As, Bs, Cs(Option<i32>) }
578 enum A { As, Bs, Cs(Option<i32>) }
583 A::Cs(${0:_}) => todo!(),
591 fn fill_match_arms_empty_body() {
595 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
603 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
611 A::Ds(_, _) => todo!(),
612 A::Es { x, y } => todo!(),
620 fn fill_match_arms_tuple_of_enum() {
641 $0(A::One, B::One) => todo!(),
642 (A::One, B::Two) => todo!(),
643 (A::Two, B::One) => todo!(),
644 (A::Two, B::Two) => todo!(),
652 fn fill_match_arms_tuple_of_enum_ref() {
673 $0(A::One, B::One) => todo!(),
674 (A::One, B::Two) => todo!(),
675 (A::Two, B::One) => todo!(),
676 (A::Two, B::Two) => todo!(),
684 fn fill_match_arms_tuple_of_enum_partial() {
695 (A::Two, B::One) => {}
707 (A::Two, B::One) => {}
708 $0(A::One, B::One) => todo!(),
709 (A::One, B::Two) => todo!(),
710 (A::Two, B::Two) => todo!(),
718 fn fill_match_arms_tuple_of_enum_partial_with_wildcards() {
725 (None, Some(_)) => {}
731 &format!("//- /main.rs crate:main deps:core{}{}", ra_fixture, FamousDefs::FIXTURE),
738 (None, Some(_)) => {}
739 $0(None, None) => todo!(),
747 fn fill_match_arms_partial_with_deep_pattern() {
748 // Fixme: cannot handle deep patterns
757 check_assist_not_applicable(
759 &format!("//- /main.rs crate:main deps:core{}{}", ra_fixture, FamousDefs::FIXTURE),
764 fn fill_match_arms_tuple_of_enum_not_applicable() {
765 check_assist_not_applicable(
775 (A::Two, B::One) => {}
776 (A::One, B::One) => {}
777 (A::One, B::Two) => {}
778 (A::Two, B::Two) => {}
786 fn fill_match_arms_single_element_tuple_of_enum() {
804 $0(A::One,) => todo!(),
805 (A::Two,) => todo!(),
813 fn test_fill_match_arm_refs() {
839 Es { x: usize, y: usize }
849 Es { x: usize, y: usize }
854 $0A::Es { x, y } => todo!(),
862 fn fill_match_arms_target() {
877 fn fill_match_arms_trivial_arm() {
903 fn fill_match_arms_qualifies_path() {
907 mod foo { pub enum E { X, Y } }
917 mod foo { pub enum E { X, Y } }
923 foo::E::Y => todo!(),
931 fn fill_match_arms_preserves_comments() {
940 // This is where the rest should be
951 // This is where the rest should be
959 fn fill_match_arms_preserves_comments_empty() {
984 fn fill_match_arms_placeholder() {
1009 cov_mark::check!(option_order);
1011 fn foo(opt: Option<i32>) {
1016 let before = &format!("//- /main.rs crate:main deps:core{}{}", before, FamousDefs::FIXTURE);
1022 fn foo(opt: Option<i32>) {
1024 Some(${0:_}) => todo!(),
1033 fn works_inside_macro_call() {
1037 macro_rules! m { ($expr:expr) => {$expr}}
1048 macro_rules! m { ($expr:expr) => {$expr}}
1057 $0Test::A => todo!(),
1066 fn lazy_computation() {
1067 // Computing a single missing arm is enough to determine applicability of the assist.
1068 cov_mark::check_count!(fill_match_arms_lazy_computation, 1);
1069 check_assist_unresolved(
1072 enum A { One, Two, }
1073 fn foo(tuple: (A, A)) {
1081 fn adds_comma_before_new_arms() {
1101 fn does_not_add_extra_comma() {