3 use hir::{Adt, HasSource, ModuleDef, Semantics};
4 use ide_db::helpers::{mod_path_to_ast, FamousDefs};
5 use ide_db::RootDatabase;
6 use itertools::Itertools;
7 use syntax::ast::{self, make, AstNode, MatchArm, NameOwner, Pat};
11 utils::{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::<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 module = ctx.sema.scope(expr.syntax()).module()?;
54 let missing_arms: Vec<MatchArm> = if let Some(enum_def) = resolve_enum_def(&ctx.sema, &expr) {
55 let variants = enum_def.variants(ctx.db());
57 let mut variants = variants
59 .filter_map(|variant| build_pat(ctx.db(), module, variant))
60 .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat))
61 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
63 if Some(enum_def) == FamousDefs(&ctx.sema, Some(module.krate())).core_option_Option() {
64 // Match `Some` variant first.
65 mark::hit!(option_order);
69 } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) {
70 // Partial fill not currently supported for tuple of enums.
75 // We do not currently support filling match arms for a tuple
76 // containing a single enum.
77 if enum_defs.len() < 2 {
81 // When calculating the match arms for a tuple of enums, we want
82 // to create a match arm for each possible combination of enum
83 // values. The `multi_cartesian_product` method transforms
84 // Vec<Vec<EnumVariant>> into Vec<(EnumVariant, .., EnumVariant)>
85 // where each tuple represents a proposed match arm.
88 .map(|enum_def| enum_def.variants(ctx.db()))
89 .multi_cartesian_product()
92 variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant));
93 ast::Pat::from(make::tuple_pat(patterns))
95 .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat))
96 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
102 if missing_arms.is_empty() {
106 let target = match_expr.syntax().text_range();
108 AssistId("fill_match_arms", AssistKind::QuickFix),
112 let new_arm_list = match_arm_list.remove_placeholder();
113 let n_old_arms = new_arm_list.arms().count();
114 let new_arm_list = new_arm_list.append_arms(missing_arms);
115 let first_new_arm = new_arm_list.arms().nth(n_old_arms);
116 let old_range = match_arm_list.syntax().text_range();
117 match (first_new_arm, ctx.config.snippet_cap) {
118 (Some(first_new_arm), Some(cap)) => {
121 match first_new_arm.syntax().descendants().find_map(ast::WildcardPat::cast)
124 extend_lifetime = it.syntax().clone();
125 Cursor::Replace(&extend_lifetime)
127 None => Cursor::Before(first_new_arm.syntax()),
129 let snippet = render_snippet(cap, new_arm_list.syntax(), cursor);
130 builder.replace_snippet(cap, old_range, snippet);
132 _ => builder.replace(old_range, new_arm_list.to_string()),
138 fn is_variant_missing(existing_arms: &mut Vec<MatchArm>, var: &Pat) -> bool {
139 existing_arms.iter().filter_map(|arm| arm.pat()).all(|pat| {
140 // Special casee OrPat as separate top-level pats
141 let top_level_pats: Vec<Pat> = match pat {
142 Pat::OrPat(pats) => pats.pats().collect::<Vec<_>>(),
146 !top_level_pats.iter().any(|pat| does_pat_match_variant(pat, var))
150 fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
151 let first_node_text = |pat: &Pat| pat.syntax().first_child().map(|node| node.text());
153 let pat_head = match pat {
154 Pat::IdentPat(bind_pat) => {
155 if let Some(p) = bind_pat.pat() {
161 pat => first_node_text(pat),
164 let var_head = first_node_text(var);
169 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
170 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
171 Some(Adt::Enum(e)) => Some(e),
176 fn resolve_tuple_of_enum_def(
177 sema: &Semantics<RootDatabase>,
179 ) -> Option<Vec<hir::Enum>> {
180 sema.type_of_expr(&expr)?
181 .tuple_fields(sema.db)
184 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
185 Some(Adt::Enum(e)) => Some(e),
186 // For now we only handle expansion for a tuple of enums. Here
187 // we map non-enum items to None and rely on `collect` to
188 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
195 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::EnumVariant) -> Option<ast::Pat> {
196 let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?);
198 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
199 let pat: ast::Pat = match var.source(db).value.kind() {
200 ast::StructKind::Tuple(field_list) => {
201 let pats = iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count());
202 make::tuple_struct_pat(path, pats).into()
204 ast::StructKind::Record(field_list) => {
205 let pats = field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into());
206 make::record_pat(path, pats).into()
208 ast::StructKind::Unit => make::path_pat(path),
216 use ide_db::helpers::FamousDefs;
217 use test_utils::mark;
219 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
221 use super::fill_match_arms;
224 fn all_match_arms_provided() {
225 check_assist_not_applicable(
230 Bs{x:i32, y:Option<i32>},
231 Cs(i32, Option<i32>),
236 A::Bs{x,y:Some(_)} => {}
237 A::Cs(_, Some(_)) => {}
245 fn tuple_of_non_enum() {
246 // for now this case is not handled, although it potentially could be
248 check_assist_not_applicable(
252 match (0, false)<|> {
260 fn partial_fill_record_tuple() {
266 Bs { x: i32, y: Option<i32> },
267 Cs(i32, Option<i32>),
271 A::Bs { x, y: Some(_) } => {}
272 A::Cs(_, Some(_)) => {}
279 Bs { x: i32, y: Option<i32> },
280 Cs(i32, Option<i32>),
284 A::Bs { x, y: Some(_) } => {}
285 A::Cs(_, Some(_)) => {}
294 fn partial_fill_or_pat() {
298 enum A { As, Bs, Cs(Option<i32>) }
301 A::Cs(_) | A::Bs => {}
306 enum A { As, Bs, Cs(Option<i32>) }
309 A::Cs(_) | A::Bs => {}
322 enum A { As, Bs, Cs, Ds(String), Es(B) }
327 A::Ds(_value) => { let x = 1; }
333 enum A { As, Bs, Cs, Ds(String), Es(B) }
338 A::Ds(_value) => { let x = 1; }
349 fn partial_fill_bind_pat() {
353 enum A { As, Bs, Cs(Option<i32>) }
362 enum A { As, Bs, Cs(Option<i32>) }
375 fn fill_match_arms_empty_body() {
379 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
387 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
404 fn fill_match_arms_tuple_of_enum() {
425 $0(A::One, B::One) => {}
426 (A::One, B::Two) => {}
427 (A::Two, B::One) => {}
428 (A::Two, B::Two) => {}
436 fn fill_match_arms_tuple_of_enum_ref() {
457 $0(A::One, B::One) => {}
458 (A::One, B::Two) => {}
459 (A::Two, B::One) => {}
460 (A::Two, B::Two) => {}
468 fn fill_match_arms_tuple_of_enum_partial() {
469 check_assist_not_applicable(
479 (A::Two, B::One) => {}
487 fn fill_match_arms_tuple_of_enum_not_applicable() {
488 check_assist_not_applicable(
498 (A::Two, B::One) => {}
499 (A::One, B::One) => {}
500 (A::One, B::Two) => {}
501 (A::Two, B::Two) => {}
509 fn fill_match_arms_single_element_tuple_of_enum() {
510 // For now we don't hande the case of a single element tuple, but
511 // we could handle this in the future if `make::tuple_pat` allowed
512 // creating a tuple with a single pattern.
513 check_assist_not_applicable(
528 fn test_fill_match_arm_refs() {
554 Es { x: usize, y: usize }
564 Es { x: usize, y: usize }
569 $0A::Es { x, y } => {}
577 fn fill_match_arms_target() {
592 fn fill_match_arms_trivial_arm() {
618 fn fill_match_arms_qualifies_path() {
622 mod foo { pub enum E { X, Y } }
632 mod foo { pub enum E { X, Y } }
646 fn fill_match_arms_preserves_comments() {
655 // This is where the rest should be
665 // This is where the rest should be
674 fn fill_match_arms_preserves_comments_empty() {
699 fn fill_match_arms_placeholder() {
724 mark::check!(option_order);
726 fn foo(opt: Option<i32>) {
731 let before = &format!("//- /main.rs crate:main deps:core{}{}", before, FamousDefs::FIXTURE);
737 fn foo(opt: Option<i32>) {