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 // We do not currently support filling match arms for a tuple
75 // containing a single enum.
76 if enum_defs.len() < 2 {
80 // When calculating the match arms for a tuple of enums, we want
81 // to create a match arm for each possible combination of enum
82 // values. The `multi_cartesian_product` method transforms
83 // Vec<Vec<EnumVariant>> into Vec<(EnumVariant, .., EnumVariant)>
84 // where each tuple represents a proposed match arm.
87 .map(|enum_def| enum_def.variants(ctx.db()))
88 .multi_cartesian_product()
91 variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant));
92 ast::Pat::from(make::tuple_pat(patterns))
94 .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat))
95 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
101 if missing_arms.is_empty() {
105 let target = ctx.sema.original_range(match_expr.syntax()).range;
107 AssistId("fill_match_arms", AssistKind::QuickFix),
111 let new_arm_list = match_arm_list.remove_placeholder();
112 let n_old_arms = new_arm_list.arms().count();
113 let new_arm_list = new_arm_list.append_arms(missing_arms);
114 let first_new_arm = new_arm_list.arms().nth(n_old_arms);
115 let old_range = ctx.sema.original_range(match_arm_list.syntax()).range;
116 match (first_new_arm, ctx.config.snippet_cap) {
117 (Some(first_new_arm), Some(cap)) => {
120 match first_new_arm.syntax().descendants().find_map(ast::WildcardPat::cast)
123 extend_lifetime = it.syntax().clone();
124 Cursor::Replace(&extend_lifetime)
126 None => Cursor::Before(first_new_arm.syntax()),
128 let snippet = render_snippet(cap, new_arm_list.syntax(), cursor);
129 builder.replace_snippet(cap, old_range, snippet);
131 _ => builder.replace(old_range, new_arm_list.to_string()),
137 fn is_variant_missing(existing_arms: &mut Vec<MatchArm>, var: &Pat) -> bool {
138 existing_arms.iter().filter_map(|arm| arm.pat()).all(|pat| {
139 // Special casee OrPat as separate top-level pats
140 let top_level_pats: Vec<Pat> = match pat {
141 Pat::OrPat(pats) => pats.pats().collect::<Vec<_>>(),
145 !top_level_pats.iter().any(|pat| does_pat_match_variant(pat, var))
149 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
150 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
151 Some(Adt::Enum(e)) => Some(e),
156 fn resolve_tuple_of_enum_def(
157 sema: &Semantics<RootDatabase>,
159 ) -> Option<Vec<hir::Enum>> {
160 sema.type_of_expr(&expr)?
161 .tuple_fields(sema.db)
164 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
165 Some(Adt::Enum(e)) => Some(e),
166 // For now we only handle expansion for a tuple of enums. Here
167 // we map non-enum items to None and rely on `collect` to
168 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
175 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::Variant) -> Option<ast::Pat> {
176 let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?);
178 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
179 let pat: ast::Pat = match var.source(db)?.value.kind() {
180 ast::StructKind::Tuple(field_list) => {
181 let pats = iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count());
182 make::tuple_struct_pat(path, pats).into()
184 ast::StructKind::Record(field_list) => {
185 let pats = field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into());
186 make::record_pat(path, pats).into()
188 ast::StructKind::Unit => make::path_pat(path),
196 use ide_db::helpers::FamousDefs;
198 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
200 use super::fill_match_arms;
203 fn all_match_arms_provided() {
204 check_assist_not_applicable(
209 Bs{x:i32, y:Option<i32>},
210 Cs(i32, Option<i32>),
215 A::Bs{x,y:Some(_)} => {}
216 A::Cs(_, Some(_)) => {}
224 fn tuple_of_non_enum() {
225 // for now this case is not handled, although it potentially could be
227 check_assist_not_applicable(
239 fn partial_fill_record_tuple() {
245 Bs { x: i32, y: Option<i32> },
246 Cs(i32, Option<i32>),
250 A::Bs { x, y: Some(_) } => {}
251 A::Cs(_, Some(_)) => {}
258 Bs { x: i32, y: Option<i32> },
259 Cs(i32, Option<i32>),
263 A::Bs { x, y: Some(_) } => {}
264 A::Cs(_, Some(_)) => {}
273 fn partial_fill_option() {
277 enum Option<T> { Some(T), None }
287 enum Option<T> { Some(T), None }
301 fn partial_fill_or_pat() {
305 enum A { As, Bs, Cs(Option<i32>) }
308 A::Cs(_) | A::Bs => {}
313 enum A { As, Bs, Cs(Option<i32>) }
316 A::Cs(_) | A::Bs => {}
329 enum A { As, Bs, Cs, Ds(String), Es(B) }
334 A::Ds(_value) => { let x = 1; }
340 enum A { As, Bs, Cs, Ds(String), Es(B) }
345 A::Ds(_value) => { let x = 1; }
356 fn partial_fill_bind_pat() {
360 enum A { As, Bs, Cs(Option<i32>) }
369 enum A { As, Bs, Cs(Option<i32>) }
382 fn fill_match_arms_empty_body() {
386 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
394 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
411 fn fill_match_arms_tuple_of_enum() {
432 $0(A::One, B::One) => {}
433 (A::One, B::Two) => {}
434 (A::Two, B::One) => {}
435 (A::Two, B::Two) => {}
443 fn fill_match_arms_tuple_of_enum_ref() {
464 $0(A::One, B::One) => {}
465 (A::One, B::Two) => {}
466 (A::Two, B::One) => {}
467 (A::Two, B::Two) => {}
475 fn fill_match_arms_tuple_of_enum_partial() {
476 check_assist_not_applicable(
486 (A::Two, B::One) => {}
494 fn fill_match_arms_tuple_of_enum_not_applicable() {
495 check_assist_not_applicable(
505 (A::Two, B::One) => {}
506 (A::One, B::One) => {}
507 (A::One, B::Two) => {}
508 (A::Two, B::Two) => {}
516 fn fill_match_arms_single_element_tuple_of_enum() {
517 // For now we don't hande the case of a single element tuple, but
518 // we could handle this in the future if `make::tuple_pat` allowed
519 // creating a tuple with a single pattern.
520 check_assist_not_applicable(
535 fn test_fill_match_arm_refs() {
561 Es { x: usize, y: usize }
571 Es { x: usize, y: usize }
576 $0A::Es { x, y } => {}
584 fn fill_match_arms_target() {
599 fn fill_match_arms_trivial_arm() {
625 fn fill_match_arms_qualifies_path() {
629 mod foo { pub enum E { X, Y } }
639 mod foo { pub enum E { X, Y } }
653 fn fill_match_arms_preserves_comments() {
662 // This is where the rest should be
672 // This is where the rest should be
681 fn fill_match_arms_preserves_comments_empty() {
706 fn fill_match_arms_placeholder() {
731 cov_mark::check!(option_order);
733 fn foo(opt: Option<i32>) {
738 let before = &format!("//- /main.rs crate:main deps:core{}{}", before, FamousDefs::FIXTURE);
744 fn foo(opt: Option<i32>) {
755 fn works_inside_macro_call() {
759 macro_rules! m { ($expr:expr) => {$expr}}
769 r#"macro_rules! m { ($expr:expr) => {$expr}}