1 use ide_db::helpers::FamousDefs;
2 use stdx::{format_to, to_lower_snake_case};
3 use syntax::ast::{self, AstNode, HasName, HasVisibility};
6 utils::{convert_reference_type, find_impl_block_end, find_struct_impl, generate_impl_text},
7 AssistContext, AssistId, AssistKind, Assists, GroupLabel,
10 // Assist: generate_getter
12 // Generate a getter method.
15 // # //- minicore: as_ref
16 // # pub struct String;
17 // # impl AsRef<str> for String {
18 // # fn as_ref(&self) -> &str {
29 // # pub struct String;
30 // # impl AsRef<str> for String {
31 // # fn as_ref(&self) -> &str {
41 // /// Get a reference to the person's name.
42 // fn $0name(&self) -> &str {
47 pub(crate) fn generate_getter(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
48 generate_getter_impl(acc, ctx, false)
51 // Assist: generate_getter_mut
53 // Generate a mut getter method.
67 // /// Get a mutable reference to the person's name.
68 // fn $0name_mut(&mut self) -> &mut String {
73 pub(crate) fn generate_getter_mut(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
74 generate_getter_impl(acc, ctx, true)
77 pub(crate) fn generate_getter_impl(
82 let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
83 let field = ctx.find_node_at_offset::<ast::RecordField>()?;
85 let strukt_name = strukt.name()?;
86 let field_name = field.name()?;
87 let field_ty = field.ty()?;
89 // Return early if we've found an existing fn
90 let mut fn_name = to_lower_snake_case(&field_name.to_string());
92 format_to!(fn_name, "_mut");
94 let impl_def = find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), fn_name.as_str())?;
96 let (id, label) = if mutable {
97 ("generate_getter_mut", "Generate a mut getter method")
99 ("generate_getter", "Generate a getter method")
101 let target = field.syntax().text_range();
103 &GroupLabel("Generate getter/setter".to_owned()),
104 AssistId(id, AssistKind::Generate),
108 let mut buf = String::with_capacity(512);
110 if impl_def.is_some() {
114 let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
115 let (ty, body, description) = if mutable {
117 format!("&mut {}", field_ty),
118 format!("&mut self.{}", field_name),
119 "a mutable reference to ",
122 let famous_defs = &FamousDefs(&ctx.sema, ctx.sema.scope(field_ty.syntax()).krate());
124 .resolve_type(&field_ty)
125 .and_then(|ty| convert_reference_type(ty, ctx.db(), famous_defs))
127 cov_mark::hit!(convert_reference_type);
129 conversion.convert_type(ctx.db()),
130 conversion.getter(field_name.to_string()),
131 if conversion.is_copy() { "" } else { "a reference to " },
136 format!("&{}", field_ty),
137 format!("&self.{}", field_name),
145 " /// Get {}the {}'s {}.
146 {}fn {}(&{}self) -> {} {{
150 to_lower_snake_case(&strukt_name.to_string()).replace('_', " "),
151 fn_name.trim_end_matches("_mut").replace('_', " "),
154 mutable.then(|| "mut ").unwrap_or_default(),
159 let start_offset = impl_def
160 .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
162 buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
163 strukt.syntax().text_range().end()
166 match ctx.config.snippet_cap {
168 builder.insert_snippet(cap, start_offset, buf.replacen("fn ", "fn $0", 1))
170 None => builder.insert(start_offset, buf),
178 use crate::tests::{check_assist, check_assist_not_applicable};
183 fn test_generate_getter_from_field() {
197 /// Get a reference to the context's data.
198 fn $0data(&self) -> &Data {
218 /// Get a mutable reference to the context's data.
219 fn $0data_mut(&mut self) -> &mut Data {
228 fn test_generate_getter_already_implemented() {
229 check_assist_not_applicable(
237 fn data(&self) -> &Data {
244 check_assist_not_applicable(
252 fn data_mut(&mut self) -> &mut Data {
261 fn test_generate_getter_from_field_with_visibility_marker() {
265 pub(crate) struct Context {
270 pub(crate) struct Context {
275 /// Get a reference to the context's data.
276 pub(crate) fn $0data(&self) -> &Data {
285 fn test_multiple_generate_getter() {
295 /// Get a reference to the context's data.
296 fn data(&self) -> &Data {
308 /// Get a reference to the context's data.
309 fn data(&self) -> &Data {
313 /// Get a reference to the context's count.
314 fn $0count(&self) -> &usize {
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>
331 struct S { foo: $0String }
336 struct S { foo: String }
339 /// Get a reference to the s's foo.
340 fn $0foo(&self) -> &String {
349 fn test_convert_reference_type() {
350 cov_mark::check_count!(convert_reference_type, 6);
357 struct S { foo: $0bool }
360 struct S { foo: bool }
364 fn $0foo(&self) -> bool {
377 impl AsRef<str> for String {
378 fn as_ref(&self) -> &str {
383 struct S { foo: $0String }
387 impl AsRef<str> for String {
388 fn as_ref(&self) -> &str {
393 struct S { foo: String }
396 /// Get a reference to the s's foo.
397 fn $0foo(&self) -> &str {
411 pub struct Box<T>(T);
412 impl<T> AsRef<T> for Box<T> {
413 fn as_ref(&self) -> &T {
418 struct S { foo: $0Box<Sweets> }
423 pub struct Box<T>(T);
424 impl<T> AsRef<T> for Box<T> {
425 fn as_ref(&self) -> &T {
430 struct S { foo: Box<Sweets> }
433 /// Get a reference to the s's foo.
434 fn $0foo(&self) -> &Sweets {
447 impl<T> AsRef<[T]> for Vec<T> {
448 fn as_ref(&self) -> &[T] {
453 struct S { foo: $0Vec<()> }
457 impl<T> AsRef<[T]> for Vec<T> {
458 fn as_ref(&self) -> &[T] {
463 struct S { foo: Vec<()> }
466 /// Get a reference to the s's foo.
467 fn $0foo(&self) -> &[()] {
481 struct S { foo: $0Option<Failure> }
486 struct S { foo: Option<Failure> }
489 /// Get a reference to the s's foo.
490 fn $0foo(&self) -> Option<&Failure> {
503 dat$0a: Result<bool, i32>,
508 data: Result<bool, i32>,
512 /// Get a reference to the context's data.
513 fn $0data(&self) -> Result<&bool, &i32> {