1 //! FIXME: write short doc here
5 use hir::{Adt, HasSource, ModuleDef, Semantics};
6 use itertools::Itertools;
7 use ra_ide_db::RootDatabase;
9 use crate::{Assist, AssistCtx, AssistId};
10 use ra_syntax::ast::{self, make, AstNode, NameOwner};
12 use ast::{MatchArm, Pat};
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 // Action::Move { distance } => {}
38 pub(crate) fn fill_match_arms(ctx: AssistCtx) -> Option<Assist> {
39 let match_expr = ctx.find_node_at_offset::<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::PlaceholderPat(..)) = 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);
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 } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) {
63 // Partial fill not currently supported for tuple of enums.
68 // We do not currently support filling match arms for a tuple
69 // containing a single enum.
70 if enum_defs.len() < 2 {
74 // When calculating the match arms for a tuple of enums, we want
75 // to create a match arm for each possible combination of enum
76 // values. The `multi_cartesian_product` method transforms
77 // Vec<Vec<EnumVariant>> into Vec<(EnumVariant, .., EnumVariant)>
78 // where each tuple represents a proposed match arm.
81 .map(|enum_def| enum_def.variants(ctx.db))
82 .multi_cartesian_product()
85 variants.into_iter().filter_map(|variant| build_pat(ctx.db, module, variant));
86 ast::Pat::from(make::tuple_pat(patterns))
88 .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat))
89 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
95 if missing_arms.is_empty() {
99 ctx.add_assist(AssistId("fill_match_arms"), "Fill match arms", |edit| {
100 let new_arm_list = match_arm_list.remove_placeholder().append_arms(missing_arms);
102 edit.target(match_expr.syntax().text_range());
103 edit.set_cursor(expr.syntax().text_range().start());
104 edit.replace_ast(match_arm_list, new_arm_list);
108 fn is_variant_missing(existing_arms: &mut Vec<MatchArm>, var: &Pat) -> bool {
109 existing_arms.iter().filter_map(|arm| arm.pat()).all(|pat| {
110 // Special casee OrPat as separate top-level pats
111 let top_level_pats: Vec<Pat> = match pat {
112 Pat::OrPat(pats) => pats.pats().collect::<Vec<_>>(),
116 !top_level_pats.iter().any(|pat| does_pat_match_variant(pat, var))
120 fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
121 let pat_head = pat.syntax().first_child().map(|node| node.text());
122 let var_head = var.syntax().first_child().map(|node| node.text());
127 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
128 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
129 Some(Adt::Enum(e)) => Some(e),
134 fn resolve_tuple_of_enum_def(
135 sema: &Semantics<RootDatabase>,
137 ) -> Option<Vec<hir::Enum>> {
138 sema.type_of_expr(&expr)?
139 .tuple_fields(sema.db)
142 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
143 Some(Adt::Enum(e)) => Some(e),
144 // For now we only handle expansion for a tuple of enums. Here
145 // we map non-enum items to None and rely on `collect` to
146 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
153 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::EnumVariant) -> Option<ast::Pat> {
154 let path = crate::ast_transform::path_to_ast(module.find_use_path(db, ModuleDef::from(var))?);
156 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
157 let pat: ast::Pat = match var.source(db).value.kind() {
158 ast::StructKind::Tuple(field_list) => {
160 iter::repeat(make::placeholder_pat().into()).take(field_list.fields().count());
161 make::tuple_struct_pat(path, pats).into()
163 ast::StructKind::Record(field_list) => {
164 let pats = field_list.fields().map(|f| make::bind_pat(f.name().unwrap()).into());
165 make::record_pat(path, pats).into()
167 ast::StructKind::Unit => make::path_pat(path),
175 use crate::helpers::{check_assist, check_assist_not_applicable, check_assist_target};
177 use super::fill_match_arms;
180 fn all_match_arms_provided() {
181 check_assist_not_applicable(
186 Bs{x:i32, y:Option<i32>},
187 Cs(i32, Option<i32>),
192 A::Bs{x,y:Some(_)} => {}
193 A::Cs(_, Some(_)) => {}
201 fn tuple_of_non_enum() {
202 // for now this case is not handled, although it potentially could be
204 check_assist_not_applicable(
208 match (0, false)<|> {
216 fn partial_fill_record_tuple() {
222 Bs{x:i32, y:Option<i32>},
223 Cs(i32, Option<i32>),
227 A::Bs{x,y:Some(_)} => {}
228 A::Cs(_, Some(_)) => {}
235 Bs{x:i32, y:Option<i32>},
236 Cs(i32, Option<i32>),
240 A::Bs{x,y:Some(_)} => {}
241 A::Cs(_, Some(_)) => {}
250 fn partial_fill_or_pat() {
261 A::Cs(_) | A::Bs => {}
273 A::Cs(_) | A::Bs => {}
300 A::Ds(_value) => { let x = 1; }
320 A::Ds(_value) => { let x = 1; }
331 fn fill_match_arms_empty_body() {
340 Es{ x: usize, y: usize }
354 Es{ x: usize, y: usize }
372 fn fill_match_arms_tuple_of_enum() {
405 (A::One, B::One) => {}
406 (A::One, B::Two) => {}
407 (A::Two, B::One) => {}
408 (A::Two, B::Two) => {}
416 fn fill_match_arms_tuple_of_enum_ref() {
449 (A::One, B::One) => {}
450 (A::One, B::Two) => {}
451 (A::Two, B::One) => {}
452 (A::Two, B::Two) => {}
460 fn fill_match_arms_tuple_of_enum_partial() {
461 check_assist_not_applicable(
477 (A::Two, B::One) => {}
485 fn fill_match_arms_tuple_of_enum_not_applicable() {
486 check_assist_not_applicable(
502 (A::Two, B::One) => {}
503 (A::One, B::One) => {}
504 (A::One, B::Two) => {}
505 (A::Two, B::Two) => {}
513 fn fill_match_arms_single_element_tuple_of_enum() {
514 // For now we don't hande the case of a single element tuple, but
515 // we could handle this in the future if `make::tuple_pat` allowed
516 // creating a tuple with a single pattern.
517 check_assist_not_applicable(
535 fn test_fill_match_arm_refs() {
565 Es{ x: usize, y: usize }
575 Es{ x: usize, y: usize }
588 fn fill_match_arms_target() {
603 fn fill_match_arms_trivial_arm() {
629 fn fill_match_arms_qualifies_path() {
633 mod foo { pub enum E { X, Y } }
643 mod foo { pub enum E { X, Y } }
657 fn fill_match_arms_preserves_comments() {
669 // This is where the rest should be
682 // This is where the rest should be
691 fn fill_match_arms_preserves_comments_empty() {