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::{does_pat_match_variant, 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 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 = ctx.sema.original_range(match_expr.syntax()).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 = ctx.sema.original_range(match_arm_list.syntax()).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 resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
151 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
152 Some(Adt::Enum(e)) => Some(e),
157 fn resolve_tuple_of_enum_def(
158 sema: &Semantics<RootDatabase>,
160 ) -> Option<Vec<hir::Enum>> {
161 sema.type_of_expr(&expr)?
162 .tuple_fields(sema.db)
165 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
166 Some(Adt::Enum(e)) => Some(e),
167 // For now we only handle expansion for a tuple of enums. Here
168 // we map non-enum items to None and rely on `collect` to
169 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
176 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::Variant) -> Option<ast::Pat> {
177 let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?);
179 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
180 let pat: ast::Pat = match var.source(db)?.value.kind() {
181 ast::StructKind::Tuple(field_list) => {
182 let pats = iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count());
183 make::tuple_struct_pat(path, pats).into()
185 ast::StructKind::Record(field_list) => {
186 let pats = field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into());
187 make::record_pat(path, pats).into()
189 ast::StructKind::Unit => make::path_pat(path),
197 use ide_db::helpers::FamousDefs;
198 use test_utils::mark;
200 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
202 use super::fill_match_arms;
205 fn all_match_arms_provided() {
206 check_assist_not_applicable(
211 Bs{x:i32, y:Option<i32>},
212 Cs(i32, Option<i32>),
217 A::Bs{x,y:Some(_)} => {}
218 A::Cs(_, Some(_)) => {}
226 fn tuple_of_non_enum() {
227 // for now this case is not handled, although it potentially could be
229 check_assist_not_applicable(
241 fn partial_fill_record_tuple() {
247 Bs { x: i32, y: Option<i32> },
248 Cs(i32, Option<i32>),
252 A::Bs { x, y: Some(_) } => {}
253 A::Cs(_, Some(_)) => {}
260 Bs { x: i32, y: Option<i32> },
261 Cs(i32, Option<i32>),
265 A::Bs { x, y: Some(_) } => {}
266 A::Cs(_, Some(_)) => {}
275 fn partial_fill_option() {
279 enum Option<T> { Some(T), None }
289 enum Option<T> { Some(T), None }
303 fn partial_fill_or_pat() {
307 enum A { As, Bs, Cs(Option<i32>) }
310 A::Cs(_) | A::Bs => {}
315 enum A { As, Bs, Cs(Option<i32>) }
318 A::Cs(_) | A::Bs => {}
331 enum A { As, Bs, Cs, Ds(String), Es(B) }
336 A::Ds(_value) => { let x = 1; }
342 enum A { As, Bs, Cs, Ds(String), Es(B) }
347 A::Ds(_value) => { let x = 1; }
358 fn partial_fill_bind_pat() {
362 enum A { As, Bs, Cs(Option<i32>) }
371 enum A { As, Bs, Cs(Option<i32>) }
384 fn fill_match_arms_empty_body() {
388 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
396 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
413 fn fill_match_arms_tuple_of_enum() {
434 $0(A::One, B::One) => {}
435 (A::One, B::Two) => {}
436 (A::Two, B::One) => {}
437 (A::Two, B::Two) => {}
445 fn fill_match_arms_tuple_of_enum_ref() {
466 $0(A::One, B::One) => {}
467 (A::One, B::Two) => {}
468 (A::Two, B::One) => {}
469 (A::Two, B::Two) => {}
477 fn fill_match_arms_tuple_of_enum_partial() {
478 check_assist_not_applicable(
488 (A::Two, B::One) => {}
496 fn fill_match_arms_tuple_of_enum_not_applicable() {
497 check_assist_not_applicable(
507 (A::Two, B::One) => {}
508 (A::One, B::One) => {}
509 (A::One, B::Two) => {}
510 (A::Two, B::Two) => {}
518 fn fill_match_arms_single_element_tuple_of_enum() {
519 // For now we don't hande the case of a single element tuple, but
520 // we could handle this in the future if `make::tuple_pat` allowed
521 // creating a tuple with a single pattern.
522 check_assist_not_applicable(
537 fn test_fill_match_arm_refs() {
563 Es { x: usize, y: usize }
573 Es { x: usize, y: usize }
578 $0A::Es { x, y } => {}
586 fn fill_match_arms_target() {
601 fn fill_match_arms_trivial_arm() {
627 fn fill_match_arms_qualifies_path() {
631 mod foo { pub enum E { X, Y } }
641 mod foo { pub enum E { X, Y } }
655 fn fill_match_arms_preserves_comments() {
664 // This is where the rest should be
674 // This is where the rest should be
683 fn fill_match_arms_preserves_comments_empty() {
708 fn fill_match_arms_placeholder() {
733 mark::check!(option_order);
735 fn foo(opt: Option<i32>) {
740 let before = &format!("//- /main.rs crate:main deps:core{}{}", before, FamousDefs::FIXTURE);
746 fn foo(opt: Option<i32>) {
757 fn works_inside_macro_call() {
761 macro_rules! m { ($expr:expr) => {$expr}}
771 r#"macro_rules! m { ($expr:expr) => {$expr}}