3 use hir::{Adt, HasSource, ModuleDef, Semantics};
4 use itertools::Itertools;
5 use ra_ide_db::RootDatabase;
6 use ra_syntax::ast::{self, make, AstNode, MatchArm, NameOwner, Pat};
8 use crate::{Assist, AssistCtx, AssistId};
10 // Assist: fill_match_arms
12 // Adds missing clauses to a `match` expression.
15 // enum Action { Move { distance: u32 }, Stop }
17 // fn handle(action: Action) {
25 // enum Action { Move { distance: u32 }, Stop }
27 // fn handle(action: Action) {
29 // Action::Move { distance } => {}
34 pub(crate) fn fill_match_arms(ctx: AssistCtx) -> Option<Assist> {
35 let match_expr = ctx.find_node_at_offset::<ast::MatchExpr>()?;
36 let match_arm_list = match_expr.match_arm_list()?;
38 let expr = match_expr.expr()?;
40 let mut arms: Vec<MatchArm> = match_arm_list.arms().collect();
42 if let Some(Pat::PlaceholderPat(..)) = arms[0].pat() {
47 let module = ctx.sema.scope(expr.syntax()).module()?;
49 let missing_arms: Vec<MatchArm> = if let Some(enum_def) = resolve_enum_def(&ctx.sema, &expr) {
50 let variants = enum_def.variants(ctx.db);
54 .filter_map(|variant| build_pat(ctx.db, module, variant))
55 .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat))
56 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
58 } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) {
59 // Partial fill not currently supported for tuple of enums.
64 // We do not currently support filling match arms for a tuple
65 // containing a single enum.
66 if enum_defs.len() < 2 {
70 // When calculating the match arms for a tuple of enums, we want
71 // to create a match arm for each possible combination of enum
72 // values. The `multi_cartesian_product` method transforms
73 // Vec<Vec<EnumVariant>> into Vec<(EnumVariant, .., EnumVariant)>
74 // where each tuple represents a proposed match arm.
77 .map(|enum_def| enum_def.variants(ctx.db))
78 .multi_cartesian_product()
81 variants.into_iter().filter_map(|variant| build_pat(ctx.db, module, variant));
82 ast::Pat::from(make::tuple_pat(patterns))
84 .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat))
85 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
91 if missing_arms.is_empty() {
95 ctx.add_assist(AssistId("fill_match_arms"), "Fill match arms", |edit| {
96 let new_arm_list = match_arm_list.remove_placeholder().append_arms(missing_arms);
98 edit.target(match_expr.syntax().text_range());
99 edit.set_cursor(expr.syntax().text_range().start());
100 edit.replace_ast(match_arm_list, new_arm_list);
104 fn is_variant_missing(existing_arms: &mut Vec<MatchArm>, var: &Pat) -> bool {
105 existing_arms.iter().filter_map(|arm| arm.pat()).all(|pat| {
106 // Special casee OrPat as separate top-level pats
107 let top_level_pats: Vec<Pat> = match pat {
108 Pat::OrPat(pats) => pats.pats().collect::<Vec<_>>(),
112 !top_level_pats.iter().any(|pat| does_pat_match_variant(pat, var))
116 fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
117 let pat_head = pat.syntax().first_child().map(|node| node.text());
118 let var_head = var.syntax().first_child().map(|node| node.text());
123 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
124 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
125 Some(Adt::Enum(e)) => Some(e),
130 fn resolve_tuple_of_enum_def(
131 sema: &Semantics<RootDatabase>,
133 ) -> Option<Vec<hir::Enum>> {
134 sema.type_of_expr(&expr)?
135 .tuple_fields(sema.db)
138 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
139 Some(Adt::Enum(e)) => Some(e),
140 // For now we only handle expansion for a tuple of enums. Here
141 // we map non-enum items to None and rely on `collect` to
142 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
149 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::EnumVariant) -> Option<ast::Pat> {
150 let path = crate::ast_transform::path_to_ast(module.find_use_path(db, ModuleDef::from(var))?);
152 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
153 let pat: ast::Pat = match var.source(db).value.kind() {
154 ast::StructKind::Tuple(field_list) => {
156 iter::repeat(make::placeholder_pat().into()).take(field_list.fields().count());
157 make::tuple_struct_pat(path, pats).into()
159 ast::StructKind::Record(field_list) => {
160 let pats = field_list.fields().map(|f| make::bind_pat(f.name().unwrap()).into());
161 make::record_pat(path, pats).into()
163 ast::StructKind::Unit => make::path_pat(path),
171 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
173 use super::fill_match_arms;
176 fn all_match_arms_provided() {
177 check_assist_not_applicable(
182 Bs{x:i32, y:Option<i32>},
183 Cs(i32, Option<i32>),
188 A::Bs{x,y:Some(_)} => {}
189 A::Cs(_, Some(_)) => {}
197 fn tuple_of_non_enum() {
198 // for now this case is not handled, although it potentially could be
200 check_assist_not_applicable(
204 match (0, false)<|> {
212 fn partial_fill_record_tuple() {
218 Bs{x:i32, y:Option<i32>},
219 Cs(i32, Option<i32>),
223 A::Bs{x,y:Some(_)} => {}
224 A::Cs(_, Some(_)) => {}
231 Bs{x:i32, y:Option<i32>},
232 Cs(i32, Option<i32>),
236 A::Bs{x,y:Some(_)} => {}
237 A::Cs(_, Some(_)) => {}
246 fn partial_fill_or_pat() {
257 A::Cs(_) | A::Bs => {}
269 A::Cs(_) | A::Bs => {}
296 A::Ds(_value) => { let x = 1; }
316 A::Ds(_value) => { let x = 1; }
327 fn fill_match_arms_empty_body() {
336 Es{ x: usize, y: usize }
350 Es{ x: usize, y: usize }
368 fn fill_match_arms_tuple_of_enum() {
401 (A::One, B::One) => {}
402 (A::One, B::Two) => {}
403 (A::Two, B::One) => {}
404 (A::Two, B::Two) => {}
412 fn fill_match_arms_tuple_of_enum_ref() {
445 (A::One, B::One) => {}
446 (A::One, B::Two) => {}
447 (A::Two, B::One) => {}
448 (A::Two, B::Two) => {}
456 fn fill_match_arms_tuple_of_enum_partial() {
457 check_assist_not_applicable(
473 (A::Two, B::One) => {}
481 fn fill_match_arms_tuple_of_enum_not_applicable() {
482 check_assist_not_applicable(
498 (A::Two, B::One) => {}
499 (A::One, B::One) => {}
500 (A::One, B::Two) => {}
501 (A::Two, B::Two) => {}
509 fn fill_match_arms_single_element_tuple_of_enum() {
510 // For now we don't hande the case of a single element tuple, but
511 // we could handle this in the future if `make::tuple_pat` allowed
512 // creating a tuple with a single pattern.
513 check_assist_not_applicable(
531 fn test_fill_match_arm_refs() {
561 Es{ x: usize, y: usize }
571 Es{ x: usize, y: usize }
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() {
665 // This is where the rest should be
678 // This is where the rest should be
687 fn fill_match_arms_preserves_comments_empty() {
718 fn fill_match_arms_placeholder() {