]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/generate_getter.rs
Merge #11481
[rust.git] / crates / ide_assists / src / handlers / generate_getter.rs
1 use ide_db::helpers::FamousDefs;
2 use stdx::{format_to, to_lower_snake_case};
3 use syntax::ast::{self, AstNode, HasName, HasVisibility};
4
5 use crate::{
6     utils::{convert_reference_type, find_impl_block_end, find_struct_impl, generate_impl_text},
7     AssistContext, AssistId, AssistKind, Assists, GroupLabel,
8 };
9
10 // Assist: generate_getter
11 //
12 // Generate a getter method.
13 //
14 // ```
15 // # //- minicore: as_ref
16 // # pub struct String;
17 // # impl AsRef<str> for String {
18 // #     fn as_ref(&self) -> &str {
19 // #         ""
20 // #     }
21 // # }
22 // #
23 // struct Person {
24 //     nam$0e: String,
25 // }
26 // ```
27 // ->
28 // ```
29 // # pub struct String;
30 // # impl AsRef<str> for String {
31 // #     fn as_ref(&self) -> &str {
32 // #         ""
33 // #     }
34 // # }
35 // #
36 // struct Person {
37 //     name: String,
38 // }
39 //
40 // impl Person {
41 //     /// Get a reference to the person's name.
42 //     fn $0name(&self) -> &str {
43 //         self.name.as_ref()
44 //     }
45 // }
46 // ```
47 pub(crate) fn generate_getter(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
48     generate_getter_impl(acc, ctx, false)
49 }
50
51 // Assist: generate_getter_mut
52 //
53 // Generate a mut getter method.
54 //
55 // ```
56 // struct Person {
57 //     nam$0e: String,
58 // }
59 // ```
60 // ->
61 // ```
62 // struct Person {
63 //     name: String,
64 // }
65 //
66 // impl Person {
67 //     /// Get a mutable reference to the person's name.
68 //     fn $0name_mut(&mut self) -> &mut String {
69 //         &mut self.name
70 //     }
71 // }
72 // ```
73 pub(crate) fn generate_getter_mut(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
74     generate_getter_impl(acc, ctx, true)
75 }
76
77 pub(crate) fn generate_getter_impl(
78     acc: &mut Assists,
79     ctx: &AssistContext,
80     mutable: bool,
81 ) -> Option<()> {
82     let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
83     let field = ctx.find_node_at_offset::<ast::RecordField>()?;
84
85     let strukt_name = strukt.name()?;
86     let field_name = field.name()?;
87     let field_ty = field.ty()?;
88
89     // Return early if we've found an existing fn
90     let mut fn_name = to_lower_snake_case(&field_name.to_string());
91     if mutable {
92         format_to!(fn_name, "_mut");
93     }
94     let impl_def = find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), fn_name.as_str())?;
95
96     let (id, label) = if mutable {
97         ("generate_getter_mut", "Generate a mut getter method")
98     } else {
99         ("generate_getter", "Generate a getter method")
100     };
101     let target = field.syntax().text_range();
102     acc.add_group(
103         &GroupLabel("Generate getter/setter".to_owned()),
104         AssistId(id, AssistKind::Generate),
105         label,
106         target,
107         |builder| {
108             let mut buf = String::with_capacity(512);
109
110             if impl_def.is_some() {
111                 buf.push('\n');
112             }
113
114             let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
115             let (ty, body, description) = if mutable {
116                 (
117                     format!("&mut {}", field_ty),
118                     format!("&mut self.{}", field_name),
119                     "a mutable reference to ",
120                 )
121             } else {
122                 let famous_defs = &FamousDefs(&ctx.sema, ctx.sema.scope(field_ty.syntax()).krate());
123                 ctx.sema
124                     .resolve_type(&field_ty)
125                     .and_then(|ty| convert_reference_type(ty, ctx.db(), famous_defs))
126                     .map(|conversion| {
127                         cov_mark::hit!(convert_reference_type);
128                         (
129                             conversion.convert_type(ctx.db()),
130                             conversion.getter(field_name.to_string()),
131                             if conversion.is_copy() { "" } else { "a reference to " },
132                         )
133                     })
134                     .unwrap_or_else(|| {
135                         (
136                             format!("&{}", field_ty),
137                             format!("&self.{}", field_name),
138                             "a reference to ",
139                         )
140                     })
141             };
142
143             format_to!(
144                 buf,
145                 "    /// Get {}the {}'s {}.
146     {}fn {}(&{}self) -> {} {{
147         {}
148     }}",
149                 description,
150                 to_lower_snake_case(&strukt_name.to_string()).replace('_', " "),
151                 fn_name.trim_end_matches("_mut").replace('_', " "),
152                 vis,
153                 fn_name,
154                 mutable.then(|| "mut ").unwrap_or_default(),
155                 ty,
156                 body,
157             );
158
159             let start_offset = impl_def
160                 .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
161                 .unwrap_or_else(|| {
162                     buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
163                     strukt.syntax().text_range().end()
164                 });
165
166             match ctx.config.snippet_cap {
167                 Some(cap) => {
168                     builder.insert_snippet(cap, start_offset, buf.replacen("fn ", "fn $0", 1))
169                 }
170                 None => builder.insert(start_offset, buf),
171             }
172         },
173     )
174 }
175
176 #[cfg(test)]
177 mod tests {
178     use crate::tests::{check_assist, check_assist_not_applicable};
179
180     use super::*;
181
182     #[test]
183     fn test_generate_getter_from_field() {
184         check_assist(
185             generate_getter,
186             r#"
187 struct Context {
188     dat$0a: Data,
189 }
190 "#,
191             r#"
192 struct Context {
193     data: Data,
194 }
195
196 impl Context {
197     /// Get a reference to the context's data.
198     fn $0data(&self) -> &Data {
199         &self.data
200     }
201 }
202 "#,
203         );
204
205         check_assist(
206             generate_getter_mut,
207             r#"
208 struct Context {
209     dat$0a: Data,
210 }
211 "#,
212             r#"
213 struct Context {
214     data: Data,
215 }
216
217 impl Context {
218     /// Get a mutable reference to the context's data.
219     fn $0data_mut(&mut self) -> &mut Data {
220         &mut self.data
221     }
222 }
223 "#,
224         );
225     }
226
227     #[test]
228     fn test_generate_getter_already_implemented() {
229         check_assist_not_applicable(
230             generate_getter,
231             r#"
232 struct Context {
233     dat$0a: Data,
234 }
235
236 impl Context {
237     fn data(&self) -> &Data {
238         &self.data
239     }
240 }
241 "#,
242         );
243
244         check_assist_not_applicable(
245             generate_getter_mut,
246             r#"
247 struct Context {
248     dat$0a: Data,
249 }
250
251 impl Context {
252     fn data_mut(&mut self) -> &mut Data {
253         &mut self.data
254     }
255 }
256 "#,
257         );
258     }
259
260     #[test]
261     fn test_generate_getter_from_field_with_visibility_marker() {
262         check_assist(
263             generate_getter,
264             r#"
265 pub(crate) struct Context {
266     dat$0a: Data,
267 }
268 "#,
269             r#"
270 pub(crate) struct Context {
271     data: Data,
272 }
273
274 impl Context {
275     /// Get a reference to the context's data.
276     pub(crate) fn $0data(&self) -> &Data {
277         &self.data
278     }
279 }
280 "#,
281         );
282     }
283
284     #[test]
285     fn test_multiple_generate_getter() {
286         check_assist(
287             generate_getter,
288             r#"
289 struct Context {
290     data: Data,
291     cou$0nt: usize,
292 }
293
294 impl Context {
295     /// Get a reference to the context's data.
296     fn data(&self) -> &Data {
297         &self.data
298     }
299 }
300 "#,
301             r#"
302 struct Context {
303     data: Data,
304     count: usize,
305 }
306
307 impl Context {
308     /// Get a reference to the context's data.
309     fn data(&self) -> &Data {
310         &self.data
311     }
312
313     /// Get a reference to the context's count.
314     fn $0count(&self) -> &usize {
315         &self.count
316     }
317 }
318 "#,
319         );
320     }
321
322     #[test]
323     fn test_not_a_special_case() {
324         cov_mark::check_count!(convert_reference_type, 0);
325         // Fake string which doesn't implement AsRef<str>
326         check_assist(
327             generate_getter,
328             r#"
329 pub struct String;
330
331 struct S { foo: $0String }
332 "#,
333             r#"
334 pub struct String;
335
336 struct S { foo: String }
337
338 impl S {
339     /// Get a reference to the s's foo.
340     fn $0foo(&self) -> &String {
341         &self.foo
342     }
343 }
344 "#,
345         );
346     }
347
348     #[test]
349     fn test_convert_reference_type() {
350         cov_mark::check_count!(convert_reference_type, 6);
351
352         // Copy
353         check_assist(
354             generate_getter,
355             r#"
356 //- minicore: copy
357 struct S { foo: $0bool }
358 "#,
359             r#"
360 struct S { foo: bool }
361
362 impl S {
363     /// Get the s's foo.
364     fn $0foo(&self) -> bool {
365         self.foo
366     }
367 }
368 "#,
369         );
370
371         // AsRef<str>
372         check_assist(
373             generate_getter,
374             r#"
375 //- minicore: as_ref
376 pub struct String;
377 impl AsRef<str> for String {
378     fn as_ref(&self) -> &str {
379         ""
380     }
381 }
382
383 struct S { foo: $0String }
384 "#,
385             r#"
386 pub struct String;
387 impl AsRef<str> for String {
388     fn as_ref(&self) -> &str {
389         ""
390     }
391 }
392
393 struct S { foo: String }
394
395 impl S {
396     /// Get a reference to the s's foo.
397     fn $0foo(&self) -> &str {
398         self.foo.as_ref()
399     }
400 }
401 "#,
402         );
403
404         // AsRef<T>
405         check_assist(
406             generate_getter,
407             r#"
408 //- minicore: as_ref
409 struct Sweets;
410
411 pub struct Box<T>(T);
412 impl<T> AsRef<T> for Box<T> {
413     fn as_ref(&self) -> &T {
414         &self.0
415     }
416 }
417
418 struct S { foo: $0Box<Sweets> }
419 "#,
420             r#"
421 struct Sweets;
422
423 pub struct Box<T>(T);
424 impl<T> AsRef<T> for Box<T> {
425     fn as_ref(&self) -> &T {
426         &self.0
427     }
428 }
429
430 struct S { foo: Box<Sweets> }
431
432 impl S {
433     /// Get a reference to the s's foo.
434     fn $0foo(&self) -> &Sweets {
435         self.foo.as_ref()
436     }
437 }
438 "#,
439         );
440
441         // AsRef<[T]>
442         check_assist(
443             generate_getter,
444             r#"
445 //- minicore: as_ref
446 pub struct Vec<T>;
447 impl<T> AsRef<[T]> for Vec<T> {
448     fn as_ref(&self) -> &[T] {
449         &[]
450     }
451 }
452
453 struct S { foo: $0Vec<()> }
454 "#,
455             r#"
456 pub struct Vec<T>;
457 impl<T> AsRef<[T]> for Vec<T> {
458     fn as_ref(&self) -> &[T] {
459         &[]
460     }
461 }
462
463 struct S { foo: Vec<()> }
464
465 impl S {
466     /// Get a reference to the s's foo.
467     fn $0foo(&self) -> &[()] {
468         self.foo.as_ref()
469     }
470 }
471 "#,
472         );
473
474         // Option
475         check_assist(
476             generate_getter,
477             r#"
478 //- minicore: option
479 struct Failure;
480
481 struct S { foo: $0Option<Failure> }
482 "#,
483             r#"
484 struct Failure;
485
486 struct S { foo: Option<Failure> }
487
488 impl S {
489     /// Get a reference to the s's foo.
490     fn $0foo(&self) -> Option<&Failure> {
491         self.foo.as_ref()
492     }
493 }
494 "#,
495         );
496
497         // Result
498         check_assist(
499             generate_getter,
500             r#"
501 //- minicore: result
502 struct Context {
503     dat$0a: Result<bool, i32>,
504 }
505 "#,
506             r#"
507 struct Context {
508     data: Result<bool, i32>,
509 }
510
511 impl Context {
512     /// Get a reference to the context's data.
513     fn $0data(&self) -> Result<&bool, &i32> {
514         self.data.as_ref()
515     }
516 }
517 "#,
518         );
519     }
520 }