1 use stdx::{format_to, to_lower_snake_case};
2 use syntax::ast::{self, AstNode, HasName, HasVisibility};
5 utils::useless_type_special_case,
6 utils::{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.
26 // /// Get a reference to the person's name.
27 // fn $0name(&self) -> &str {
32 pub(crate) fn generate_getter(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
33 generate_getter_impl(acc, ctx, false)
36 // Assist: generate_getter_mut
38 // Generate a mut getter method.
52 // /// Get a mutable reference to the person's name.
53 // fn $0name_mut(&mut self) -> &mut String {
58 pub(crate) fn generate_getter_mut(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
59 generate_getter_impl(acc, ctx, true)
62 pub(crate) fn generate_getter_impl(
67 let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
68 let field = ctx.find_node_at_offset::<ast::RecordField>()?;
70 let strukt_name = strukt.name()?;
71 let field_name = field.name()?;
72 let field_ty = field.ty()?;
74 // Return early if we've found an existing fn
75 let mut fn_name = to_lower_snake_case(&field_name.to_string());
77 format_to!(fn_name, "_mut");
79 let impl_def = find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), fn_name.as_str())?;
81 let (id, label) = if mutable {
82 ("generate_getter_mut", "Generate a mut getter method")
84 ("generate_getter", "Generate a getter method")
86 let target = field.syntax().text_range();
88 &GroupLabel("Generate getter/setter".to_owned()),
89 AssistId(id, AssistKind::Generate),
93 let mut buf = String::with_capacity(512);
95 if impl_def.is_some() {
99 let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
100 let (ty, body) = if mutable {
101 (format!("&mut {}", field_ty), format!("&mut self.{}", field_name))
103 useless_type_special_case(&field_name.to_string(), &field_ty.to_string())
104 .unwrap_or_else(|| (format!("&{}", field_ty), format!("&self.{}", field_name)))
109 " /// Get a {}reference to the {}'s {}.
110 {}fn {}(&{}self) -> {} {{
113 mutable.then(|| "mutable ").unwrap_or_default(),
114 to_lower_snake_case(&strukt_name.to_string()).replace('_', " "),
115 fn_name.trim_end_matches("_mut").replace('_', " "),
118 mutable.then(|| "mut ").unwrap_or_default(),
123 let start_offset = impl_def
124 .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
126 buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
127 strukt.syntax().text_range().end()
130 match ctx.config.snippet_cap {
132 builder.insert_snippet(cap, start_offset, buf.replacen("fn ", "fn $0", 1))
134 None => builder.insert(start_offset, buf),
142 use crate::tests::{check_assist, check_assist_not_applicable};
147 fn test_generate_getter_from_field() {
161 /// Get a reference to the context's data.
162 fn $0data(&self) -> &Data {
182 /// Get a mutable reference to the context's data.
183 fn $0data_mut(&mut self) -> &mut Data {
192 fn test_generate_getter_already_implemented() {
193 check_assist_not_applicable(
201 fn data(&self) -> &Data {
208 check_assist_not_applicable(
216 fn data_mut(&mut self) -> &mut Data {
225 fn test_generate_getter_from_field_with_visibility_marker() {
229 pub(crate) struct Context {
234 pub(crate) struct Context {
239 /// Get a reference to the context's data.
240 pub(crate) fn $0data(&self) -> &Data {
249 fn test_multiple_generate_getter() {
259 /// Get a reference to the context's data.
260 fn data(&self) -> &Data {
272 /// Get a reference to the context's data.
273 fn data(&self) -> &Data {
277 /// Get a reference to the context's count.
278 fn $0count(&self) -> &usize {
287 fn test_special_cases() {
288 cov_mark::check!(useless_type_special_case);
292 struct S { foo: $0String }
295 struct S { foo: String }
298 /// Get a reference to the s's foo.
299 fn $0foo(&self) -> &str {
308 struct S { foo: $0Box<Sweets> }
311 struct S { foo: Box<Sweets> }
314 /// Get a reference to the s's foo.
315 fn $0foo(&self) -> &Sweets {
324 struct S { foo: $0Vec<()> }
327 struct S { foo: Vec<()> }
330 /// Get a reference to the s's foo.
331 fn $0foo(&self) -> &[()] {
340 struct S { foo: $0Option<Failure> }
343 struct S { foo: Option<Failure> }
346 /// Get a reference to the s's foo.
347 fn $0foo(&self) -> Option<&Failure> {