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::{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 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)),
62 let module = ctx.sema.scope(expr.syntax()).module()?;
64 let missing_arms: Vec<MatchArm> = if let Some(enum_def) = resolve_enum_def(&ctx.sema, &expr) {
65 let variants = enum_def.variants(ctx.db());
67 let mut variants = variants
69 .filter_map(|variant| build_pat(ctx.db(), module, variant))
70 .filter(|variant_pat| is_variant_missing(&top_lvl_pats, variant_pat))
71 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
73 if Some(enum_def) == FamousDefs(&ctx.sema, Some(module.krate())).core_option_Option() {
74 // Match `Some` variant first.
75 cov_mark::hit!(option_order);
79 } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) {
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(&top_lvl_pats, 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_pats: &[Pat], var: &Pat) -> bool {
138 !existing_pats.iter().any(|pat| match (pat, var) {
139 (Pat::TuplePat(tpat), Pat::TuplePat(tvar)) => {
140 // `does_pat_match_variant` gives false positives for tuple patterns
141 // Fixme: this is still somewhat limited
142 tpat.fields().zip(tvar.fields()).all(|(p, v)| does_pat_match_variant(&p, &v))
144 _ => does_pat_match_variant(pat, var),
148 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
149 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
150 Some(Adt::Enum(e)) => Some(e),
155 fn resolve_tuple_of_enum_def(
156 sema: &Semantics<RootDatabase>,
158 ) -> Option<Vec<hir::Enum>> {
159 sema.type_of_expr(&expr)?
160 .tuple_fields(sema.db)
163 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
164 Some(Adt::Enum(e)) => Some(e),
165 // For now we only handle expansion for a tuple of enums. Here
166 // we map non-enum items to None and rely on `collect` to
167 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
174 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::Variant) -> Option<ast::Pat> {
175 let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?);
177 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
178 let pat: ast::Pat = match var.source(db)?.value.kind() {
179 ast::StructKind::Tuple(field_list) => {
180 let pats = iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count());
181 make::tuple_struct_pat(path, pats).into()
183 ast::StructKind::Record(field_list) => {
184 let pats = field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into());
185 make::record_pat(path, pats).into()
187 ast::StructKind::Unit => make::path_pat(path),
195 use ide_db::helpers::FamousDefs;
197 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
199 use super::fill_match_arms;
202 fn all_match_arms_provided() {
203 check_assist_not_applicable(
208 Bs{x:i32, y:Option<i32>},
209 Cs(i32, Option<i32>),
214 A::Bs{x,y:Some(_)} => {}
215 A::Cs(_, Some(_)) => {}
223 fn tuple_of_non_enum() {
224 // for now this case is not handled, although it potentially could be
226 check_assist_not_applicable(
238 fn partial_fill_record_tuple() {
244 Bs { x: i32, y: Option<i32> },
245 Cs(i32, Option<i32>),
249 A::Bs { x, y: Some(_) } => {}
250 A::Cs(_, Some(_)) => {}
257 Bs { x: i32, y: Option<i32> },
258 Cs(i32, Option<i32>),
262 A::Bs { x, y: Some(_) } => {}
263 A::Cs(_, Some(_)) => {}
272 fn partial_fill_option() {
276 enum Option<T> { Some(T), None }
286 enum Option<T> { Some(T), None }
300 fn partial_fill_or_pat() {
304 enum A { As, Bs, Cs(Option<i32>) }
307 A::Cs(_) | A::Bs => {}
312 enum A { As, Bs, Cs(Option<i32>) }
315 A::Cs(_) | A::Bs => {}
328 enum A { As, Bs, Cs, Ds(String), Es(B) }
333 A::Ds(_value) => { let x = 1; }
339 enum A { As, Bs, Cs, Ds(String), Es(B) }
344 A::Ds(_value) => { let x = 1; }
355 fn partial_fill_bind_pat() {
359 enum A { As, Bs, Cs(Option<i32>) }
368 enum A { As, Bs, Cs(Option<i32>) }
381 fn fill_match_arms_empty_body() {
385 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
393 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
410 fn fill_match_arms_tuple_of_enum() {
431 $0(A::One, B::One) => {}
432 (A::One, B::Two) => {}
433 (A::Two, B::One) => {}
434 (A::Two, B::Two) => {}
442 fn fill_match_arms_tuple_of_enum_ref() {
463 $0(A::One, B::One) => {}
464 (A::One, B::Two) => {}
465 (A::Two, B::One) => {}
466 (A::Two, B::Two) => {}
474 fn fill_match_arms_tuple_of_enum_partial() {
485 (A::Two, B::One) => {}
497 (A::Two, B::One) => {}
498 $0(A::One, B::One) => {}
499 (A::One, B::Two) => {}
500 (A::Two, B::Two) => {}
507 // Fixme: This fails with extra useless match arms added.
508 // To fix, it needs full fledged match exhaustiveness checking from
509 // hir_ty::diagnostics::match_check
510 // see https://github.com/rust-analyzer/rust-analyzer/issues/8493
513 fn fill_match_arms_tuple_of_enum_partial_with_wildcards() {
520 (None, Some(_)) => {}
526 &format!("//- /main.rs crate:main deps:core{}{}", ra_fixture, FamousDefs::FIXTURE),
533 (None, Some(_)) => {}
542 fn fill_match_arms_tuple_of_enum_not_applicable() {
543 check_assist_not_applicable(
553 (A::Two, B::One) => {}
554 (A::One, B::One) => {}
555 (A::One, B::Two) => {}
556 (A::Two, B::Two) => {}
564 fn fill_match_arms_single_element_tuple_of_enum() {
591 fn test_fill_match_arm_refs() {
617 Es { x: usize, y: usize }
627 Es { x: usize, y: usize }
632 $0A::Es { x, y } => {}
640 fn fill_match_arms_target() {
655 fn fill_match_arms_trivial_arm() {
681 fn fill_match_arms_qualifies_path() {
685 mod foo { pub enum E { X, Y } }
695 mod foo { pub enum E { X, Y } }
709 fn fill_match_arms_preserves_comments() {
718 // This is where the rest should be
728 // This is where the rest should be
737 fn fill_match_arms_preserves_comments_empty() {
762 fn fill_match_arms_placeholder() {
787 cov_mark::check!(option_order);
789 fn foo(opt: Option<i32>) {
794 let before = &format!("//- /main.rs crate:main deps:core{}{}", before, FamousDefs::FIXTURE);
800 fn foo(opt: Option<i32>) {
811 fn works_inside_macro_call() {
815 macro_rules! m { ($expr:expr) => {$expr}}
825 r#"macro_rules! m { ($expr:expr) => {$expr}}