1 use stdx::{format_to, to_lower_snake_case};
2 use syntax::ast::{self, AstNode, NameOwner, VisibilityOwner};
5 utils::{find_impl_block_end, find_struct_impl, generate_impl_text},
6 AssistContext, AssistId, AssistKind, Assists, GroupLabel,
9 // Assist: generate_getter
11 // Generate a getter method.
25 // /// Get a reference to the person's name.
26 // fn $0name(&self) -> &str {
31 pub(crate) fn generate_getter(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
32 generate_getter_impl(acc, ctx, false)
35 // Assist: generate_getter_mut
37 // Generate a mut getter method.
51 // /// Get a mutable reference to the person's name.
52 // fn $0name_mut(&mut self) -> &mut String {
57 pub(crate) fn generate_getter_mut(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
58 generate_getter_impl(acc, ctx, true)
61 pub(crate) fn generate_getter_impl(
66 let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
67 let field = ctx.find_node_at_offset::<ast::RecordField>()?;
69 let strukt_name = strukt.name()?;
70 let field_name = field.name()?;
71 let field_ty = field.ty()?;
73 // Return early if we've found an existing fn
74 let mut fn_name = to_lower_snake_case(&field_name.to_string());
76 format_to!(fn_name, "_mut");
78 let impl_def = find_struct_impl(&ctx, &ast::Adt::Struct(strukt.clone()), fn_name.as_str())?;
80 let (id, label) = if mutable {
81 ("generate_getter_mut", "Generate a mut getter method")
83 ("generate_getter", "Generate a getter method")
85 let target = field.syntax().text_range();
87 &GroupLabel("Generate getter/setter".to_owned()),
88 AssistId(id, AssistKind::Generate),
92 let mut buf = String::with_capacity(512);
94 if impl_def.is_some() {
98 let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
99 let (ty, body) = if mutable {
100 (format!("&mut {}", field_ty), format!("&mut self.{}", field_name))
102 useless_type_special_case(&field_name.to_string(), &field_ty)
103 .unwrap_or_else(|| (format!("&{}", field_ty), format!("&self.{}", field_name)))
108 " /// Get a {}reference to the {}'s {}.
109 {}fn {}(&{}self) -> {} {{
112 mutable.then(|| "mutable ").unwrap_or_default(),
113 to_lower_snake_case(&strukt_name.to_string()).replace('_', " "),
114 fn_name.trim_end_matches("_mut").replace('_', " "),
117 mutable.then(|| "mut ").unwrap_or_default(),
122 let start_offset = impl_def
123 .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
125 buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
126 strukt.syntax().text_range().end()
129 match ctx.config.snippet_cap {
131 builder.insert_snippet(cap, start_offset, buf.replacen("fn ", "fn $0", 1))
133 None => builder.insert(start_offset, buf),
139 fn useless_type_special_case(field_name: &str, field_ty: &ast::Type) -> Option<(String, String)> {
140 if field_ty.to_string() == "String" {
141 cov_mark::hit!(useless_type_special_case);
142 return Some(("&str".to_string(), format!("self.{}.as_str()", field_name)));
144 if let Some(arg) = ty_ctor(field_ty, "Vec") {
145 return Some((format!("&[{}]", arg), format!("self.{}.as_slice()", field_name)));
147 if let Some(arg) = ty_ctor(field_ty, "Box") {
148 return Some((format!("&{}", arg), format!("self.{}.as_ref()", field_name)));
150 if let Some(arg) = ty_ctor(field_ty, "Option") {
151 return Some((format!("Option<&{}>", arg), format!("self.{}.as_ref()", field_name)));
156 // FIXME: This should rely on semantic info.
157 fn ty_ctor(ty: &ast::Type, ctor: &str) -> Option<String> {
158 let res = ty.to_string().strip_prefix(ctor)?.strip_prefix('<')?.strip_suffix('>')?.to_string();
164 use crate::tests::{check_assist, check_assist_not_applicable};
169 fn test_generate_getter_from_field() {
183 /// Get a reference to the context's data.
184 fn $0data(&self) -> &Data {
204 /// Get a mutable reference to the context's data.
205 fn $0data_mut(&mut self) -> &mut Data {
214 fn test_generate_getter_already_implemented() {
215 check_assist_not_applicable(
223 fn data(&self) -> &Data {
230 check_assist_not_applicable(
238 fn data_mut(&mut self) -> &mut Data {
247 fn test_generate_getter_from_field_with_visibility_marker() {
251 pub(crate) struct Context {
256 pub(crate) struct Context {
261 /// Get a reference to the context's data.
262 pub(crate) fn $0data(&self) -> &Data {
271 fn test_multiple_generate_getter() {
281 /// Get a reference to the context's data.
282 fn data(&self) -> &Data {
294 /// Get a reference to the context's data.
295 fn data(&self) -> &Data {
299 /// Get a reference to the context's count.
300 fn $0count(&self) -> &usize {
309 fn test_special_cases() {
310 cov_mark::check!(useless_type_special_case);
314 struct S { foo: $0String }
317 struct S { foo: String }
320 /// Get a reference to the s's foo.
321 fn $0foo(&self) -> &str {
330 struct S { foo: $0Box<Sweets> }
333 struct S { foo: Box<Sweets> }
336 /// Get a reference to the s's foo.
337 fn $0foo(&self) -> &Sweets {
346 struct S { foo: $0Vec<()> }
349 struct S { foo: Vec<()> }
352 /// Get a reference to the s's foo.
353 fn $0foo(&self) -> &[()] {
362 struct S { foo: $0Option<Failure> }
365 struct S { foo: Option<Failure> }
368 /// Get a reference to the s's foo.
369 fn $0foo(&self) -> Option<&Failure> {