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};
10 utils::{does_pat_match_variant, render_snippet, Cursor},
11 AssistContext, AssistId, AssistKind, Assists,
14 // Assist: fill_match_arms
16 // Adds missing clauses to a `match` expression.
19 // enum Action { Move { distance: u32 }, Stop }
21 // fn handle(action: Action) {
29 // enum Action { Move { distance: u32 }, Stop }
31 // fn handle(action: Action) {
33 // $0Action::Move { distance } => {}
38 pub(crate) fn fill_match_arms(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
39 let match_expr = ctx.find_node_at_offset_with_descend::<ast::MatchExpr>()?;
40 let match_arm_list = match_expr.match_arm_list()?;
42 let expr = match_expr.expr()?;
44 let mut arms: Vec<MatchArm> = match_arm_list.arms().collect();
46 if let Some(Pat::WildcardPat(..)) = arms[0].pat() {
51 let module = ctx.sema.scope(expr.syntax()).module()?;
53 let missing_arms: Vec<MatchArm> = if let Some(enum_def) = resolve_enum_def(&ctx.sema, &expr) {
54 let variants = enum_def.variants(ctx.db());
56 let mut variants = variants
58 .filter_map(|variant| build_pat(ctx.db(), module, variant))
59 .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat))
60 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
62 if Some(enum_def) == FamousDefs(&ctx.sema, Some(module.krate())).core_option_Option() {
63 // Match `Some` variant first.
64 cov_mark::hit!(option_order);
68 } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) {
69 // Partial fill not currently supported for tuple of enums.
74 // When calculating the match arms for a tuple of enums, we want
75 // to create a match arm for each possible combination of enum
76 // values. The `multi_cartesian_product` method transforms
77 // Vec<Vec<EnumVariant>> into Vec<(EnumVariant, .., EnumVariant)>
78 // where each tuple represents a proposed match arm.
81 .map(|enum_def| enum_def.variants(ctx.db()))
82 .multi_cartesian_product()
85 variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant));
86 ast::Pat::from(make::tuple_pat(patterns))
88 .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat))
89 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
95 if missing_arms.is_empty() {
99 let target = ctx.sema.original_range(match_expr.syntax()).range;
101 AssistId("fill_match_arms", AssistKind::QuickFix),
105 let new_arm_list = match_arm_list.remove_placeholder();
106 let n_old_arms = new_arm_list.arms().count();
107 let new_arm_list = new_arm_list.append_arms(missing_arms);
108 let first_new_arm = new_arm_list.arms().nth(n_old_arms);
109 let old_range = ctx.sema.original_range(match_arm_list.syntax()).range;
110 match (first_new_arm, ctx.config.snippet_cap) {
111 (Some(first_new_arm), Some(cap)) => {
114 match first_new_arm.syntax().descendants().find_map(ast::WildcardPat::cast)
117 extend_lifetime = it.syntax().clone();
118 Cursor::Replace(&extend_lifetime)
120 None => Cursor::Before(first_new_arm.syntax()),
122 let snippet = render_snippet(cap, new_arm_list.syntax(), cursor);
123 builder.replace_snippet(cap, old_range, snippet);
125 _ => builder.replace(old_range, new_arm_list.to_string()),
131 fn is_variant_missing(existing_arms: &mut Vec<MatchArm>, var: &Pat) -> bool {
132 existing_arms.iter().filter_map(|arm| arm.pat()).all(|pat| {
133 // Special casee OrPat as separate top-level pats
134 let top_level_pats: Vec<Pat> = match pat {
135 Pat::OrPat(pats) => pats.pats().collect::<Vec<_>>(),
139 !top_level_pats.iter().any(|pat| does_pat_match_variant(pat, var))
143 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
144 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
145 Some(Adt::Enum(e)) => Some(e),
150 fn resolve_tuple_of_enum_def(
151 sema: &Semantics<RootDatabase>,
153 ) -> Option<Vec<hir::Enum>> {
154 sema.type_of_expr(&expr)?
155 .tuple_fields(sema.db)
158 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
159 Some(Adt::Enum(e)) => Some(e),
160 // For now we only handle expansion for a tuple of enums. Here
161 // we map non-enum items to None and rely on `collect` to
162 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
169 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::Variant) -> Option<ast::Pat> {
170 let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?);
172 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
173 let pat: ast::Pat = match var.source(db)?.value.kind() {
174 ast::StructKind::Tuple(field_list) => {
175 let pats = iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count());
176 make::tuple_struct_pat(path, pats).into()
178 ast::StructKind::Record(field_list) => {
179 let pats = field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into());
180 make::record_pat(path, pats).into()
182 ast::StructKind::Unit => make::path_pat(path),
190 use ide_db::helpers::FamousDefs;
192 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
194 use super::fill_match_arms;
197 fn all_match_arms_provided() {
198 check_assist_not_applicable(
203 Bs{x:i32, y:Option<i32>},
204 Cs(i32, Option<i32>),
209 A::Bs{x,y:Some(_)} => {}
210 A::Cs(_, Some(_)) => {}
218 fn tuple_of_non_enum() {
219 // for now this case is not handled, although it potentially could be
221 check_assist_not_applicable(
233 fn partial_fill_record_tuple() {
239 Bs { x: i32, y: Option<i32> },
240 Cs(i32, Option<i32>),
244 A::Bs { x, y: Some(_) } => {}
245 A::Cs(_, Some(_)) => {}
252 Bs { x: i32, y: Option<i32> },
253 Cs(i32, Option<i32>),
257 A::Bs { x, y: Some(_) } => {}
258 A::Cs(_, Some(_)) => {}
267 fn partial_fill_option() {
271 enum Option<T> { Some(T), None }
281 enum Option<T> { Some(T), None }
295 fn partial_fill_or_pat() {
299 enum A { As, Bs, Cs(Option<i32>) }
302 A::Cs(_) | A::Bs => {}
307 enum A { As, Bs, Cs(Option<i32>) }
310 A::Cs(_) | A::Bs => {}
323 enum A { As, Bs, Cs, Ds(String), Es(B) }
328 A::Ds(_value) => { let x = 1; }
334 enum A { As, Bs, Cs, Ds(String), Es(B) }
339 A::Ds(_value) => { let x = 1; }
350 fn partial_fill_bind_pat() {
354 enum A { As, Bs, Cs(Option<i32>) }
363 enum A { As, Bs, Cs(Option<i32>) }
376 fn fill_match_arms_empty_body() {
380 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
388 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
405 fn fill_match_arms_tuple_of_enum() {
426 $0(A::One, B::One) => {}
427 (A::One, B::Two) => {}
428 (A::Two, B::One) => {}
429 (A::Two, B::Two) => {}
437 fn fill_match_arms_tuple_of_enum_ref() {
458 $0(A::One, B::One) => {}
459 (A::One, B::Two) => {}
460 (A::Two, B::One) => {}
461 (A::Two, B::Two) => {}
469 fn fill_match_arms_tuple_of_enum_partial() {
470 check_assist_not_applicable(
480 (A::Two, B::One) => {}
488 fn fill_match_arms_tuple_of_enum_not_applicable() {
489 check_assist_not_applicable(
499 (A::Two, B::One) => {}
500 (A::One, B::One) => {}
501 (A::One, B::Two) => {}
502 (A::Two, B::Two) => {}
510 fn fill_match_arms_single_element_tuple_of_enum() {
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 cov_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}}