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::{self, 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| does_pat_match_variant(pat, var))
141 // Fixme: this is still somewhat limited, use hir_ty::diagnostics::match_check?
142 fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
144 (Pat::WildcardPat(_), _) => true,
145 (Pat::TuplePat(tpat), Pat::TuplePat(tvar)) => {
146 tpat.fields().zip(tvar.fields()).all(|(p, v)| does_pat_match_variant(&p, &v))
148 _ => utils::does_pat_match_variant(pat, var),
152 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
153 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
154 Some(Adt::Enum(e)) => Some(e),
159 fn resolve_tuple_of_enum_def(
160 sema: &Semantics<RootDatabase>,
162 ) -> Option<Vec<hir::Enum>> {
163 sema.type_of_expr(&expr)?
164 .tuple_fields(sema.db)
167 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
168 Some(Adt::Enum(e)) => Some(e),
169 // For now we only handle expansion for a tuple of enums. Here
170 // we map non-enum items to None and rely on `collect` to
171 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
178 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::Variant) -> Option<ast::Pat> {
179 let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?);
181 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
182 let pat: ast::Pat = match var.source(db)?.value.kind() {
183 ast::StructKind::Tuple(field_list) => {
184 let pats = iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count());
185 make::tuple_struct_pat(path, pats).into()
187 ast::StructKind::Record(field_list) => {
188 let pats = field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into());
189 make::record_pat(path, pats).into()
191 ast::StructKind::Unit => make::path_pat(path),
199 use ide_db::helpers::FamousDefs;
201 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
203 use super::fill_match_arms;
206 fn all_match_arms_provided() {
207 check_assist_not_applicable(
212 Bs{x:i32, y:Option<i32>},
213 Cs(i32, Option<i32>),
218 A::Bs{x,y:Some(_)} => {}
219 A::Cs(_, Some(_)) => {}
227 fn tuple_of_non_enum() {
228 // for now this case is not handled, although it potentially could be
230 check_assist_not_applicable(
242 fn partial_fill_record_tuple() {
248 Bs { x: i32, y: Option<i32> },
249 Cs(i32, Option<i32>),
253 A::Bs { x, y: Some(_) } => {}
254 A::Cs(_, Some(_)) => {}
261 Bs { x: i32, y: Option<i32> },
262 Cs(i32, Option<i32>),
266 A::Bs { x, y: Some(_) } => {}
267 A::Cs(_, Some(_)) => {}
276 fn partial_fill_option() {
280 enum Option<T> { Some(T), None }
290 enum Option<T> { Some(T), None }
304 fn partial_fill_or_pat() {
308 enum A { As, Bs, Cs(Option<i32>) }
311 A::Cs(_) | A::Bs => {}
316 enum A { As, Bs, Cs(Option<i32>) }
319 A::Cs(_) | A::Bs => {}
332 enum A { As, Bs, Cs, Ds(String), Es(B) }
337 A::Ds(_value) => { let x = 1; }
343 enum A { As, Bs, Cs, Ds(String), Es(B) }
348 A::Ds(_value) => { let x = 1; }
359 fn partial_fill_bind_pat() {
363 enum A { As, Bs, Cs(Option<i32>) }
372 enum A { As, Bs, Cs(Option<i32>) }
385 fn fill_match_arms_empty_body() {
389 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
397 enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
414 fn fill_match_arms_tuple_of_enum() {
435 $0(A::One, B::One) => {}
436 (A::One, B::Two) => {}
437 (A::Two, B::One) => {}
438 (A::Two, B::Two) => {}
446 fn fill_match_arms_tuple_of_enum_ref() {
467 $0(A::One, B::One) => {}
468 (A::One, B::Two) => {}
469 (A::Two, B::One) => {}
470 (A::Two, B::Two) => {}
478 fn fill_match_arms_tuple_of_enum_partial() {
489 (A::Two, B::One) => {}
501 (A::Two, B::One) => {}
502 $0(A::One, B::One) => {}
503 (A::One, B::Two) => {}
504 (A::Two, B::Two) => {}
512 fn fill_match_arms_tuple_of_enum_partial_with_wildcards() {
519 (None, Some(_)) => {}
525 &format!("//- /main.rs crate:main deps:core{}{}", ra_fixture, FamousDefs::FIXTURE),
532 (None, Some(_)) => {}
541 fn fill_match_arms_partial_with_deep_pattern() {
542 // Fixme: cannot handle deep patterns
551 check_assist_not_applicable(
553 &format!("//- /main.rs crate:main deps:core{}{}", ra_fixture, FamousDefs::FIXTURE),
558 fn fill_match_arms_tuple_of_enum_not_applicable() {
559 check_assist_not_applicable(
569 (A::Two, B::One) => {}
570 (A::One, B::One) => {}
571 (A::One, B::Two) => {}
572 (A::Two, B::Two) => {}
580 fn fill_match_arms_single_element_tuple_of_enum() {
607 fn test_fill_match_arm_refs() {
633 Es { x: usize, y: usize }
643 Es { x: usize, y: usize }
648 $0A::Es { x, y } => {}
656 fn fill_match_arms_target() {
671 fn fill_match_arms_trivial_arm() {
697 fn fill_match_arms_qualifies_path() {
701 mod foo { pub enum E { X, Y } }
711 mod foo { pub enum E { X, Y } }
725 fn fill_match_arms_preserves_comments() {
734 // This is where the rest should be
744 // This is where the rest should be
753 fn fill_match_arms_preserves_comments_empty() {
778 fn fill_match_arms_placeholder() {
803 cov_mark::check!(option_order);
805 fn foo(opt: Option<i32>) {
810 let before = &format!("//- /main.rs crate:main deps:core{}{}", before, FamousDefs::FIXTURE);
816 fn foo(opt: Option<i32>) {
827 fn works_inside_macro_call() {
831 macro_rules! m { ($expr:expr) => {$expr}}
841 r#"macro_rules! m { ($expr:expr) => {$expr}}