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()))
76 == FamousDefs(&ctx.sema, Some(module.krate()))
78 .map(|x| lift_enum(x))
80 // Match `Some` variant first.
81 cov_mark::hit!(option_order);
85 } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) {
86 // When calculating the match arms for a tuple of enums, we want
87 // to create a match arm for each possible combination of enum
88 // values. The `multi_cartesian_product` method transforms
89 // Vec<Vec<EnumVariant>> into Vec<(EnumVariant, .., EnumVariant)>
90 // where each tuple represents a proposed match arm.
93 .map(|enum_def| enum_def.variants(ctx.db()))
94 .multi_cartesian_product()
97 variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant));
98 ast::Pat::from(make::tuple_pat(patterns))
100 .filter(|variant_pat| is_variant_missing(&top_lvl_pats, variant_pat))
101 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
107 if missing_arms.is_empty() {
111 let target = ctx.sema.original_range(match_expr.syntax()).range;
113 AssistId("fill_match_arms", AssistKind::QuickFix),
117 let new_arm_list = match_arm_list.remove_placeholder();
118 let n_old_arms = new_arm_list.arms().count();
119 let new_arm_list = new_arm_list.append_arms(missing_arms);
120 let first_new_arm = new_arm_list.arms().nth(n_old_arms);
121 let old_range = ctx.sema.original_range(match_arm_list.syntax()).range;
122 match (first_new_arm, ctx.config.snippet_cap) {
123 (Some(first_new_arm), Some(cap)) => {
126 match first_new_arm.syntax().descendants().find_map(ast::WildcardPat::cast)
129 extend_lifetime = it.syntax().clone();
130 Cursor::Replace(&extend_lifetime)
132 None => Cursor::Before(first_new_arm.syntax()),
134 let snippet = render_snippet(cap, new_arm_list.syntax(), cursor);
135 builder.replace_snippet(cap, old_range, snippet);
137 _ => builder.replace(old_range, new_arm_list.to_string()),
143 fn is_variant_missing(existing_pats: &[Pat], var: &Pat) -> bool {
144 !existing_pats.iter().any(|pat| does_pat_match_variant(pat, var))
147 // Fixme: this is still somewhat limited, use hir_ty::diagnostics::match_check?
148 fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
150 (Pat::WildcardPat(_), _) => true,
151 (Pat::TuplePat(tpat), Pat::TuplePat(tvar)) => {
152 tpat.fields().zip(tvar.fields()).all(|(p, v)| does_pat_match_variant(&p, &v))
154 _ => utils::does_pat_match_variant(pat, var),
158 #[derive(Eq, PartialEq, Clone)]
164 #[derive(Eq, PartialEq, Clone)]
165 enum ExtendedVariant {
168 Variant(hir::Variant),
171 fn lift_enum(e: hir::Enum) -> ExtendedEnum {
172 ExtendedEnum::Enum(e)
176 fn variants(&self, db: &RootDatabase) -> Vec<ExtendedVariant> {
178 ExtendedEnum::Enum(e) => {
179 e.variants(db).into_iter().map(|x| ExtendedVariant::Variant(x)).collect::<Vec<_>>()
181 ExtendedEnum::Bool => {
182 Vec::<ExtendedVariant>::from([ExtendedVariant::True, ExtendedVariant::False])
188 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<ExtendedEnum> {
189 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
190 Some(Adt::Enum(e)) => Some(ExtendedEnum::Enum(e)),
193 Some(ExtendedEnum::Bool)
201 fn resolve_tuple_of_enum_def(
202 sema: &Semantics<RootDatabase>,
204 ) -> Option<Vec<ExtendedEnum>> {
205 sema.type_of_expr(&expr)?
206 .tuple_fields(sema.db)
209 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
210 Some(Adt::Enum(e)) => Some(lift_enum(e)),
211 // For now we only handle expansion for a tuple of enums. Here
212 // we map non-enum items to None and rely on `collect` to
213 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
216 Some(ExtendedEnum::Bool)
226 fn build_pat(db: &RootDatabase, module: hir::Module, var: ExtendedVariant) -> Option<ast::Pat> {
228 ExtendedVariant::Variant(var) => {
229 let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?);
231 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
232 let pat: ast::Pat = match var.source(db)?.value.kind() {
233 ast::StructKind::Tuple(field_list) => {
235 iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count());
236 make::tuple_struct_pat(path, pats).into()
238 ast::StructKind::Record(field_list) => {
240 field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into());
241 make::record_pat(path, pats).into()
243 ast::StructKind::Unit => make::path_pat(path),
248 ExtendedVariant::True => Some(ast::Pat::from(make::literal_pat("true"))),
249 ExtendedVariant::False => Some(ast::Pat::from(make::literal_pat("false"))),
255 use ide_db::helpers::FamousDefs;
257 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
259 use super::fill_match_arms;
262 fn all_match_arms_provided() {
263 check_assist_not_applicable(
268 Bs{x:i32, y:Option<i32>},
269 Cs(i32, Option<i32>),
274 A::Bs{x,y:Some(_)} => {}
275 A::Cs(_, Some(_)) => {}
283 fn all_boolean_match_arms_provided() {
284 check_assist_not_applicable(
298 fn tuple_of_non_enum() {
299 // for now this case is not handled, although it potentially could be
301 check_assist_not_applicable(
313 fn fill_match_arms_boolean() {
334 fn partial_fill_boolean() {
356 fn all_boolean_tuple_arms_provided() {
357 check_assist_not_applicable(
373 fn fill_boolean_tuple() {
396 fn partial_fill_boolean_tuple() {
420 fn partial_fill_record_tuple() {
426 Bs { x: i32, y: Option<i32> },
427 Cs(i32, Option<i32>),
431 A::Bs { x, y: Some(_) } => {}
432 A::Cs(_, Some(_)) => {}
439 Bs { x: i32, y: Option<i32> },
440 Cs(i32, Option<i32>),
444 A::Bs { x, y: Some(_) } => {}
445 A::Cs(_, Some(_)) => {}
454 fn partial_fill_option() {
458 enum Option<T> { Some(T), None }
468 enum Option<T> { Some(T), None }
482 fn partial_fill_or_pat() {
486 enum A { As, Bs, Cs(Option<i32>) }
489 A::Cs(_) | A::Bs => {}
494 enum A { As, Bs, Cs(Option<i32>) }
497 A::Cs(_) | A::Bs => {}
510 enum A { As, Bs, Cs, Ds(String), Es(B) }
515 A::Ds(_value) => { let x = 1; }
521 enum A { As, Bs, Cs, Ds(String), Es(B) }
526 A::Ds(_value) => { let x = 1; }
537 fn partial_fill_bind_pat() {
541 enum A { As, Bs, Cs(Option<i32>) }
550 enum A { As, Bs, Cs(Option<i32>) }
563 fn fill_match_arms_empty_body() {
567 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
575 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
592 fn fill_match_arms_tuple_of_enum() {
613 $0(A::One, B::One) => {}
614 (A::One, B::Two) => {}
615 (A::Two, B::One) => {}
616 (A::Two, B::Two) => {}
624 fn fill_match_arms_tuple_of_enum_ref() {
645 $0(A::One, B::One) => {}
646 (A::One, B::Two) => {}
647 (A::Two, B::One) => {}
648 (A::Two, B::Two) => {}
656 fn fill_match_arms_tuple_of_enum_partial() {
667 (A::Two, B::One) => {}
679 (A::Two, B::One) => {}
680 $0(A::One, B::One) => {}
681 (A::One, B::Two) => {}
682 (A::Two, B::Two) => {}
690 fn fill_match_arms_tuple_of_enum_partial_with_wildcards() {
697 (None, Some(_)) => {}
703 &format!("//- /main.rs crate:main deps:core{}{}", ra_fixture, FamousDefs::FIXTURE),
710 (None, Some(_)) => {}
719 fn fill_match_arms_partial_with_deep_pattern() {
720 // Fixme: cannot handle deep patterns
729 check_assist_not_applicable(
731 &format!("//- /main.rs crate:main deps:core{}{}", ra_fixture, FamousDefs::FIXTURE),
736 fn fill_match_arms_tuple_of_enum_not_applicable() {
737 check_assist_not_applicable(
747 (A::Two, B::One) => {}
748 (A::One, B::One) => {}
749 (A::One, B::Two) => {}
750 (A::Two, B::Two) => {}
758 fn fill_match_arms_single_element_tuple_of_enum() {
785 fn test_fill_match_arm_refs() {
811 Es { x: usize, y: usize }
821 Es { x: usize, y: usize }
826 $0A::Es { x, y } => {}
834 fn fill_match_arms_target() {
849 fn fill_match_arms_trivial_arm() {
875 fn fill_match_arms_qualifies_path() {
879 mod foo { pub enum E { X, Y } }
889 mod foo { pub enum E { X, Y } }
903 fn fill_match_arms_preserves_comments() {
912 // This is where the rest should be
922 // This is where the rest should be
931 fn fill_match_arms_preserves_comments_empty() {
956 fn fill_match_arms_placeholder() {
981 cov_mark::check!(option_order);
983 fn foo(opt: Option<i32>) {
988 let before = &format!("//- /main.rs crate:main deps:core{}{}", before, FamousDefs::FIXTURE);
994 fn foo(opt: Option<i32>) {
1005 fn works_inside_macro_call() {
1009 macro_rules! m { ($expr:expr) => {$expr}}
1019 r#"macro_rules! m { ($expr:expr) => {$expr}}