diff options
Diffstat (limited to 'crates/assists/src/handlers/extract_struct_from_enum_variant.rs')
-rw-r--r-- | crates/assists/src/handlers/extract_struct_from_enum_variant.rs | 317 |
1 files changed, 317 insertions, 0 deletions
diff --git a/crates/assists/src/handlers/extract_struct_from_enum_variant.rs b/crates/assists/src/handlers/extract_struct_from_enum_variant.rs new file mode 100644 index 000000000..4bcdae7ba --- /dev/null +++ b/crates/assists/src/handlers/extract_struct_from_enum_variant.rs | |||
@@ -0,0 +1,317 @@ | |||
1 | use base_db::FileId; | ||
2 | use hir::{EnumVariant, Module, ModuleDef, Name}; | ||
3 | use ide_db::{defs::Definition, search::Reference, RootDatabase}; | ||
4 | use rustc_hash::FxHashSet; | ||
5 | use syntax::{ | ||
6 | algo::find_node_at_offset, | ||
7 | ast::{self, edit::IndentLevel, ArgListOwner, AstNode, NameOwner, VisibilityOwner}, | ||
8 | SourceFile, TextRange, TextSize, | ||
9 | }; | ||
10 | |||
11 | use crate::{ | ||
12 | assist_context::AssistBuilder, utils::insert_use_statement, AssistContext, AssistId, | ||
13 | AssistKind, Assists, | ||
14 | }; | ||
15 | |||
16 | // Assist: extract_struct_from_enum_variant | ||
17 | // | ||
18 | // Extracts a struct from enum variant. | ||
19 | // | ||
20 | // ``` | ||
21 | // enum A { <|>One(u32, u32) } | ||
22 | // ``` | ||
23 | // -> | ||
24 | // ``` | ||
25 | // struct One(pub u32, pub u32); | ||
26 | // | ||
27 | // enum A { One(One) } | ||
28 | // ``` | ||
29 | pub(crate) fn extract_struct_from_enum_variant( | ||
30 | acc: &mut Assists, | ||
31 | ctx: &AssistContext, | ||
32 | ) -> Option<()> { | ||
33 | let variant = ctx.find_node_at_offset::<ast::Variant>()?; | ||
34 | let field_list = match variant.kind() { | ||
35 | ast::StructKind::Tuple(field_list) => field_list, | ||
36 | _ => return None, | ||
37 | }; | ||
38 | let variant_name = variant.name()?.to_string(); | ||
39 | let variant_hir = ctx.sema.to_def(&variant)?; | ||
40 | if existing_struct_def(ctx.db(), &variant_name, &variant_hir) { | ||
41 | return None; | ||
42 | } | ||
43 | let enum_ast = variant.parent_enum(); | ||
44 | let visibility = enum_ast.visibility(); | ||
45 | let enum_hir = ctx.sema.to_def(&enum_ast)?; | ||
46 | let variant_hir_name = variant_hir.name(ctx.db()); | ||
47 | let enum_module_def = ModuleDef::from(enum_hir); | ||
48 | let current_module = enum_hir.module(ctx.db()); | ||
49 | let target = variant.syntax().text_range(); | ||
50 | acc.add( | ||
51 | AssistId("extract_struct_from_enum_variant", AssistKind::RefactorRewrite), | ||
52 | "Extract struct from enum variant", | ||
53 | target, | ||
54 | |builder| { | ||
55 | let definition = Definition::ModuleDef(ModuleDef::EnumVariant(variant_hir)); | ||
56 | let res = definition.find_usages(&ctx.sema, None); | ||
57 | let start_offset = variant.parent_enum().syntax().text_range().start(); | ||
58 | let mut visited_modules_set = FxHashSet::default(); | ||
59 | visited_modules_set.insert(current_module); | ||
60 | for reference in res { | ||
61 | let source_file = ctx.sema.parse(reference.file_range.file_id); | ||
62 | update_reference( | ||
63 | ctx, | ||
64 | builder, | ||
65 | reference, | ||
66 | &source_file, | ||
67 | &enum_module_def, | ||
68 | &variant_hir_name, | ||
69 | &mut visited_modules_set, | ||
70 | ); | ||
71 | } | ||
72 | extract_struct_def( | ||
73 | builder, | ||
74 | &enum_ast, | ||
75 | &variant_name, | ||
76 | &field_list.to_string(), | ||
77 | start_offset, | ||
78 | ctx.frange.file_id, | ||
79 | &visibility, | ||
80 | ); | ||
81 | let list_range = field_list.syntax().text_range(); | ||
82 | update_variant(builder, &variant_name, ctx.frange.file_id, list_range); | ||
83 | }, | ||
84 | ) | ||
85 | } | ||
86 | |||
87 | fn existing_struct_def(db: &RootDatabase, variant_name: &str, variant: &EnumVariant) -> bool { | ||
88 | variant | ||
89 | .parent_enum(db) | ||
90 | .module(db) | ||
91 | .scope(db, None) | ||
92 | .into_iter() | ||
93 | .any(|(name, _)| name.to_string() == variant_name.to_string()) | ||
94 | } | ||
95 | |||
96 | fn insert_import( | ||
97 | ctx: &AssistContext, | ||
98 | builder: &mut AssistBuilder, | ||
99 | path: &ast::PathExpr, | ||
100 | module: &Module, | ||
101 | enum_module_def: &ModuleDef, | ||
102 | variant_hir_name: &Name, | ||
103 | ) -> Option<()> { | ||
104 | let db = ctx.db(); | ||
105 | let mod_path = module.find_use_path(db, enum_module_def.clone()); | ||
106 | if let Some(mut mod_path) = mod_path { | ||
107 | mod_path.segments.pop(); | ||
108 | mod_path.segments.push(variant_hir_name.clone()); | ||
109 | insert_use_statement(path.syntax(), &mod_path, ctx, builder.text_edit_builder()); | ||
110 | } | ||
111 | Some(()) | ||
112 | } | ||
113 | |||
114 | // FIXME: this should use strongly-typed `make`, rather than string manipulation. | ||
115 | fn extract_struct_def( | ||
116 | builder: &mut AssistBuilder, | ||
117 | enum_: &ast::Enum, | ||
118 | variant_name: &str, | ||
119 | variant_list: &str, | ||
120 | start_offset: TextSize, | ||
121 | file_id: FileId, | ||
122 | visibility: &Option<ast::Visibility>, | ||
123 | ) -> Option<()> { | ||
124 | let visibility_string = if let Some(visibility) = visibility { | ||
125 | format!("{} ", visibility.to_string()) | ||
126 | } else { | ||
127 | "".to_string() | ||
128 | }; | ||
129 | let indent = IndentLevel::from_node(enum_.syntax()); | ||
130 | let struct_def = format!( | ||
131 | r#"{}struct {}{}; | ||
132 | |||
133 | {}"#, | ||
134 | visibility_string, | ||
135 | variant_name, | ||
136 | list_with_visibility(variant_list), | ||
137 | indent | ||
138 | ); | ||
139 | builder.edit_file(file_id); | ||
140 | builder.insert(start_offset, struct_def); | ||
141 | Some(()) | ||
142 | } | ||
143 | |||
144 | fn update_variant( | ||
145 | builder: &mut AssistBuilder, | ||
146 | variant_name: &str, | ||
147 | file_id: FileId, | ||
148 | list_range: TextRange, | ||
149 | ) -> Option<()> { | ||
150 | let inside_variant_range = TextRange::new( | ||
151 | list_range.start().checked_add(TextSize::from(1))?, | ||
152 | list_range.end().checked_sub(TextSize::from(1))?, | ||
153 | ); | ||
154 | builder.edit_file(file_id); | ||
155 | builder.replace(inside_variant_range, variant_name); | ||
156 | Some(()) | ||
157 | } | ||
158 | |||
159 | fn update_reference( | ||
160 | ctx: &AssistContext, | ||
161 | builder: &mut AssistBuilder, | ||
162 | reference: Reference, | ||
163 | source_file: &SourceFile, | ||
164 | enum_module_def: &ModuleDef, | ||
165 | variant_hir_name: &Name, | ||
166 | visited_modules_set: &mut FxHashSet<Module>, | ||
167 | ) -> Option<()> { | ||
168 | let path_expr: ast::PathExpr = find_node_at_offset::<ast::PathExpr>( | ||
169 | source_file.syntax(), | ||
170 | reference.file_range.range.start(), | ||
171 | )?; | ||
172 | let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?; | ||
173 | let list = call.arg_list()?; | ||
174 | let segment = path_expr.path()?.segment()?; | ||
175 | let module = ctx.sema.scope(&path_expr.syntax()).module()?; | ||
176 | let list_range = list.syntax().text_range(); | ||
177 | let inside_list_range = TextRange::new( | ||
178 | list_range.start().checked_add(TextSize::from(1))?, | ||
179 | list_range.end().checked_sub(TextSize::from(1))?, | ||
180 | ); | ||
181 | builder.edit_file(reference.file_range.file_id); | ||
182 | if !visited_modules_set.contains(&module) { | ||
183 | if insert_import(ctx, builder, &path_expr, &module, enum_module_def, variant_hir_name) | ||
184 | .is_some() | ||
185 | { | ||
186 | visited_modules_set.insert(module); | ||
187 | } | ||
188 | } | ||
189 | builder.replace(inside_list_range, format!("{}{}", segment, list)); | ||
190 | Some(()) | ||
191 | } | ||
192 | |||
193 | fn list_with_visibility(list: &str) -> String { | ||
194 | list.split(',') | ||
195 | .map(|part| { | ||
196 | let index = if part.chars().next().unwrap() == '(' { 1usize } else { 0 }; | ||
197 | let mut mod_part = part.trim().to_string(); | ||
198 | mod_part.insert_str(index, "pub "); | ||
199 | mod_part | ||
200 | }) | ||
201 | .collect::<Vec<String>>() | ||
202 | .join(", ") | ||
203 | } | ||
204 | |||
205 | #[cfg(test)] | ||
206 | mod tests { | ||
207 | |||
208 | use crate::{ | ||
209 | tests::{check_assist, check_assist_not_applicable}, | ||
210 | utils::FamousDefs, | ||
211 | }; | ||
212 | |||
213 | use super::*; | ||
214 | |||
215 | #[test] | ||
216 | fn test_extract_struct_several_fields() { | ||
217 | check_assist( | ||
218 | extract_struct_from_enum_variant, | ||
219 | "enum A { <|>One(u32, u32) }", | ||
220 | r#"struct One(pub u32, pub u32); | ||
221 | |||
222 | enum A { One(One) }"#, | ||
223 | ); | ||
224 | } | ||
225 | |||
226 | #[test] | ||
227 | fn test_extract_struct_one_field() { | ||
228 | check_assist( | ||
229 | extract_struct_from_enum_variant, | ||
230 | "enum A { <|>One(u32) }", | ||
231 | r#"struct One(pub u32); | ||
232 | |||
233 | enum A { One(One) }"#, | ||
234 | ); | ||
235 | } | ||
236 | |||
237 | #[test] | ||
238 | fn test_extract_struct_pub_visibility() { | ||
239 | check_assist( | ||
240 | extract_struct_from_enum_variant, | ||
241 | "pub enum A { <|>One(u32, u32) }", | ||
242 | r#"pub struct One(pub u32, pub u32); | ||
243 | |||
244 | pub enum A { One(One) }"#, | ||
245 | ); | ||
246 | } | ||
247 | |||
248 | #[test] | ||
249 | fn test_extract_struct_with_complex_imports() { | ||
250 | check_assist( | ||
251 | extract_struct_from_enum_variant, | ||
252 | r#"mod my_mod { | ||
253 | fn another_fn() { | ||
254 | let m = my_other_mod::MyEnum::MyField(1, 1); | ||
255 | } | ||
256 | |||
257 | pub mod my_other_mod { | ||
258 | fn another_fn() { | ||
259 | let m = MyEnum::MyField(1, 1); | ||
260 | } | ||
261 | |||
262 | pub enum MyEnum { | ||
263 | <|>MyField(u8, u8), | ||
264 | } | ||
265 | } | ||
266 | } | ||
267 | |||
268 | fn another_fn() { | ||
269 | let m = my_mod::my_other_mod::MyEnum::MyField(1, 1); | ||
270 | }"#, | ||
271 | r#"use my_mod::my_other_mod::MyField; | ||
272 | |||
273 | mod my_mod { | ||
274 | use my_other_mod::MyField; | ||
275 | |||
276 | fn another_fn() { | ||
277 | let m = my_other_mod::MyEnum::MyField(MyField(1, 1)); | ||
278 | } | ||
279 | |||
280 | pub mod my_other_mod { | ||
281 | fn another_fn() { | ||
282 | let m = MyEnum::MyField(MyField(1, 1)); | ||
283 | } | ||
284 | |||
285 | pub struct MyField(pub u8, pub u8); | ||
286 | |||
287 | pub enum MyEnum { | ||
288 | MyField(MyField), | ||
289 | } | ||
290 | } | ||
291 | } | ||
292 | |||
293 | fn another_fn() { | ||
294 | let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1)); | ||
295 | }"#, | ||
296 | ); | ||
297 | } | ||
298 | |||
299 | fn check_not_applicable(ra_fixture: &str) { | ||
300 | let fixture = | ||
301 | format!("//- /main.rs crate:main deps:core\n{}\n{}", ra_fixture, FamousDefs::FIXTURE); | ||
302 | check_assist_not_applicable(extract_struct_from_enum_variant, &fixture) | ||
303 | } | ||
304 | |||
305 | #[test] | ||
306 | fn test_extract_enum_not_applicable_for_element_with_no_fields() { | ||
307 | check_not_applicable("enum A { <|>One }"); | ||
308 | } | ||
309 | |||
310 | #[test] | ||
311 | fn test_extract_enum_not_applicable_if_struct_exists() { | ||
312 | check_not_applicable( | ||
313 | r#"struct One; | ||
314 | enum A { <|>One(u8) }"#, | ||
315 | ); | ||
316 | } | ||
317 | } | ||