1 use ide_db::famous_defs::FamousDefs;
2 use stdx::{format_to, to_lower_snake_case};
4 ast::{self, AstNode, HasName, HasVisibility},
9 utils::{convert_reference_type, find_impl_block_end, find_struct_impl, generate_impl_text},
10 AssistContext, AssistId, AssistKind, Assists, GroupLabel,
13 // Assist: generate_getter
15 // Generate a getter method.
18 // # //- minicore: as_ref
19 // # pub struct String;
20 // # impl AsRef<str> for String {
21 // # fn as_ref(&self) -> &str {
32 // # pub struct String;
33 // # impl AsRef<str> for String {
34 // # fn as_ref(&self) -> &str {
44 // fn $0name(&self) -> &str {
49 pub(crate) fn generate_getter(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
50 generate_getter_impl(acc, ctx, false)
53 // Assist: generate_getter_mut
55 // Generate a mut getter method.
69 // fn $0name_mut(&mut self) -> &mut String {
74 pub(crate) fn generate_getter_mut(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
75 generate_getter_impl(acc, ctx, true)
78 #[derive(Clone, Debug)]
79 struct RecordFieldInfo {
80 field_name: syntax::ast::Name,
81 field_ty: syntax::ast::Type,
87 impl_def: Option<ast::Impl>,
92 pub(crate) fn generate_getter_impl(
94 ctx: &AssistContext<'_>,
97 // This if condition denotes two modes this assist can work in:
98 // - First is acting upon selection of record fields
99 // - Next is acting upon a single record field
101 // This is the only part where implementation diverges a bit,
102 // subsequent code is generic for both of these modes
104 let (strukt, info_of_record_fields, fn_names) = if !ctx.has_empty_selection() {
106 let node = ctx.covering_element();
108 let node = match node {
109 syntax::NodeOrToken::Node(n) => n,
110 syntax::NodeOrToken::Token(t) => t.parent()?,
113 let parent_struct = node.ancestors().find_map(ast::Struct::cast)?;
115 let (info_of_record_fields, field_names) =
116 extract_and_parse_record_fields(&parent_struct, ctx.selection_trimmed(), mutable)?;
118 (parent_struct, info_of_record_fields, field_names)
120 // Single Record Field mode
121 let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
122 let field = ctx.find_node_at_offset::<ast::RecordField>()?;
124 let record_field_info = parse_record_field(field, mutable)?;
126 let fn_name = record_field_info.fn_name.clone();
128 (strukt, vec![record_field_info], vec![fn_name])
131 // No record fields to do work on :(
132 if info_of_record_fields.len() == 0 {
136 let impl_def = find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), &fn_names)?;
138 let (id, label) = if mutable {
139 ("generate_getter_mut", "Generate a mut getter method")
141 ("generate_getter", "Generate a getter method")
144 // Computing collective text range of all record fields in selected region
145 let target: TextRange = info_of_record_fields
147 .map(|record_field_info| record_field_info.target)
148 .reduce(|acc, target| acc.cover(target))?;
150 let getter_info = GetterInfo { impl_def, strukt, mutable };
153 &GroupLabel("Generate getter/setter".to_owned()),
154 AssistId(id, AssistKind::Generate),
158 let record_fields_count = info_of_record_fields.len();
160 let mut buf = String::with_capacity(512);
162 // Check if an impl exists
163 if let Some(impl_def) = &getter_info.impl_def {
164 // Check if impl is empty
165 if let Some(assoc_item_list) = impl_def.assoc_item_list() {
166 if assoc_item_list.assoc_items().next().is_some() {
167 // If not empty then only insert a new line
173 for (i, record_field_info) in info_of_record_fields.iter().enumerate() {
174 // this buf inserts a newline at the end of a getter
175 // automatically, if one wants to add one more newline
176 // for separating it from other assoc items, that needs
177 // to be handled spearately
179 generate_getter_from_info(ctx, &getter_info, &record_field_info);
181 // Insert `$0` only for last getter we generate
182 if i == record_fields_count - 1 {
183 getter_buf = getter_buf.replacen("fn ", "fn $0", 1);
186 // For first element we do not merge with '\n', as
187 // that can be inserted by impl_def check defined
188 // above, for other cases which are:
190 // - impl exists but it empty, here we would ideally
191 // not want to keep newline between impl <struct> {
192 // and fn <fn-name>() { line
194 // - next if impl itself does not exist, in this
195 // case we ourselves generate a new impl and that
196 // again ends up with the same reasoning as above
197 // for not keeping newline
199 buf = buf + &getter_buf;
201 buf = buf + "\n" + &getter_buf;
204 // We don't insert a new line at the end of
205 // last getter as it will end up in the end
206 // of an impl where we would not like to keep
207 // getter and end of impl ( i.e. `}` ) with an
208 // extra line for no reason
209 if i < record_fields_count - 1 {
214 let start_offset = getter_info
217 .and_then(|impl_def| find_impl_block_end(impl_def.to_owned(), &mut buf))
219 buf = generate_impl_text(&ast::Adt::Struct(getter_info.strukt.clone()), &buf);
220 getter_info.strukt.syntax().text_range().end()
223 match ctx.config.snippet_cap {
224 Some(cap) => builder.insert_snippet(cap, start_offset, buf),
225 None => builder.insert(start_offset, buf),
231 fn generate_getter_from_info(
232 ctx: &AssistContext<'_>,
234 record_field_info: &RecordFieldInfo,
236 let mut buf = String::with_capacity(512);
238 let vis = info.strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
239 let (ty, body) = if info.mutable {
241 format!("&mut {}", record_field_info.field_ty),
242 format!("&mut self.{}", record_field_info.field_name),
246 let krate = ctx.sema.scope(record_field_info.field_ty.syntax())?.krate();
247 let famous_defs = &FamousDefs(&ctx.sema, krate);
249 .resolve_type(&record_field_info.field_ty)
250 .and_then(|ty| convert_reference_type(ty, ctx.db(), famous_defs))
252 cov_mark::hit!(convert_reference_type);
254 conversion.convert_type(ctx.db()),
255 conversion.getter(record_field_info.field_name.to_string()),
261 format!("&{}", record_field_info.field_ty),
262 format!("&self.{}", record_field_info.field_name),
269 " {}fn {}(&{}self) -> {} {{
273 record_field_info.fn_name,
274 info.mutable.then(|| "mut ").unwrap_or_default(),
282 fn extract_and_parse_record_fields(
284 selection_range: TextRange,
286 ) -> Option<(Vec<RecordFieldInfo>, Vec<String>)> {
287 let mut field_names: Vec<String> = vec![];
288 let field_list = node.field_list()?;
291 ast::FieldList::RecordFieldList(ele) => {
292 let info_of_record_fields_in_selection = ele
294 .filter_map(|record_field| {
295 if selection_range.contains_range(record_field.syntax().text_range()) {
296 let record_field_info = parse_record_field(record_field, mutable)?;
297 field_names.push(record_field_info.fn_name.clone());
298 return Some(record_field_info);
303 .collect::<Vec<RecordFieldInfo>>();
305 if info_of_record_fields_in_selection.len() == 0 {
309 Some((info_of_record_fields_in_selection, field_names))
311 ast::FieldList::TupleFieldList(_) => {
317 fn parse_record_field(record_field: ast::RecordField, mutable: bool) -> Option<RecordFieldInfo> {
318 let field_name = record_field.name()?;
319 let field_ty = record_field.ty()?;
321 let mut fn_name = to_lower_snake_case(&field_name.to_string());
323 format_to!(fn_name, "_mut");
326 let target = record_field.syntax().text_range();
328 Some(RecordFieldInfo { field_name, field_ty, fn_name, target })
333 use crate::tests::{check_assist, check_assist_not_applicable};
338 fn test_generate_getter_from_field() {
352 fn $0data(&self) -> &Data {
372 fn $0data_mut(&mut self) -> &mut Data {
381 fn test_generate_getter_already_implemented() {
382 check_assist_not_applicable(
390 fn data(&self) -> &Data {
397 check_assist_not_applicable(
405 fn data_mut(&mut self) -> &mut Data {
414 fn test_generate_getter_from_field_with_visibility_marker() {
418 pub(crate) struct Context {
423 pub(crate) struct Context {
428 pub(crate) fn $0data(&self) -> &Data {
437 fn test_multiple_generate_getter() {
447 fn data(&self) -> &Data {
459 fn data(&self) -> &Data {
463 fn $0count(&self) -> &usize {
472 fn test_not_a_special_case() {
473 cov_mark::check_count!(convert_reference_type, 0);
474 // Fake string which doesn't implement AsRef<str>
480 struct S { foo: $0String }
485 struct S { foo: String }
488 fn $0foo(&self) -> &String {
497 fn test_convert_reference_type() {
498 cov_mark::check_count!(convert_reference_type, 6);
505 struct S { foo: $0bool }
508 struct S { foo: bool }
511 fn $0foo(&self) -> bool {
524 impl AsRef<str> for String {
525 fn as_ref(&self) -> &str {
530 struct S { foo: $0String }
534 impl AsRef<str> for String {
535 fn as_ref(&self) -> &str {
540 struct S { foo: String }
543 fn $0foo(&self) -> &str {
557 pub struct Box<T>(T);
558 impl<T> AsRef<T> for Box<T> {
559 fn as_ref(&self) -> &T {
564 struct S { foo: $0Box<Sweets> }
569 pub struct Box<T>(T);
570 impl<T> AsRef<T> for Box<T> {
571 fn as_ref(&self) -> &T {
576 struct S { foo: Box<Sweets> }
579 fn $0foo(&self) -> &Sweets {
592 impl<T> AsRef<[T]> for Vec<T> {
593 fn as_ref(&self) -> &[T] {
598 struct S { foo: $0Vec<()> }
602 impl<T> AsRef<[T]> for Vec<T> {
603 fn as_ref(&self) -> &[T] {
608 struct S { foo: Vec<()> }
611 fn $0foo(&self) -> &[()] {
625 struct S { foo: $0Option<Failure> }
630 struct S { foo: Option<Failure> }
633 fn $0foo(&self) -> Option<&Failure> {
646 dat$0a: Result<bool, i32>,
651 data: Result<bool, i32>,
655 fn $0data(&self) -> Result<&bool, &i32> {
664 fn test_generate_multiple_getters_from_selection() {
680 fn data(&self) -> &Data {
684 fn $0count(&self) -> &usize {
693 fn test_generate_multiple_getters_from_selection_one_already_exists() {
694 // As impl for one of the fields already exist, skip it
695 check_assist_not_applicable(
704 fn data(&self) -> &Data {