]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_new.rs
Rollup merge of #101420 - kraktus:doc_hir_local, r=cjgillot
[rust.git] / src / tools / rust-analyzer / crates / ide-assists / src / handlers / generate_new.rs
1 use ide_db::{
2     imports::import_assets::item_for_path_search, use_trivial_contructor::use_trivial_constructor,
3 };
4 use itertools::Itertools;
5 use stdx::format_to;
6 use syntax::ast::{self, AstNode, HasName, HasVisibility, StructKind};
7
8 use crate::{
9     utils::{find_impl_block_start, find_struct_impl, generate_impl_text},
10     AssistContext, AssistId, AssistKind, Assists,
11 };
12
13 // Assist: generate_new
14 //
15 // Adds a `fn new` for a type.
16 //
17 // ```
18 // struct Ctx<T: Clone> {
19 //      data: T,$0
20 // }
21 // ```
22 // ->
23 // ```
24 // struct Ctx<T: Clone> {
25 //      data: T,
26 // }
27 //
28 // impl<T: Clone> Ctx<T> {
29 //     fn $0new(data: T) -> Self { Self { data } }
30 // }
31 // ```
32 pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
33     let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
34
35     // We want to only apply this to non-union structs with named fields
36     let field_list = match strukt.kind() {
37         StructKind::Record(named) => named,
38         _ => return None,
39     };
40
41     // Return early if we've found an existing new fn
42     let impl_def = find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), "new")?;
43
44     let current_module = ctx.sema.scope(strukt.syntax())?.module();
45
46     let target = strukt.syntax().text_range();
47     acc.add(AssistId("generate_new", AssistKind::Generate), "Generate `new`", target, |builder| {
48         let mut buf = String::with_capacity(512);
49
50         if impl_def.is_some() {
51             buf.push('\n');
52         }
53
54         let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
55
56         let trivial_constructors = field_list
57             .fields()
58             .map(|f| {
59                 let ty = ctx.sema.resolve_type(&f.ty()?)?;
60
61                 let item_in_ns = hir::ItemInNs::from(hir::ModuleDef::from(ty.as_adt()?));
62
63                 let type_path = current_module
64                     .find_use_path(ctx.sema.db, item_for_path_search(ctx.sema.db, item_in_ns)?)?;
65
66                 let expr = use_trivial_constructor(
67                     &ctx.sema.db,
68                     ide_db::helpers::mod_path_to_ast(&type_path),
69                     &ty,
70                 )?;
71
72                 Some(format!("{}: {}", f.name()?.syntax(), expr))
73             })
74             .collect::<Vec<_>>();
75
76         let params = field_list
77             .fields()
78             .enumerate()
79             .filter_map(|(i, f)| {
80                 if trivial_constructors[i].is_none() {
81                     Some(format!("{}: {}", f.name()?.syntax(), f.ty()?.syntax()))
82                 } else {
83                     None
84                 }
85             })
86             .format(", ");
87
88         let fields = field_list
89             .fields()
90             .enumerate()
91             .filter_map(|(i, f)| {
92                 let contructor = trivial_constructors[i].clone();
93                 if contructor.is_some() {
94                     contructor
95                 } else {
96                     Some(f.name()?.to_string())
97                 }
98             })
99             .format(", ");
100
101         format_to!(buf, "    {}fn new({}) -> Self {{ Self {{ {} }} }}", vis, params, fields);
102
103         let start_offset = impl_def
104             .and_then(|impl_def| find_impl_block_start(impl_def, &mut buf))
105             .unwrap_or_else(|| {
106                 buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
107                 strukt.syntax().text_range().end()
108             });
109
110         match ctx.config.snippet_cap {
111             None => builder.insert(start_offset, buf),
112             Some(cap) => {
113                 buf = buf.replace("fn new", "fn $0new");
114                 builder.insert_snippet(cap, start_offset, buf);
115             }
116         }
117     })
118 }
119
120 #[cfg(test)]
121 mod tests {
122     use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
123
124     use super::*;
125
126     #[test]
127     fn test_generate_new_with_zst_fields() {
128         check_assist(
129             generate_new,
130             r#"
131 struct Empty;
132
133 struct Foo { empty: Empty $0}
134 "#,
135             r#"
136 struct Empty;
137
138 struct Foo { empty: Empty }
139
140 impl Foo {
141     fn $0new() -> Self { Self { empty: Empty } }
142 }
143 "#,
144         );
145         check_assist(
146             generate_new,
147             r#"
148 struct Empty;
149
150 struct Foo { baz: String, empty: Empty $0}
151 "#,
152             r#"
153 struct Empty;
154
155 struct Foo { baz: String, empty: Empty }
156
157 impl Foo {
158     fn $0new(baz: String) -> Self { Self { baz, empty: Empty } }
159 }
160 "#,
161         );
162         check_assist(
163             generate_new,
164             r#"
165 enum Empty { Bar }
166
167 struct Foo { empty: Empty $0}
168 "#,
169             r#"
170 enum Empty { Bar }
171
172 struct Foo { empty: Empty }
173
174 impl Foo {
175     fn $0new() -> Self { Self { empty: Empty::Bar } }
176 }
177 "#,
178         );
179
180         // make sure the assist only works on unit variants
181         check_assist(
182             generate_new,
183             r#"
184 struct Empty {}
185
186 struct Foo { empty: Empty $0}
187 "#,
188             r#"
189 struct Empty {}
190
191 struct Foo { empty: Empty }
192
193 impl Foo {
194     fn $0new(empty: Empty) -> Self { Self { empty } }
195 }
196 "#,
197         );
198         check_assist(
199             generate_new,
200             r#"
201 enum Empty { Bar {} }
202
203 struct Foo { empty: Empty $0}
204 "#,
205             r#"
206 enum Empty { Bar {} }
207
208 struct Foo { empty: Empty }
209
210 impl Foo {
211     fn $0new(empty: Empty) -> Self { Self { empty } }
212 }
213 "#,
214         );
215     }
216
217     #[test]
218     fn test_generate_new() {
219         check_assist(
220             generate_new,
221             r#"
222 struct Foo {$0}
223 "#,
224             r#"
225 struct Foo {}
226
227 impl Foo {
228     fn $0new() -> Self { Self {  } }
229 }
230 "#,
231         );
232         check_assist(
233             generate_new,
234             r#"
235 struct Foo<T: Clone> {$0}
236 "#,
237             r#"
238 struct Foo<T: Clone> {}
239
240 impl<T: Clone> Foo<T> {
241     fn $0new() -> Self { Self {  } }
242 }
243 "#,
244         );
245         check_assist(
246             generate_new,
247             r#"
248 struct Foo<'a, T: Foo<'a>> {$0}
249 "#,
250             r#"
251 struct Foo<'a, T: Foo<'a>> {}
252
253 impl<'a, T: Foo<'a>> Foo<'a, T> {
254     fn $0new() -> Self { Self {  } }
255 }
256 "#,
257         );
258         check_assist(
259             generate_new,
260             r#"
261 struct Foo { baz: String $0}
262 "#,
263             r#"
264 struct Foo { baz: String }
265
266 impl Foo {
267     fn $0new(baz: String) -> Self { Self { baz } }
268 }
269 "#,
270         );
271         check_assist(
272             generate_new,
273             r#"
274 struct Foo { baz: String, qux: Vec<i32> $0}
275 "#,
276             r#"
277 struct Foo { baz: String, qux: Vec<i32> }
278
279 impl Foo {
280     fn $0new(baz: String, qux: Vec<i32>) -> Self { Self { baz, qux } }
281 }
282 "#,
283         );
284     }
285
286     #[test]
287     fn check_that_visibility_modifiers_dont_get_brought_in() {
288         check_assist(
289             generate_new,
290             r#"
291 struct Foo { pub baz: String, pub qux: Vec<i32> $0}
292 "#,
293             r#"
294 struct Foo { pub baz: String, pub qux: Vec<i32> }
295
296 impl Foo {
297     fn $0new(baz: String, qux: Vec<i32>) -> Self { Self { baz, qux } }
298 }
299 "#,
300         );
301     }
302
303     #[test]
304     fn check_it_reuses_existing_impls() {
305         check_assist(
306             generate_new,
307             r#"
308 struct Foo {$0}
309
310 impl Foo {}
311 "#,
312             r#"
313 struct Foo {}
314
315 impl Foo {
316     fn $0new() -> Self { Self {  } }
317 }
318 "#,
319         );
320         check_assist(
321             generate_new,
322             r#"
323 struct Foo {$0}
324
325 impl Foo {
326     fn qux(&self) {}
327 }
328 "#,
329             r#"
330 struct Foo {}
331
332 impl Foo {
333     fn $0new() -> Self { Self {  } }
334
335     fn qux(&self) {}
336 }
337 "#,
338         );
339
340         check_assist(
341             generate_new,
342             r#"
343 struct Foo {$0}
344
345 impl Foo {
346     fn qux(&self) {}
347     fn baz() -> i32 {
348         5
349     }
350 }
351 "#,
352             r#"
353 struct Foo {}
354
355 impl Foo {
356     fn $0new() -> Self { Self {  } }
357
358     fn qux(&self) {}
359     fn baz() -> i32 {
360         5
361     }
362 }
363 "#,
364         );
365     }
366
367     #[test]
368     fn check_visibility_of_new_fn_based_on_struct() {
369         check_assist(
370             generate_new,
371             r#"
372 pub struct Foo {$0}
373 "#,
374             r#"
375 pub struct Foo {}
376
377 impl Foo {
378     pub fn $0new() -> Self { Self {  } }
379 }
380 "#,
381         );
382         check_assist(
383             generate_new,
384             r#"
385 pub(crate) struct Foo {$0}
386 "#,
387             r#"
388 pub(crate) struct Foo {}
389
390 impl Foo {
391     pub(crate) fn $0new() -> Self { Self {  } }
392 }
393 "#,
394         );
395     }
396
397     #[test]
398     fn generate_new_not_applicable_if_fn_exists() {
399         check_assist_not_applicable(
400             generate_new,
401             r#"
402 struct Foo {$0}
403
404 impl Foo {
405     fn new() -> Self {
406         Self
407     }
408 }
409 "#,
410         );
411
412         check_assist_not_applicable(
413             generate_new,
414             r#"
415 struct Foo {$0}
416
417 impl Foo {
418     fn New() -> Self {
419         Self
420     }
421 }
422 "#,
423         );
424     }
425
426     #[test]
427     fn generate_new_target() {
428         check_assist_target(
429             generate_new,
430             r#"
431 struct SomeThingIrrelevant;
432 /// Has a lifetime parameter
433 struct Foo<'a, T: Foo<'a>> {$0}
434 struct EvenMoreIrrelevant;
435 "#,
436             "/// Has a lifetime parameter
437 struct Foo<'a, T: Foo<'a>> {}",
438         );
439     }
440
441     #[test]
442     fn test_unrelated_new() {
443         check_assist(
444             generate_new,
445             r#"
446 pub struct AstId<N: AstNode> {
447     file_id: HirFileId,
448     file_ast_id: FileAstId<N>,
449 }
450
451 impl<N: AstNode> AstId<N> {
452     pub fn new(file_id: HirFileId, file_ast_id: FileAstId<N>) -> AstId<N> {
453         AstId { file_id, file_ast_id }
454     }
455 }
456
457 pub struct Source<T> {
458     pub file_id: HirFileId,$0
459     pub ast: T,
460 }
461
462 impl<T> Source<T> {
463     pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Source<U> {
464         Source { file_id: self.file_id, ast: f(self.ast) }
465     }
466 }
467 "#,
468             r#"
469 pub struct AstId<N: AstNode> {
470     file_id: HirFileId,
471     file_ast_id: FileAstId<N>,
472 }
473
474 impl<N: AstNode> AstId<N> {
475     pub fn new(file_id: HirFileId, file_ast_id: FileAstId<N>) -> AstId<N> {
476         AstId { file_id, file_ast_id }
477     }
478 }
479
480 pub struct Source<T> {
481     pub file_id: HirFileId,
482     pub ast: T,
483 }
484
485 impl<T> Source<T> {
486     pub fn $0new(file_id: HirFileId, ast: T) -> Self { Self { file_id, ast } }
487
488     pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Source<U> {
489         Source { file_id: self.file_id, ast: f(self.ast) }
490     }
491 }
492 "#,
493         );
494     }
495 }