3 use syntax::ast::{self, AstNode, NameOwner};
4 use syntax::{ast::VisibilityOwner, T};
7 use crate::{AssistContext, AssistId, AssistKind, Assists};
9 // Assist: generate_enum_match_method
11 // Generate an `is_` method for an enum variant.
29 // fn is_minor(&self) -> bool {
30 // matches!(self, Self::Minor)
34 pub(crate) fn generate_enum_match_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
35 let variant = ctx.find_node_at_offset::<ast::Variant>()?;
36 let variant_name = variant.name()?;
37 let parent_enum = variant.parent_enum();
38 if !matches!(variant.kind(), ast::StructKind::Unit) {
39 mark::hit!(test_gen_enum_match_on_non_unit_variant_not_implemented);
43 let fn_name = to_lower_snake_case(&format!("{}", variant_name));
45 // Return early if we've found an existing new fn
46 let impl_def = find_struct_impl(&ctx, &parent_enum, format!("is_{}", fn_name).as_str())?;
48 let target = variant.syntax().text_range();
50 AssistId("generate_enum_match_method", AssistKind::Generate),
51 "Generate an `is_` method for an enum variant",
54 let mut buf = String::with_capacity(512);
56 if impl_def.is_some() {
60 let vis = parent_enum.visibility().map_or(String::new(), |v| format!("{} ", v));
64 " {}fn is_{}(&self) -> bool {{
65 matches!(self, Self::{})
72 let start_offset = impl_def
73 .and_then(|impl_def| {
77 .descendants_with_tokens()
78 .find(|t| t.kind() == T!['{'])?
85 buf = generate_impl_text(&parent_enum, &buf);
86 parent_enum.syntax().text_range().end()
89 builder.insert(start_offset, buf);
94 // Generates the surrounding `impl Type { <code> }` including type and lifetime
96 fn generate_impl_text(strukt: &ast::Enum, code: &str) -> String {
97 let mut buf = String::with_capacity(code.len());
98 buf.push_str("\n\nimpl");
100 buf.push_str(strukt.name().unwrap().text());
101 format_to!(buf, " {{\n{}\n}}", code);
105 fn to_lower_snake_case(s: &str) -> String {
106 let mut buf = String::with_capacity(s.len());
107 let mut prev = false;
109 if c.is_ascii_uppercase() && prev {
114 buf.push(c.to_ascii_lowercase());
119 // Uses a syntax-driven approach to find any impl blocks for the struct that
120 // exist within the module/file
122 // Returns `None` if we've found an existing `new` fn
124 // FIXME: change the new fn checking to a more semantic approach when that's more
125 // viable (e.g. we process proc macros, etc)
130 ) -> Option<Option<ast::Impl>> {
132 let module = strukt.syntax().ancestors().find(|node| {
133 ast::Module::can_cast(node.kind()) || ast::SourceFile::can_cast(node.kind())
136 let struct_def = ctx.sema.to_def(strukt)?;
138 let block = module.descendants().filter_map(ast::Impl::cast).find_map(|impl_blk| {
139 let blk = ctx.sema.to_def(&impl_blk)?;
141 // FIXME: handle e.g. `struct S<T>; impl<U> S<U> {}`
142 // (we currently use the wrong type parameter)
143 // also we wouldn't want to use e.g. `impl S<u32>`
144 let same_ty = match blk.target_ty(db).as_adt() {
145 Some(def) => def == Adt::Enum(struct_def),
148 let not_trait_impl = blk.target_trait(db).is_none();
150 if !(same_ty && not_trait_impl) {
157 if let Some(ref impl_blk) = block {
158 if has_fn(impl_blk, name) {
159 mark::hit!(test_gen_enum_match_impl_already_exists);
167 fn has_fn(imp: &ast::Impl, rhs_name: &str) -> bool {
168 if let Some(il) = imp.assoc_item_list() {
169 for item in il.assoc_items() {
170 if let ast::AssocItem::Fn(f) = item {
171 if let Some(name) = f.name() {
172 if name.text().eq_ignore_ascii_case(rhs_name) {
185 use ide_db::helpers::FamousDefs;
186 use test_utils::mark;
188 use crate::tests::{check_assist, check_assist_not_applicable};
192 fn check_not_applicable(ra_fixture: &str) {
194 format!("//- /main.rs crate:main deps:core\n{}\n{}", ra_fixture, FamousDefs::FIXTURE);
195 check_assist_not_applicable(generate_enum_match_method, &fixture)
199 fn test_generate_enum_match_from_variant() {
201 generate_enum_match_method,
215 fn is_minor(&self) -> bool {
216 matches!(self, Self::Minor)
223 fn test_generate_enum_match_already_implemented() {
224 mark::check!(test_gen_enum_match_impl_already_exists);
225 check_not_applicable(
234 fn is_minor(&self) -> bool {
235 matches!(self, Self::Minor)
242 fn test_add_from_impl_no_element() {
243 mark::check!(test_gen_enum_match_on_non_unit_variant_not_implemented);
244 check_not_applicable(
255 fn test_generate_enum_match_from_variant_with_one_variant() {
257 generate_enum_match_method,
258 r#"enum Variant { Undefi$0ned }"#,
260 enum Variant { Undefined }
263 fn is_undefined(&self) -> bool {
264 matches!(self, Self::Undefined)
271 fn test_generate_enum_match_from_variant_with_visibility_marker() {
273 generate_enum_match_method,
275 pub(crate) enum Variant {
280 r#"pub(crate) enum Variant {
287 pub(crate) fn is_minor(&self) -> bool {
288 matches!(self, Self::Minor)