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) = if mutable {
116 (format!("&mut {}", field_ty), format!("&mut self.{}", field_name))
118 let famous_defs = &FamousDefs(&ctx.sema, ctx.sema.scope(field_ty.syntax()).krate());
120 .resolve_type(&field_ty)
121 .and_then(|ty| convert_reference_type(ty, ctx.db(), famous_defs))
123 cov_mark::hit!(convert_reference_type);
125 conversion.convert_type(ctx.db()),
126 conversion.getter(field_name.to_string()),
129 .unwrap_or_else(|| (format!("&{}", field_ty), format!("&self.{}", field_name)))
134 " /// Get a {}reference to the {}'s {}.
135 {}fn {}(&{}self) -> {} {{
138 mutable.then(|| "mutable ").unwrap_or_default(),
139 to_lower_snake_case(&strukt_name.to_string()).replace('_', " "),
140 fn_name.trim_end_matches("_mut").replace('_', " "),
143 mutable.then(|| "mut ").unwrap_or_default(),
148 let start_offset = impl_def
149 .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
151 buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
152 strukt.syntax().text_range().end()
155 match ctx.config.snippet_cap {
157 builder.insert_snippet(cap, start_offset, buf.replacen("fn ", "fn $0", 1))
159 None => builder.insert(start_offset, buf),
167 use crate::tests::{check_assist, check_assist_not_applicable};
172 fn test_generate_getter_from_field() {
186 /// Get a reference to the context's data.
187 fn $0data(&self) -> &Data {
207 /// Get a mutable reference to the context's data.
208 fn $0data_mut(&mut self) -> &mut Data {
217 fn test_generate_getter_already_implemented() {
218 check_assist_not_applicable(
226 fn data(&self) -> &Data {
233 check_assist_not_applicable(
241 fn data_mut(&mut self) -> &mut Data {
250 fn test_generate_getter_from_field_with_visibility_marker() {
254 pub(crate) struct Context {
259 pub(crate) struct Context {
264 /// Get a reference to the context's data.
265 pub(crate) fn $0data(&self) -> &Data {
274 fn test_multiple_generate_getter() {
284 /// Get a reference to the context's data.
285 fn data(&self) -> &Data {
297 /// Get a reference to the context's data.
298 fn data(&self) -> &Data {
302 /// Get a reference to the context's count.
303 fn $0count(&self) -> &usize {
312 fn test_not_a_special_case() {
313 cov_mark::check_count!(convert_reference_type, 0);
314 // Fake string which doesn't implement AsRef<str>
320 struct S { foo: $0String }
325 struct S { foo: String }
328 /// Get a reference to the s's foo.
329 fn $0foo(&self) -> &String {
338 fn test_convert_reference_type() {
339 cov_mark::check_count!(convert_reference_type, 6);
346 struct S { foo: $0bool }
349 struct S { foo: bool }
352 /// Get a reference to the s's foo.
353 fn $0foo(&self) -> bool {
366 impl AsRef<str> for String {
367 fn as_ref(&self) -> &str {
372 struct S { foo: $0String }
376 impl AsRef<str> for String {
377 fn as_ref(&self) -> &str {
382 struct S { foo: String }
385 /// Get a reference to the s's foo.
386 fn $0foo(&self) -> &str {
400 pub struct Box<T>(T);
401 impl<T> AsRef<T> for Box<T> {
402 fn as_ref(&self) -> &T {
407 struct S { foo: $0Box<Sweets> }
412 pub struct Box<T>(T);
413 impl<T> AsRef<T> for Box<T> {
414 fn as_ref(&self) -> &T {
419 struct S { foo: Box<Sweets> }
422 /// Get a reference to the s's foo.
423 fn $0foo(&self) -> &Sweets {
436 impl<T> AsRef<[T]> for Vec<T> {
437 fn as_ref(&self) -> &[T] {
442 struct S { foo: $0Vec<()> }
446 impl<T> AsRef<[T]> for Vec<T> {
447 fn as_ref(&self) -> &[T] {
452 struct S { foo: Vec<()> }
455 /// Get a reference to the s's foo.
456 fn $0foo(&self) -> &[()] {
470 struct S { foo: $0Option<Failure> }
475 struct S { foo: Option<Failure> }
478 /// Get a reference to the s's foo.
479 fn $0foo(&self) -> Option<&Failure> {
492 dat$0a: Result<bool, i32>,
497 data: Result<bool, i32>,
501 /// Get a reference to the context's data.
502 fn $0data(&self) -> Result<&bool, &i32> {