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 casee 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()))
75 if Some(enum_def) == FamousDefs(&ctx.sema, Some(module.krate())).core_option_Option() {
76 // Match `Some` variant first.
77 cov_mark::hit!(option_order);
81 } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) {
82 // When calculating the match arms for a tuple of enums, we want
83 // to create a match arm for each possible combination of enum
84 // values. The `multi_cartesian_product` method transforms
85 // Vec<Vec<EnumVariant>> into Vec<(EnumVariant, .., EnumVariant)>
86 // where each tuple represents a proposed match arm.
89 .map(|enum_def| enum_def.variants(ctx.db()))
90 .multi_cartesian_product()
93 variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant));
94 ast::Pat::from(make::tuple_pat(patterns))
96 .filter(|variant_pat| is_variant_missing(&top_lvl_pats, variant_pat))
97 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
103 if missing_arms.is_empty() {
107 let target = ctx.sema.original_range(match_expr.syntax()).range;
109 AssistId("fill_match_arms", AssistKind::QuickFix),
113 let new_arm_list = match_arm_list.remove_placeholder();
114 let n_old_arms = new_arm_list.arms().count();
115 let new_arm_list = new_arm_list.append_arms(missing_arms);
116 let first_new_arm = new_arm_list.arms().nth(n_old_arms);
117 let old_range = ctx.sema.original_range(match_arm_list.syntax()).range;
118 match (first_new_arm, ctx.config.snippet_cap) {
119 (Some(first_new_arm), Some(cap)) => {
122 match first_new_arm.syntax().descendants().find_map(ast::WildcardPat::cast)
125 extend_lifetime = it.syntax().clone();
126 Cursor::Replace(&extend_lifetime)
128 None => Cursor::Before(first_new_arm.syntax()),
130 let snippet = render_snippet(cap, new_arm_list.syntax(), cursor);
131 builder.replace_snippet(cap, old_range, snippet);
133 _ => builder.replace(old_range, new_arm_list.to_string()),
139 fn is_variant_missing(existing_pats: &[Pat], var: &Pat) -> bool {
140 !existing_pats.iter().any(|pat| does_pat_match_variant(pat, var))
143 // Fixme: this is still somewhat limited, use hir_ty::diagnostics::match_check?
144 fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
146 (Pat::WildcardPat(_), _) => true,
147 (Pat::TuplePat(tpat), Pat::TuplePat(tvar)) => {
148 tpat.fields().zip(tvar.fields()).all(|(p, v)| does_pat_match_variant(&p, &v))
150 _ => utils::does_pat_match_variant(pat, var),
154 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
155 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
156 Some(Adt::Enum(e)) => Some(e),
161 fn resolve_tuple_of_enum_def(
162 sema: &Semantics<RootDatabase>,
164 ) -> Option<Vec<hir::Enum>> {
165 sema.type_of_expr(&expr)?
166 .tuple_fields(sema.db)
169 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
170 Some(Adt::Enum(e)) => Some(e),
171 // For now we only handle expansion for a tuple of enums. Here
172 // we map non-enum items to None and rely on `collect` to
173 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
180 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::Variant) -> Option<ast::Pat> {
181 let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?);
183 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
184 let pat: ast::Pat = match var.source(db)?.value.kind() {
185 ast::StructKind::Tuple(field_list) => {
186 let pats = iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count());
187 make::tuple_struct_pat(path, pats).into()
189 ast::StructKind::Record(field_list) => {
190 let pats = field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into());
191 make::record_pat(path, pats).into()
193 ast::StructKind::Unit => make::path_pat(path),
201 use ide_db::helpers::FamousDefs;
203 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
205 use super::fill_match_arms;
208 fn all_match_arms_provided() {
209 check_assist_not_applicable(
214 Bs{x:i32, y:Option<i32>},
215 Cs(i32, Option<i32>),
220 A::Bs{x,y:Some(_)} => {}
221 A::Cs(_, Some(_)) => {}
229 fn tuple_of_non_enum() {
230 // for now this case is not handled, although it potentially could be
232 check_assist_not_applicable(
244 fn partial_fill_record_tuple() {
250 Bs { x: i32, y: Option<i32> },
251 Cs(i32, Option<i32>),
255 A::Bs { x, y: Some(_) } => {}
256 A::Cs(_, Some(_)) => {}
263 Bs { x: i32, y: Option<i32> },
264 Cs(i32, Option<i32>),
268 A::Bs { x, y: Some(_) } => {}
269 A::Cs(_, Some(_)) => {}
278 fn partial_fill_option() {
282 enum Option<T> { Some(T), None }
292 enum Option<T> { Some(T), None }
306 fn partial_fill_or_pat() {
310 enum A { As, Bs, Cs(Option<i32>) }
313 A::Cs(_) | A::Bs => {}
318 enum A { As, Bs, Cs(Option<i32>) }
321 A::Cs(_) | A::Bs => {}
334 enum A { As, Bs, Cs, Ds(String), Es(B) }
339 A::Ds(_value) => { let x = 1; }
345 enum A { As, Bs, Cs, Ds(String), Es(B) }
350 A::Ds(_value) => { let x = 1; }
361 fn partial_fill_bind_pat() {
365 enum A { As, Bs, Cs(Option<i32>) }
374 enum A { As, Bs, Cs(Option<i32>) }
387 fn fill_match_arms_empty_body() {
391 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
399 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
416 fn fill_match_arms_tuple_of_enum() {
437 $0(A::One, B::One) => {}
438 (A::One, B::Two) => {}
439 (A::Two, B::One) => {}
440 (A::Two, B::Two) => {}
448 fn fill_match_arms_tuple_of_enum_ref() {
469 $0(A::One, B::One) => {}
470 (A::One, B::Two) => {}
471 (A::Two, B::One) => {}
472 (A::Two, B::Two) => {}
480 fn fill_match_arms_tuple_of_enum_partial() {
491 (A::Two, B::One) => {}
503 (A::Two, B::One) => {}
504 $0(A::One, B::One) => {}
505 (A::One, B::Two) => {}
506 (A::Two, B::Two) => {}
514 fn fill_match_arms_tuple_of_enum_partial_with_wildcards() {
521 (None, Some(_)) => {}
527 &format!("//- /main.rs crate:main deps:core{}{}", ra_fixture, FamousDefs::FIXTURE),
534 (None, Some(_)) => {}
543 fn fill_match_arms_partial_with_deep_pattern() {
544 // Fixme: cannot handle deep patterns
553 check_assist_not_applicable(
555 &format!("//- /main.rs crate:main deps:core{}{}", ra_fixture, FamousDefs::FIXTURE),
560 fn fill_match_arms_tuple_of_enum_not_applicable() {
561 check_assist_not_applicable(
571 (A::Two, B::One) => {}
572 (A::One, B::One) => {}
573 (A::One, B::Two) => {}
574 (A::Two, B::Two) => {}
582 fn fill_match_arms_single_element_tuple_of_enum() {
609 fn test_fill_match_arm_refs() {
635 Es { x: usize, y: usize }
645 Es { x: usize, y: usize }
650 $0A::Es { x, y } => {}
658 fn fill_match_arms_target() {
673 fn fill_match_arms_trivial_arm() {
699 fn fill_match_arms_qualifies_path() {
703 mod foo { pub enum E { X, Y } }
713 mod foo { pub enum E { X, Y } }
727 fn fill_match_arms_preserves_comments() {
736 // This is where the rest should be
746 // This is where the rest should be
755 fn fill_match_arms_preserves_comments_empty() {
780 fn fill_match_arms_placeholder() {
805 cov_mark::check!(option_order);
807 fn foo(opt: Option<i32>) {
812 let before = &format!("//- /main.rs crate:main deps:core{}{}", before, FamousDefs::FIXTURE);
818 fn foo(opt: Option<i32>) {
829 fn works_inside_macro_call() {
833 macro_rules! m { ($expr:expr) => {$expr}}
843 r#"macro_rules! m { ($expr:expr) => {$expr}}