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, edit::IndentLevel, 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 } => (),
34 // Action::Stop => (),
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_unit()))
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_unit()))
95 if missing_arms.is_empty() {
99 ctx.add_assist(AssistId("fill_match_arms"), "Fill match arms", |edit| {
100 arms.extend(missing_arms);
102 let indent_level = IndentLevel::from_node(match_arm_list.syntax());
103 let new_arm_list = indent_level.increase_indent(make::match_arm_list(arms));
105 edit.target(match_expr.syntax().text_range());
106 edit.set_cursor(expr.syntax().text_range().start());
107 edit.replace_ast(match_arm_list, new_arm_list);
111 fn is_variant_missing(existing_arms: &mut Vec<MatchArm>, var: &Pat) -> bool {
112 existing_arms.iter().filter_map(|arm| arm.pat()).all(|pat| {
113 // Special casee OrPat as separate top-level pats
114 let top_level_pats: Vec<Pat> = match pat {
115 Pat::OrPat(pats) => pats.pats().collect::<Vec<_>>(),
119 !top_level_pats.iter().any(|pat| does_pat_match_variant(pat, var))
123 fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
124 let pat_head = pat.syntax().first_child().map(|node| node.text());
125 let var_head = var.syntax().first_child().map(|node| node.text());
130 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
131 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
132 Some(Adt::Enum(e)) => Some(e),
137 fn resolve_tuple_of_enum_def(
138 sema: &Semantics<RootDatabase>,
140 ) -> Option<Vec<hir::Enum>> {
141 sema.type_of_expr(&expr)?
142 .tuple_fields(sema.db)
145 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
146 Some(Adt::Enum(e)) => Some(e),
147 // For now we only handle expansion for a tuple of enums. Here
148 // we map non-enum items to None and rely on `collect` to
149 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
156 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::EnumVariant) -> Option<ast::Pat> {
157 let path = crate::ast_transform::path_to_ast(module.find_use_path(db, ModuleDef::from(var))?);
159 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
160 let pat: ast::Pat = match var.source(db).value.kind() {
161 ast::StructKind::Tuple(field_list) => {
163 iter::repeat(make::placeholder_pat().into()).take(field_list.fields().count());
164 make::tuple_struct_pat(path, pats).into()
166 ast::StructKind::Record(field_list) => {
167 let pats = field_list.fields().map(|f| make::bind_pat(f.name().unwrap()).into());
168 make::record_pat(path, pats).into()
170 ast::StructKind::Unit => make::path_pat(path),
178 use crate::helpers::{check_assist, check_assist_not_applicable, check_assist_target};
180 use super::fill_match_arms;
183 fn all_match_arms_provided() {
184 check_assist_not_applicable(
189 Bs{x:i32, y:Option<i32>},
190 Cs(i32, Option<i32>),
195 A::Bs{x,y:Some(_)} => (),
196 A::Cs(_, Some(_)) => (),
204 fn tuple_of_non_enum() {
205 // for now this case is not handled, although it potentially could be
207 check_assist_not_applicable(
211 match (0, false)<|> {
219 fn partial_fill_record_tuple() {
225 Bs{x:i32, y:Option<i32>},
226 Cs(i32, Option<i32>),
230 A::Bs{x,y:Some(_)} => (),
231 A::Cs(_, Some(_)) => (),
238 Bs{x:i32, y:Option<i32>},
239 Cs(i32, Option<i32>),
243 A::Bs{x,y:Some(_)} => (),
244 A::Cs(_, Some(_)) => (),
253 fn partial_fill_or_pat() {
264 A::Cs(_) | A::Bs => (),
276 A::Cs(_) | A::Bs => (),
302 A::Bs if 0 < 1 => (),
322 A::Bs if 0 < 1 => (),
334 fn fill_match_arms_empty_body() {
343 Es{ x: usize, y: usize }
357 Es{ x: usize, y: usize }
367 A::Es { x, y } => (),
375 fn fill_match_arms_tuple_of_enum() {
408 (A::One, B::One) => (),
409 (A::One, B::Two) => (),
410 (A::Two, B::One) => (),
411 (A::Two, B::Two) => (),
419 fn fill_match_arms_tuple_of_enum_ref() {
452 (A::One, B::One) => (),
453 (A::One, B::Two) => (),
454 (A::Two, B::One) => (),
455 (A::Two, B::Two) => (),
463 fn fill_match_arms_tuple_of_enum_partial() {
464 check_assist_not_applicable(
480 (A::Two, B::One) => (),
488 fn fill_match_arms_tuple_of_enum_not_applicable() {
489 check_assist_not_applicable(
505 (A::Two, B::One) => (),
506 (A::One, B::One) => (),
507 (A::One, B::Two) => (),
508 (A::Two, B::Two) => (),
516 fn fill_match_arms_single_element_tuple_of_enum() {
517 // For now we don't hande the case of a single element tuple, but
518 // we could handle this in the future if `make::tuple_pat` allowed
519 // creating a tuple with a single pattern.
520 check_assist_not_applicable(
538 fn test_fill_match_arm_refs() {
568 Es{ x: usize, y: usize }
578 Es{ x: usize, y: usize }
583 A::Es { x, y } => (),
591 fn fill_match_arms_target() {
606 fn fill_match_arms_trivial_arm() {
632 fn fill_match_arms_qualifies_path() {
636 mod foo { pub enum E { X, Y } }
646 mod foo { pub enum E { X, Y } }