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 first_node_text = |pat: &Pat| pat.syntax().first_child().map(|node| node.text());
141 let pat_head = match pat {
142 Pat::BindPat(bind_pat) => {
143 if let Some(p) = bind_pat.pat() {
149 pat => first_node_text(pat),
152 let var_head = first_node_text(var);
157 fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
158 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
159 Some(Adt::Enum(e)) => Some(e),
164 fn resolve_tuple_of_enum_def(
165 sema: &Semantics<RootDatabase>,
167 ) -> Option<Vec<hir::Enum>> {
168 sema.type_of_expr(&expr)?
169 .tuple_fields(sema.db)
172 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
173 Some(Adt::Enum(e)) => Some(e),
174 // For now we only handle expansion for a tuple of enums. Here
175 // we map non-enum items to None and rely on `collect` to
176 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
183 fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::EnumVariant) -> Option<ast::Pat> {
184 let path = crate::ast_transform::path_to_ast(module.find_use_path(db, ModuleDef::from(var))?);
186 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
187 let pat: ast::Pat = match var.source(db).value.kind() {
188 ast::StructKind::Tuple(field_list) => {
190 iter::repeat(make::placeholder_pat().into()).take(field_list.fields().count());
191 make::tuple_struct_pat(path, pats).into()
193 ast::StructKind::Record(field_list) => {
194 let pats = field_list.fields().map(|f| make::bind_pat(f.name().unwrap()).into());
195 make::record_pat(path, pats).into()
197 ast::StructKind::Unit => make::path_pat(path),
205 use test_utils::mark;
208 tests::{check_assist, check_assist_not_applicable, check_assist_target},
212 use super::fill_match_arms;
215 fn all_match_arms_provided() {
216 check_assist_not_applicable(
221 Bs{x:i32, y:Option<i32>},
222 Cs(i32, Option<i32>),
227 A::Bs{x,y:Some(_)} => {}
228 A::Cs(_, Some(_)) => {}
236 fn tuple_of_non_enum() {
237 // for now this case is not handled, although it potentially could be
239 check_assist_not_applicable(
243 match (0, false)<|> {
251 fn partial_fill_record_tuple() {
257 Bs { x: i32, y: Option<i32> },
258 Cs(i32, Option<i32>),
262 A::Bs { x, y: Some(_) } => {}
263 A::Cs(_, Some(_)) => {}
270 Bs { x: i32, y: Option<i32> },
271 Cs(i32, Option<i32>),
275 A::Bs { x, y: Some(_) } => {}
276 A::Cs(_, Some(_)) => {}
285 fn partial_fill_or_pat() {
296 A::Cs(_) | A::Bs => {}
308 A::Cs(_) | A::Bs => {}
335 A::Ds(_value) => { let x = 1; }
355 A::Ds(_value) => { let x = 1; }
366 fn partial_fill_bind_pat() {
400 fn fill_match_arms_empty_body() {
409 Es { x: usize, y: usize }
423 Es { x: usize, y: usize }
441 fn fill_match_arms_tuple_of_enum() {
462 $0(A::One, B::One) => {}
463 (A::One, B::Two) => {}
464 (A::Two, B::One) => {}
465 (A::Two, B::Two) => {}
473 fn fill_match_arms_tuple_of_enum_ref() {
494 $0(A::One, B::One) => {}
495 (A::One, B::Two) => {}
496 (A::Two, B::One) => {}
497 (A::Two, B::Two) => {}
505 fn fill_match_arms_tuple_of_enum_partial() {
506 check_assist_not_applicable(
516 (A::Two, B::One) => {}
524 fn fill_match_arms_tuple_of_enum_not_applicable() {
525 check_assist_not_applicable(
535 (A::Two, B::One) => {}
536 (A::One, B::One) => {}
537 (A::One, B::Two) => {}
538 (A::Two, B::Two) => {}
546 fn fill_match_arms_single_element_tuple_of_enum() {
547 // For now we don't hande the case of a single element tuple, but
548 // we could handle this in the future if `make::tuple_pat` allowed
549 // creating a tuple with a single pattern.
550 check_assist_not_applicable(
565 fn test_fill_match_arm_refs() {
591 Es { x: usize, y: usize }
601 Es { x: usize, y: usize }
606 $0A::Es { x, y } => {}
614 fn fill_match_arms_target() {
629 fn fill_match_arms_trivial_arm() {
655 fn fill_match_arms_qualifies_path() {
659 mod foo { pub enum E { X, Y } }
669 mod foo { pub enum E { X, Y } }
683 fn fill_match_arms_preserves_comments() {
692 // This is where the rest should be
702 // This is where the rest should be
711 fn fill_match_arms_preserves_comments_empty() {
736 fn fill_match_arms_placeholder() {
761 mark::check!(option_order);
763 fn foo(opt: Option<i32>) {
768 &format!("//- /main.rs crate:main deps:core\n{}{}", before, FamousDefs::FIXTURE);
774 fn foo(opt: Option<i32>) {