aboutsummaryrefslogtreecommitdiff
path: root/crates/assists/src/handlers/generate_enum_match_method.rs
diff options
context:
space:
mode:
authorYoshua Wuyts <[email protected]>2021-02-05 13:36:07 +0000
committerYoshua Wuyts <[email protected]>2021-02-05 13:36:07 +0000
commitdfd751303ec6336a4a78776eb8030790b7b0b000 (patch)
treebdacccec9a3df5694b2efaa76bc993af5761c50c /crates/assists/src/handlers/generate_enum_match_method.rs
parent13d663dd16430cec18d7eccd214c3d4891b1a9a1 (diff)
Move `find_struct_impl` to assist utils
Diffstat (limited to 'crates/assists/src/handlers/generate_enum_match_method.rs')
-rw-r--r--crates/assists/src/handlers/generate_enum_match_method.rs100
1 files changed, 10 insertions, 90 deletions
diff --git a/crates/assists/src/handlers/generate_enum_match_method.rs b/crates/assists/src/handlers/generate_enum_match_method.rs
index 079ed27bd..270b438b7 100644
--- a/crates/assists/src/handlers/generate_enum_match_method.rs
+++ b/crates/assists/src/handlers/generate_enum_match_method.rs
@@ -1,10 +1,9 @@
1use hir::Adt; 1use stdx::{format_to, to_lower_snake_case};
2use stdx::format_to;
3use syntax::ast::{self, AstNode, NameOwner}; 2use syntax::ast::{self, AstNode, NameOwner};
4use syntax::{ast::VisibilityOwner, T}; 3use syntax::{ast::VisibilityOwner, T};
5use test_utils::mark; 4use test_utils::mark;
6 5
7use crate::{AssistContext, AssistId, AssistKind, Assists}; 6use crate::{utils::find_struct_impl, AssistContext, AssistId, AssistKind, Assists};
8 7
9// Assist: generate_enum_match_method 8// Assist: generate_enum_match_method
10// 9//
@@ -40,10 +39,14 @@ pub(crate) fn generate_enum_match_method(acc: &mut Assists, ctx: &AssistContext)
40 return None; 39 return None;
41 } 40 }
42 41
43 let fn_name = to_lower_snake_case(&format!("{}", variant_name)); 42 let fn_name = to_lower_snake_case(&variant_name.to_string());
44 43
45 // Return early if we've found an existing new fn 44 // 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())?; 45 let impl_def = find_struct_impl(
46 &ctx,
47 &ast::AdtDef::Enum(parent_enum.clone()),
48 format!("is_{}", fn_name).as_str(),
49 )?;
47 50
48 let target = variant.syntax().text_range(); 51 let target = variant.syntax().text_range();
49 acc.add( 52 acc.add(
@@ -95,94 +98,14 @@ pub(crate) fn generate_enum_match_method(acc: &mut Assists, ctx: &AssistContext)
95// parameters 98// parameters
96fn generate_impl_text(strukt: &ast::Enum, code: &str) -> String { 99fn generate_impl_text(strukt: &ast::Enum, code: &str) -> String {
97 let mut buf = String::with_capacity(code.len()); 100 let mut buf = String::with_capacity(code.len());
98 buf.push_str("\n\nimpl"); 101 buf.push_str("\n\nimpl ");
99 buf.push_str(" ");
100 buf.push_str(strukt.name().unwrap().text()); 102 buf.push_str(strukt.name().unwrap().text());
101 format_to!(buf, " {{\n{}\n}}", code); 103 format_to!(buf, " {{\n{}\n}}", code);
102 buf 104 buf
103} 105}
104 106
105fn to_lower_snake_case(s: &str) -> String {
106 let mut buf = String::with_capacity(s.len());
107 let mut prev = false;
108 for c in s.chars() {
109 if c.is_ascii_uppercase() && prev {
110 buf.push('_')
111 }
112 prev = true;
113
114 buf.push(c.to_ascii_lowercase());
115 }
116 buf
117}
118
119// Uses a syntax-driven approach to find any impl blocks for the struct that
120// exist within the module/file
121//
122// Returns `None` if we've found an existing `new` fn
123//
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)
126fn find_struct_impl(
127 ctx: &AssistContext,
128 strukt: &ast::Enum,
129 name: &str,
130) -> Option<Option<ast::Impl>> {
131 let db = ctx.db();
132 let module = strukt.syntax().ancestors().find(|node| {
133 ast::Module::can_cast(node.kind()) || ast::SourceFile::can_cast(node.kind())
134 })?;
135
136 let struct_def = ctx.sema.to_def(strukt)?;
137
138 let block = module.descendants().filter_map(ast::Impl::cast).find_map(|impl_blk| {
139 let blk = ctx.sema.to_def(&impl_blk)?;
140
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),
146 None => false,
147 };
148 let not_trait_impl = blk.target_trait(db).is_none();
149
150 if !(same_ty && not_trait_impl) {
151 None
152 } else {
153 Some(impl_blk)
154 }
155 });
156
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);
160 return None;
161 }
162 }
163
164 Some(block)
165}
166
167fn 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) {
173 return true;
174 }
175 }
176 }
177 }
178 }
179
180 false
181}
182
183#[cfg(test)] 107#[cfg(test)]
184mod tests { 108mod tests {
185 use ide_db::helpers::FamousDefs;
186 use test_utils::mark; 109 use test_utils::mark;
187 110
188 use crate::tests::{check_assist, check_assist_not_applicable}; 111 use crate::tests::{check_assist, check_assist_not_applicable};
@@ -190,9 +113,7 @@ mod tests {
190 use super::*; 113 use super::*;
191 114
192 fn check_not_applicable(ra_fixture: &str) { 115 fn check_not_applicable(ra_fixture: &str) {
193 let fixture = 116 check_assist_not_applicable(generate_enum_match_method, ra_fixture)
194 format!("//- /main.rs crate:main deps:core\n{}\n{}", ra_fixture, FamousDefs::FIXTURE);
195 check_assist_not_applicable(generate_enum_match_method, &fixture)
196 } 117 }
197 118
198 #[test] 119 #[test]
@@ -221,7 +142,6 @@ impl Variant {
221 142
222 #[test] 143 #[test]
223 fn test_generate_enum_match_already_implemented() { 144 fn test_generate_enum_match_already_implemented() {
224 mark::check!(test_gen_enum_match_impl_already_exists);
225 check_not_applicable( 145 check_not_applicable(
226 r#" 146 r#"
227enum Variant { 147enum Variant {