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 } => {}
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 missing_arms: Vec<MatchArm> = if let Some(enum_def) = resolve_enum_def(&ctx.sema, &expr) {
67 let variants = enum_def.variants(ctx.db());
69 let mut variants = variants
71 .filter_map(|variant| build_pat(ctx.db(), module, variant))
72 .filter(|variant_pat| is_variant_missing(&top_lvl_pats, variant_pat))
73 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
74 .map(|it| it.clone_for_update())
77 == FamousDefs(&ctx.sema, Some(module.krate()))
79 .map(|x| lift_enum(x))
81 // Match `Some` variant first.
82 cov_mark::hit!(option_order);
86 } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) {
87 // When calculating the match arms for a tuple of enums, we want
88 // to create a match arm for each possible combination of enum
89 // values. The `multi_cartesian_product` method transforms
90 // Vec<Vec<EnumVariant>> into Vec<(EnumVariant, .., EnumVariant)>
91 // where each tuple represents a proposed match arm.
94 .map(|enum_def| enum_def.variants(ctx.db()))
95 .multi_cartesian_product()
98 variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant));
99 ast::Pat::from(make::tuple_pat(patterns))
101 .filter(|variant_pat| is_variant_missing(&top_lvl_pats, variant_pat))
102 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
103 .map(|it| it.clone_for_update())
109 if missing_arms.is_empty() {
113 let target = ctx.sema.original_range(match_expr.syntax()).range;
115 AssistId("fill_match_arms", AssistKind::QuickFix),
119 let new_match_arm_list = match_arm_list.clone_for_update();
121 let catch_all_arm = new_match_arm_list
123 .find(|arm| matches!(arm.pat(), Some(ast::Pat::WildcardPat(_))));
124 if let Some(arm) = catch_all_arm {
127 let mut first_new_arm = None;
128 for arm in missing_arms {
129 first_new_arm.get_or_insert_with(|| arm.clone());
130 new_match_arm_list.add_arm(arm);
133 let old_range = ctx.sema.original_range(match_arm_list.syntax()).range;
134 match (first_new_arm, ctx.config.snippet_cap) {
135 (Some(first_new_arm), Some(cap)) => {
138 match first_new_arm.syntax().descendants().find_map(ast::WildcardPat::cast)
141 extend_lifetime = it.syntax().clone();
142 Cursor::Replace(&extend_lifetime)
144 None => Cursor::Before(first_new_arm.syntax()),
146 let snippet = render_snippet(cap, new_match_arm_list.syntax(), cursor);
147 builder.replace_snippet(cap, old_range, snippet);
149 _ => builder.replace(old_range, new_match_arm_list.to_string()),
155 fn is_variant_missing(existing_pats: &[Pat], var: &Pat) -> bool {
156 !existing_pats.iter().any(|pat| does_pat_match_variant(pat, var))
159 // Fixme: this is still somewhat limited, use hir_ty::diagnostics::match_check?
160 fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
162 (Pat::WildcardPat(_), _) => true,
163 (Pat::TuplePat(tpat), Pat::TuplePat(tvar)) => {
164 tpat.fields().zip(tvar.fields()).all(|(p, v)| does_pat_match_variant(&p, &v))
166 _ => utils::does_pat_match_variant(pat, var),
170 #[derive(Eq, PartialEq, Clone)]
176 #[derive(Eq, PartialEq, Clone)]
177 enum ExtendedVariant {
180 Variant(hir::Variant),
183 fn lift_enum(e: hir::Enum) -> ExtendedEnum {
184 ExtendedEnum::Enum(e)
188 fn variants(&self, db: &RootDatabase) -> Vec<ExtendedVariant> {
190 ExtendedEnum::Enum(e) => {
191 e.variants(db).into_iter().map(|x| ExtendedVariant::Variant(x)).collect::<Vec<_>>()
193 ExtendedEnum::Bool => {
194 Vec::<ExtendedVariant>::from([ExtendedVariant::True, ExtendedVariant::False])
200 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<ExtendedEnum> {
201 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
202 Some(Adt::Enum(e)) => Some(ExtendedEnum::Enum(e)),
205 Some(ExtendedEnum::Bool)
213 fn resolve_tuple_of_enum_def(
214 sema: &Semantics<RootDatabase>,
216 ) -> Option<Vec<ExtendedEnum>> {
217 sema.type_of_expr(&expr)?
218 .tuple_fields(sema.db)
221 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
222 Some(Adt::Enum(e)) => Some(lift_enum(e)),
223 // For now we only handle expansion for a tuple of enums. Here
224 // we map non-enum items to None and rely on `collect` to
225 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
228 Some(ExtendedEnum::Bool)
238 fn build_pat(db: &RootDatabase, module: hir::Module, var: ExtendedVariant) -> Option<ast::Pat> {
240 ExtendedVariant::Variant(var) => {
241 let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?);
243 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
244 let pat: ast::Pat = match var.source(db)?.value.kind() {
245 ast::StructKind::Tuple(field_list) => {
247 iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count());
248 make::tuple_struct_pat(path, pats).into()
250 ast::StructKind::Record(field_list) => {
252 field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into());
253 make::record_pat(path, pats).into()
255 ast::StructKind::Unit => make::path_pat(path),
260 ExtendedVariant::True => Some(ast::Pat::from(make::literal_pat("true"))),
261 ExtendedVariant::False => Some(ast::Pat::from(make::literal_pat("false"))),
267 use ide_db::helpers::FamousDefs;
269 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
271 use super::fill_match_arms;
274 fn all_match_arms_provided() {
275 check_assist_not_applicable(
280 Bs{x:i32, y:Option<i32>},
281 Cs(i32, Option<i32>),
286 A::Bs{x,y:Some(_)} => {}
287 A::Cs(_, Some(_)) => {}
295 fn all_boolean_match_arms_provided() {
296 check_assist_not_applicable(
310 fn tuple_of_non_enum() {
311 // for now this case is not handled, although it potentially could be
313 check_assist_not_applicable(
325 fn fill_match_arms_boolean() {
346 fn partial_fill_boolean() {
368 fn all_boolean_tuple_arms_provided() {
369 check_assist_not_applicable(
385 fn fill_boolean_tuple() {
408 fn partial_fill_boolean_tuple() {
432 fn partial_fill_record_tuple() {
438 Bs { x: i32, y: Option<i32> },
439 Cs(i32, Option<i32>),
443 A::Bs { x, y: Some(_) } => {}
444 A::Cs(_, Some(_)) => {}
451 Bs { x: i32, y: Option<i32> },
452 Cs(i32, Option<i32>),
456 A::Bs { x, y: Some(_) } => {}
457 A::Cs(_, Some(_)) => {}
466 fn partial_fill_option() {
470 enum Option<T> { Some(T), None }
480 enum Option<T> { Some(T), None }
494 fn partial_fill_or_pat() {
498 enum A { As, Bs, Cs(Option<i32>) }
501 A::Cs(_) | A::Bs => {}
506 enum A { As, Bs, Cs(Option<i32>) }
509 A::Cs(_) | A::Bs => {}
522 enum A { As, Bs, Cs, Ds(String), Es(B) }
527 A::Ds(_value) => { let x = 1; }
533 enum A { As, Bs, Cs, Ds(String), Es(B) }
538 A::Ds(_value) => { let x = 1; }
549 fn partial_fill_bind_pat() {
553 enum A { As, Bs, Cs(Option<i32>) }
562 enum A { As, Bs, Cs(Option<i32>) }
575 fn fill_match_arms_empty_body() {
579 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
587 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
604 fn fill_match_arms_tuple_of_enum() {
625 $0(A::One, B::One) => {}
626 (A::One, B::Two) => {}
627 (A::Two, B::One) => {}
628 (A::Two, B::Two) => {}
636 fn fill_match_arms_tuple_of_enum_ref() {
657 $0(A::One, B::One) => {}
658 (A::One, B::Two) => {}
659 (A::Two, B::One) => {}
660 (A::Two, B::Two) => {}
668 fn fill_match_arms_tuple_of_enum_partial() {
679 (A::Two, B::One) => {}
691 (A::Two, B::One) => {}
692 $0(A::One, B::One) => {}
693 (A::One, B::Two) => {}
694 (A::Two, B::Two) => {}
702 fn fill_match_arms_tuple_of_enum_partial_with_wildcards() {
709 (None, Some(_)) => {}
715 &format!("//- /main.rs crate:main deps:core{}{}", ra_fixture, FamousDefs::FIXTURE),
722 (None, Some(_)) => {}
731 fn fill_match_arms_partial_with_deep_pattern() {
732 // Fixme: cannot handle deep patterns
741 check_assist_not_applicable(
743 &format!("//- /main.rs crate:main deps:core{}{}", ra_fixture, FamousDefs::FIXTURE),
748 fn fill_match_arms_tuple_of_enum_not_applicable() {
749 check_assist_not_applicable(
759 (A::Two, B::One) => {}
760 (A::One, B::One) => {}
761 (A::One, B::Two) => {}
762 (A::Two, B::Two) => {}
770 fn fill_match_arms_single_element_tuple_of_enum() {
797 fn test_fill_match_arm_refs() {
823 Es { x: usize, y: usize }
833 Es { x: usize, y: usize }
838 $0A::Es { x, y } => {}
846 fn fill_match_arms_target() {
861 fn fill_match_arms_trivial_arm() {
887 fn fill_match_arms_qualifies_path() {
891 mod foo { pub enum E { X, Y } }
901 mod foo { pub enum E { X, Y } }
915 fn fill_match_arms_preserves_comments() {
924 // This is where the rest should be
935 // This is where the rest should be
943 fn fill_match_arms_preserves_comments_empty() {
968 fn fill_match_arms_placeholder() {
993 cov_mark::check!(option_order);
995 fn foo(opt: Option<i32>) {
1000 let before = &format!("//- /main.rs crate:main deps:core{}{}", before, FamousDefs::FIXTURE);
1006 fn foo(opt: Option<i32>) {
1017 fn works_inside_macro_call() {
1021 macro_rules! m { ($expr:expr) => {$expr}}
1032 macro_rules! m { ($expr:expr) => {$expr}}