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};
10 utils::{render_snippet, Cursor, FamousDefs},
11 AssistContext, AssistId, Assists,
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 // $0Action::Move { distance } => {}
38 pub(crate) fn fill_match_arms(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
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);
56 let mut variants = variants
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 if Some(enum_def) == FamousDefs(&ctx.sema, module.krate()).core_option_Option() {
63 // Match `Some` variant first.
64 mark::hit!(option_order);
68 } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) {
69 // Partial fill not currently supported for tuple of enums.
74 // We do not currently support filling match arms for a tuple
75 // containing a single enum.
76 if enum_defs.len() < 2 {
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(&mut arms, variant_pat))
95 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
101 if missing_arms.is_empty() {
105 let target = match_expr.syntax().text_range();
106 acc.add(AssistId("fill_match_arms"), "Fill match arms", target, |builder| {
107 let new_arm_list = match_arm_list.remove_placeholder();
108 let n_old_arms = new_arm_list.arms().count();
109 let new_arm_list = new_arm_list.append_arms(missing_arms);
110 let first_new_arm = new_arm_list.arms().nth(n_old_arms);
111 let old_range = match_arm_list.syntax().text_range();
112 match (first_new_arm, ctx.config.snippet_cap) {
113 (Some(first_new_arm), Some(cap)) => {
114 let snippet = render_snippet(
116 new_arm_list.syntax(),
117 Cursor::Before(first_new_arm.syntax()),
119 builder.replace_snippet(cap, old_range, snippet);
121 _ => builder.replace(old_range, new_arm_list.to_string()),
126 fn is_variant_missing(existing_arms: &mut Vec<MatchArm>, var: &Pat) -> bool {
127 existing_arms.iter().filter_map(|arm| arm.pat()).all(|pat| {
128 // Special casee OrPat as separate top-level pats
129 let top_level_pats: Vec<Pat> = match pat {
130 Pat::OrPat(pats) => pats.pats().collect::<Vec<_>>(),
134 !top_level_pats.iter().any(|pat| does_pat_match_variant(pat, var))
138 fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
139 let pat_head = pat.syntax().first_child().map(|node| node.text());
140 let var_head = var.syntax().first_child().map(|node| node.text());
145 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
146 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
147 Some(Adt::Enum(e)) => Some(e),
152 fn resolve_tuple_of_enum_def(
153 sema: &Semantics<RootDatabase>,
155 ) -> Option<Vec<hir::Enum>> {
156 sema.type_of_expr(&expr)?
157 .tuple_fields(sema.db)
160 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
161 Some(Adt::Enum(e)) => Some(e),
162 // For now we only handle expansion for a tuple of enums. Here
163 // we map non-enum items to None and rely on `collect` to
164 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
171 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::EnumVariant) -> Option<ast::Pat> {
172 let path = crate::ast_transform::path_to_ast(module.find_use_path(db, ModuleDef::from(var))?);
174 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
175 let pat: ast::Pat = match var.source(db).value.kind() {
176 ast::StructKind::Tuple(field_list) => {
178 iter::repeat(make::placeholder_pat().into()).take(field_list.fields().count());
179 make::tuple_struct_pat(path, pats).into()
181 ast::StructKind::Record(field_list) => {
182 let pats = field_list.fields().map(|f| make::bind_pat(f.name().unwrap()).into());
183 make::record_pat(path, pats).into()
185 ast::StructKind::Unit => make::path_pat(path),
193 use test_utils::mark;
196 tests::{check_assist, check_assist_not_applicable, check_assist_target},
200 use super::fill_match_arms;
203 fn all_match_arms_provided() {
204 check_assist_not_applicable(
209 Bs{x:i32, y:Option<i32>},
210 Cs(i32, Option<i32>),
215 A::Bs{x,y:Some(_)} => {}
216 A::Cs(_, Some(_)) => {}
224 fn tuple_of_non_enum() {
225 // for now this case is not handled, although it potentially could be
227 check_assist_not_applicable(
231 match (0, false)<|> {
239 fn partial_fill_record_tuple() {
245 Bs { x: i32, y: Option<i32> },
246 Cs(i32, Option<i32>),
250 A::Bs { x, y: Some(_) } => {}
251 A::Cs(_, Some(_)) => {}
258 Bs { x: i32, y: Option<i32> },
259 Cs(i32, Option<i32>),
263 A::Bs { x, y: Some(_) } => {}
264 A::Cs(_, Some(_)) => {}
273 fn partial_fill_or_pat() {
284 A::Cs(_) | A::Bs => {}
296 A::Cs(_) | A::Bs => {}
323 A::Ds(_value) => { let x = 1; }
343 A::Ds(_value) => { let x = 1; }
354 fn fill_match_arms_empty_body() {
363 Es { x: usize, y: usize }
377 Es { x: usize, y: usize }
395 fn fill_match_arms_tuple_of_enum() {
416 $0(A::One, B::One) => {}
417 (A::One, B::Two) => {}
418 (A::Two, B::One) => {}
419 (A::Two, B::Two) => {}
427 fn fill_match_arms_tuple_of_enum_ref() {
448 $0(A::One, B::One) => {}
449 (A::One, B::Two) => {}
450 (A::Two, B::One) => {}
451 (A::Two, B::Two) => {}
459 fn fill_match_arms_tuple_of_enum_partial() {
460 check_assist_not_applicable(
470 (A::Two, B::One) => {}
478 fn fill_match_arms_tuple_of_enum_not_applicable() {
479 check_assist_not_applicable(
489 (A::Two, B::One) => {}
490 (A::One, B::One) => {}
491 (A::One, B::Two) => {}
492 (A::Two, B::Two) => {}
500 fn fill_match_arms_single_element_tuple_of_enum() {
501 // For now we don't hande the case of a single element tuple, but
502 // we could handle this in the future if `make::tuple_pat` allowed
503 // creating a tuple with a single pattern.
504 check_assist_not_applicable(
519 fn test_fill_match_arm_refs() {
545 Es { x: usize, y: usize }
555 Es { x: usize, y: usize }
560 $0A::Es { x, y } => {}
568 fn fill_match_arms_target() {
583 fn fill_match_arms_trivial_arm() {
609 fn fill_match_arms_qualifies_path() {
613 mod foo { pub enum E { X, Y } }
623 mod foo { pub enum E { X, Y } }
637 fn fill_match_arms_preserves_comments() {
646 // This is where the rest should be
656 // This is where the rest should be
665 fn fill_match_arms_preserves_comments_empty() {
690 fn fill_match_arms_placeholder() {
715 mark::check!(option_order);
717 fn foo(opt: Option<i32>) {
722 &format!("//- main.rs crate:main deps:core\n{}{}", before, FamousDefs::FIXTURE);
728 fn foo(opt: Option<i32>) {