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 let target = match_expr.syntax().text_range();
96 ctx.add_assist(AssistId("fill_match_arms"), "Fill match arms", target, |edit| {
97 let new_arm_list = match_arm_list.remove_placeholder().append_arms(missing_arms);
98 edit.set_cursor(expr.syntax().text_range().start());
99 edit.replace_ast(match_arm_list, new_arm_list);
103 fn is_variant_missing(existing_arms: &mut Vec<MatchArm>, var: &Pat) -> bool {
104 existing_arms.iter().filter_map(|arm| arm.pat()).all(|pat| {
105 // Special casee OrPat as separate top-level pats
106 let top_level_pats: Vec<Pat> = match pat {
107 Pat::OrPat(pats) => pats.pats().collect::<Vec<_>>(),
111 !top_level_pats.iter().any(|pat| does_pat_match_variant(pat, var))
115 fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
116 let pat_head = pat.syntax().first_child().map(|node| node.text());
117 let var_head = var.syntax().first_child().map(|node| node.text());
122 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
123 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
124 Some(Adt::Enum(e)) => Some(e),
129 fn resolve_tuple_of_enum_def(
130 sema: &Semantics<RootDatabase>,
132 ) -> Option<Vec<hir::Enum>> {
133 sema.type_of_expr(&expr)?
134 .tuple_fields(sema.db)
137 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
138 Some(Adt::Enum(e)) => Some(e),
139 // For now we only handle expansion for a tuple of enums. Here
140 // we map non-enum items to None and rely on `collect` to
141 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
148 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::EnumVariant) -> Option<ast::Pat> {
149 let path = crate::ast_transform::path_to_ast(module.find_use_path(db, ModuleDef::from(var))?);
151 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
152 let pat: ast::Pat = match var.source(db).value.kind() {
153 ast::StructKind::Tuple(field_list) => {
155 iter::repeat(make::placeholder_pat().into()).take(field_list.fields().count());
156 make::tuple_struct_pat(path, pats).into()
158 ast::StructKind::Record(field_list) => {
159 let pats = field_list.fields().map(|f| make::bind_pat(f.name().unwrap()).into());
160 make::record_pat(path, pats).into()
162 ast::StructKind::Unit => make::path_pat(path),
170 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
172 use super::fill_match_arms;
175 fn all_match_arms_provided() {
176 check_assist_not_applicable(
181 Bs{x:i32, y:Option<i32>},
182 Cs(i32, Option<i32>),
187 A::Bs{x,y:Some(_)} => {}
188 A::Cs(_, Some(_)) => {}
196 fn tuple_of_non_enum() {
197 // for now this case is not handled, although it potentially could be
199 check_assist_not_applicable(
203 match (0, false)<|> {
211 fn partial_fill_record_tuple() {
217 Bs{x:i32, y:Option<i32>},
218 Cs(i32, Option<i32>),
222 A::Bs{x,y:Some(_)} => {}
223 A::Cs(_, Some(_)) => {}
230 Bs{x:i32, y:Option<i32>},
231 Cs(i32, Option<i32>),
235 A::Bs{x,y:Some(_)} => {}
236 A::Cs(_, Some(_)) => {}
245 fn partial_fill_or_pat() {
256 A::Cs(_) | A::Bs => {}
268 A::Cs(_) | A::Bs => {}
295 A::Ds(_value) => { let x = 1; }
315 A::Ds(_value) => { let x = 1; }
326 fn fill_match_arms_empty_body() {
335 Es{ x: usize, y: usize }
349 Es{ x: usize, y: usize }
367 fn fill_match_arms_tuple_of_enum() {
400 (A::One, B::One) => {}
401 (A::One, B::Two) => {}
402 (A::Two, B::One) => {}
403 (A::Two, B::Two) => {}
411 fn fill_match_arms_tuple_of_enum_ref() {
444 (A::One, B::One) => {}
445 (A::One, B::Two) => {}
446 (A::Two, B::One) => {}
447 (A::Two, B::Two) => {}
455 fn fill_match_arms_tuple_of_enum_partial() {
456 check_assist_not_applicable(
472 (A::Two, B::One) => {}
480 fn fill_match_arms_tuple_of_enum_not_applicable() {
481 check_assist_not_applicable(
497 (A::Two, B::One) => {}
498 (A::One, B::One) => {}
499 (A::One, B::Two) => {}
500 (A::Two, B::Two) => {}
508 fn fill_match_arms_single_element_tuple_of_enum() {
509 // For now we don't hande the case of a single element tuple, but
510 // we could handle this in the future if `make::tuple_pat` allowed
511 // creating a tuple with a single pattern.
512 check_assist_not_applicable(
530 fn test_fill_match_arm_refs() {
560 Es{ x: usize, y: usize }
570 Es{ x: usize, y: usize }
583 fn fill_match_arms_target() {
598 fn fill_match_arms_trivial_arm() {
624 fn fill_match_arms_qualifies_path() {
628 mod foo { pub enum E { X, Y } }
638 mod foo { pub enum E { X, Y } }
652 fn fill_match_arms_preserves_comments() {
664 // This is where the rest should be
677 // This is where the rest should be
686 fn fill_match_arms_preserves_comments_empty() {
717 fn fill_match_arms_placeholder() {