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