Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit f3cce5f

Browse files
committedOct 20, 2022
Auto merge of rust-lang#13365 - feniljain:master, r=Veykril
feat: add multiple getters mode in `generate_getter` This commit adds two modes to generate_getter action. First, the plain old working on single fields. Second, working on a selected range of fields. Should partially solve rust-lang#13246 If this gets approved will create a separate PR for setters version of the same ### Points to help in review: - `generate_getter_from_record_info` contains code which is mostly taken from assist before refactor - Same goes for `parse_record_fields` - There are changes in other assists, as one of the methods in utils named `find_struct_impl` is changed, before it used to accept a single `fn_name`, now it takes a list of function names to check against. All old impls are updated to create a small list to pass their single element. ### Assumptions: - If any of the fields have an implementation, the action will quit.
2 parents 32614e2 + 5bff6c5 commit f3cce5f

File tree

8 files changed

+292
-69
lines changed

8 files changed

+292
-69
lines changed
 

‎crates/ide-assists/src/handlers/generate_delegate_methods.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,14 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<'
5151
Some(field) => {
5252
let field_name = field.name()?;
5353
let field_ty = field.ty()?;
54-
(format!("{field_name}"), field_ty, field.syntax().text_range())
54+
(field_name.to_string(), field_ty, field.syntax().text_range())
5555
}
5656
None => {
5757
let field = ctx.find_node_at_offset::<ast::TupleField>()?;
5858
let field_list = ctx.find_node_at_offset::<ast::TupleFieldList>()?;
5959
let field_list_index = field_list.fields().position(|it| it == field)?;
6060
let field_ty = field.ty()?;
61-
(format!("{field_list_index}"), field_ty, field.syntax().text_range())
61+
(field_list_index.to_string(), field_ty, field.syntax().text_range())
6262
}
6363
};
6464

@@ -77,13 +77,11 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<'
7777
for method in methods {
7878
let adt = ast::Adt::Struct(strukt.clone());
7979
let name = method.name(ctx.db()).to_string();
80-
let impl_def = find_struct_impl(ctx, &adt, &name).flatten();
81-
let method_name = method.name(ctx.db());
82-
80+
let impl_def = find_struct_impl(ctx, &adt, &[name]).flatten();
8381
acc.add_group(
8482
&GroupLabel("Generate delegate methods…".to_owned()),
8583
AssistId("generate_delegate_methods", AssistKind::Generate),
86-
format!("Generate delegate for `{field_name}.{method_name}()`"),
84+
format!("Generate delegate for `{}.{}()`", field_name, method.name(ctx.db())),
8785
target,
8886
|builder| {
8987
// Create the function
@@ -158,7 +156,7 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<'
158156
}
159157
None => {
160158
let offset = strukt.syntax().text_range().end();
161-
let snippet = format!("\n\n{impl_def}");
159+
let snippet = format!("\n\n{}", impl_def.syntax());
162160
builder.insert(offset, snippet);
163161
}
164162
}

‎crates/ide-assists/src/handlers/generate_enum_is_method.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ pub(crate) fn generate_enum_is_method(acc: &mut Assists, ctx: &AssistContext<'_>
5252
let fn_name = format!("is_{}", &to_lower_snake_case(&variant_name.text()));
5353

5454
// Return early if we've found an existing new fn
55-
let impl_def = find_struct_impl(ctx, &parent_enum, &fn_name)?;
55+
let impl_def = find_struct_impl(ctx, &parent_enum, &[fn_name.clone()])?;
5656

5757
let target = variant.syntax().text_range();
5858
acc.add_group(

‎crates/ide-assists/src/handlers/generate_enum_projection_method.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ fn generate_enum_projection_method(
147147
let fn_name = format!("{}_{}", fn_name_prefix, &to_lower_snake_case(&variant_name.text()));
148148

149149
// Return early if we've found an existing new fn
150-
let impl_def = find_struct_impl(ctx, &parent_enum, &fn_name)?;
150+
let impl_def = find_struct_impl(ctx, &parent_enum, &[fn_name.clone()])?;
151151

152152
let target = variant.syntax().text_range();
153153
acc.add_group(

‎crates/ide-assists/src/handlers/generate_function.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ fn get_adt_source(
198198
let file = ctx.sema.parse(range.file_id);
199199
let adt_source =
200200
ctx.sema.find_node_at_offset_with_macros(file.syntax(), range.range.start())?;
201-
find_struct_impl(ctx, &adt_source, fn_name).map(|impl_| (impl_, range.file_id))
201+
find_struct_impl(ctx, &adt_source, &[fn_name.to_string()]).map(|impl_| (impl_, range.file_id))
202202
}
203203

204204
struct FunctionTemplate {

‎crates/ide-assists/src/handlers/generate_getter.rs

Lines changed: 272 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
use ide_db::famous_defs::FamousDefs;
22
use stdx::{format_to, to_lower_snake_case};
3-
use syntax::ast::{self, AstNode, HasName, HasVisibility};
3+
use syntax::{
4+
ast::{self, AstNode, HasName, HasVisibility},
5+
TextRange,
6+
};
47

58
use crate::{
69
utils::{convert_reference_type, find_impl_block_end, find_struct_impl, generate_impl_text},
@@ -72,88 +75,259 @@ pub(crate) fn generate_getter_mut(acc: &mut Assists, ctx: &AssistContext<'_>) ->
7275
generate_getter_impl(acc, ctx, true)
7376
}
7477

78+
#[derive(Clone, Debug)]
79+
struct RecordFieldInfo {
80+
field_name: syntax::ast::Name,
81+
field_ty: syntax::ast::Type,
82+
fn_name: String,
83+
target: TextRange,
84+
}
85+
86+
struct GetterInfo {
87+
impl_def: Option<ast::Impl>,
88+
strukt: ast::Struct,
89+
mutable: bool,
90+
}
91+
7592
pub(crate) fn generate_getter_impl(
7693
acc: &mut Assists,
7794
ctx: &AssistContext<'_>,
7895
mutable: bool,
7996
) -> Option<()> {
80-
let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
81-
let field = ctx.find_node_at_offset::<ast::RecordField>()?;
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
100+
//
101+
// This is the only part where implementation diverges a bit,
102+
// subsequent code is generic for both of these modes
82103

83-
let field_name = field.name()?;
84-
let field_ty = field.ty()?;
104+
let (strukt, info_of_record_fields, fn_names) = if !ctx.has_empty_selection() {
105+
// Selection Mode
106+
let node = ctx.covering_element();
85107

86-
// Return early if we've found an existing fn
87-
let mut fn_name = to_lower_snake_case(&field_name.to_string());
88-
if mutable {
89-
format_to!(fn_name, "_mut");
108+
let node = match node {
109+
syntax::NodeOrToken::Node(n) => n,
110+
syntax::NodeOrToken::Token(t) => t.parent()?,
111+
};
112+
113+
let parent_struct = node.ancestors().find_map(ast::Struct::cast)?;
114+
115+
let (info_of_record_fields, field_names) =
116+
extract_and_parse_record_fields(&parent_struct, ctx.selection_trimmed(), mutable)?;
117+
118+
(parent_struct, info_of_record_fields, field_names)
119+
} else {
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>()?;
123+
124+
let record_field_info = parse_record_field(field, mutable)?;
125+
126+
let fn_name = record_field_info.fn_name.clone();
127+
128+
(strukt, vec![record_field_info], vec![fn_name])
129+
};
130+
131+
// No record fields to do work on :(
132+
if info_of_record_fields.len() == 0 {
133+
return None;
90134
}
91-
let impl_def = find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), fn_name.as_str())?;
135+
136+
let impl_def = find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), &fn_names)?;
92137

93138
let (id, label) = if mutable {
94139
("generate_getter_mut", "Generate a mut getter method")
95140
} else {
96141
("generate_getter", "Generate a getter method")
97142
};
98-
let target = field.syntax().text_range();
143+
144+
// Computing collective text range of all record fields in selected region
145+
let target: TextRange = info_of_record_fields
146+
.iter()
147+
.map(|record_field_info| record_field_info.target)
148+
.reduce(|acc, target| acc.cover(target))?;
149+
150+
let getter_info = GetterInfo { impl_def, strukt, mutable };
151+
99152
acc.add_group(
100153
&GroupLabel("Generate getter/setter".to_owned()),
101154
AssistId(id, AssistKind::Generate),
102155
label,
103156
target,
104157
|builder| {
158+
let record_fields_count = info_of_record_fields.len();
159+
105160
let mut buf = String::with_capacity(512);
106161

107-
if impl_def.is_some() {
108-
buf.push('\n');
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
168+
buf.push('\n');
169+
}
170+
}
109171
}
110172

111-
let vis = strukt.visibility().map_or(String::new(), |v| format!("{v} "));
112-
let (ty, body) = if mutable {
113-
(format!("&mut {field_ty}"), format!("&mut self.{field_name}"))
114-
} else {
115-
(|| {
116-
let krate = ctx.sema.scope(field_ty.syntax())?.krate();
117-
let famous_defs = &FamousDefs(&ctx.sema, krate);
118-
ctx.sema
119-
.resolve_type(&field_ty)
120-
.and_then(|ty| convert_reference_type(ty, ctx.db(), famous_defs))
121-
.map(|conversion| {
122-
cov_mark::hit!(convert_reference_type);
123-
(
124-
conversion.convert_type(ctx.db()),
125-
conversion.getter(field_name.to_string()),
126-
)
127-
})
128-
})()
129-
.unwrap_or_else(|| (format!("&{field_ty}"), format!("&self.{field_name}")))
130-
};
131-
132-
let mut_ = mutable.then(|| "mut ").unwrap_or_default();
133-
format_to!(
134-
buf,
135-
" {vis}fn {fn_name}(&{mut_}self) -> {ty} {{
136-
{body}
137-
}}"
138-
);
139-
140-
let start_offset = impl_def
141-
.and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
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
178+
let mut getter_buf =
179+
generate_getter_from_info(ctx, &getter_info, &record_field_info);
180+
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);
184+
}
185+
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:
189+
//
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
193+
//
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
198+
if i == 0 {
199+
buf = buf + &getter_buf;
200+
} else {
201+
buf = buf + "\n" + &getter_buf;
202+
}
203+
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 {
210+
buf = buf + "\n";
211+
}
212+
}
213+
214+
let start_offset = getter_info
215+
.impl_def
216+
.as_ref()
217+
.and_then(|impl_def| find_impl_block_end(impl_def.to_owned(), &mut buf))
142218
.unwrap_or_else(|| {
143-
buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf);
144-
strukt.syntax().text_range().end()
219+
buf = generate_impl_text(&ast::Adt::Struct(getter_info.strukt.clone()), &buf);
220+
getter_info.strukt.syntax().text_range().end()
145221
});
146222

147223
match ctx.config.snippet_cap {
148-
Some(cap) => {
149-
builder.insert_snippet(cap, start_offset, buf.replacen("fn ", "fn $0", 1))
150-
}
224+
Some(cap) => builder.insert_snippet(cap, start_offset, buf),
151225
None => builder.insert(start_offset, buf),
152226
}
153227
},
154228
)
155229
}
156230

231+
fn generate_getter_from_info(
232+
ctx: &AssistContext<'_>,
233+
info: &GetterInfo,
234+
record_field_info: &RecordFieldInfo,
235+
) -> String {
236+
let mut buf = String::with_capacity(512);
237+
238+
let vis = info.strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
239+
let (ty, body) = if info.mutable {
240+
(
241+
format!("&mut {}", record_field_info.field_ty),
242+
format!("&mut self.{}", record_field_info.field_name),
243+
)
244+
} else {
245+
(|| {
246+
let krate = ctx.sema.scope(record_field_info.field_ty.syntax())?.krate();
247+
let famous_defs = &FamousDefs(&ctx.sema, krate);
248+
ctx.sema
249+
.resolve_type(&record_field_info.field_ty)
250+
.and_then(|ty| convert_reference_type(ty, ctx.db(), famous_defs))
251+
.map(|conversion| {
252+
cov_mark::hit!(convert_reference_type);
253+
(
254+
conversion.convert_type(ctx.db()),
255+
conversion.getter(record_field_info.field_name.to_string()),
256+
)
257+
})
258+
})()
259+
.unwrap_or_else(|| {
260+
(
261+
format!("&{}", record_field_info.field_ty),
262+
format!("&self.{}", record_field_info.field_name),
263+
)
264+
})
265+
};
266+
267+
format_to!(
268+
buf,
269+
" {}fn {}(&{}self) -> {} {{
270+
{}
271+
}}",
272+
vis,
273+
record_field_info.fn_name,
274+
info.mutable.then(|| "mut ").unwrap_or_default(),
275+
ty,
276+
body,
277+
);
278+
279+
buf
280+
}
281+
282+
fn extract_and_parse_record_fields(
283+
node: &ast::Struct,
284+
selection_range: TextRange,
285+
mutable: bool,
286+
) -> Option<(Vec<RecordFieldInfo>, Vec<String>)> {
287+
let mut field_names: Vec<String> = vec![];
288+
let field_list = node.field_list()?;
289+
290+
match field_list {
291+
ast::FieldList::RecordFieldList(ele) => {
292+
let info_of_record_fields_in_selection = ele
293+
.fields()
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);
299+
}
300+
301+
None
302+
})
303+
.collect::<Vec<RecordFieldInfo>>();
304+
305+
if info_of_record_fields_in_selection.len() == 0 {
306+
return None;
307+
}
308+
309+
Some((info_of_record_fields_in_selection, field_names))
310+
}
311+
ast::FieldList::TupleFieldList(_) => {
312+
return None;
313+
}
314+
}
315+
}
316+
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()?;
320+
321+
let mut fn_name = to_lower_snake_case(&field_name.to_string());
322+
if mutable {
323+
format_to!(fn_name, "_mut");
324+
}
325+
326+
let target = record_field.syntax().text_range();
327+
328+
Some(RecordFieldInfo { field_name, field_ty, fn_name, target })
329+
}
330+
157331
#[cfg(test)]
158332
mod tests {
159333
use crate::tests::{check_assist, check_assist_not_applicable};
@@ -485,4 +659,53 @@ impl Context {
485659
"#,
486660
);
487661
}
662+
663+
#[test]
664+
fn test_generate_multiple_getters_from_selection() {
665+
check_assist(
666+
generate_getter,
667+
r#"
668+
struct Context {
669+
$0data: Data,
670+
count: usize,$0
671+
}
672+
"#,
673+
r#"
674+
struct Context {
675+
data: Data,
676+
count: usize,
677+
}
678+
679+
impl Context {
680+
fn data(&self) -> &Data {
681+
&self.data
682+
}
683+
684+
fn $0count(&self) -> &usize {
685+
&self.count
686+
}
687+
}
688+
"#,
689+
);
690+
}
691+
692+
#[test]
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(
696+
generate_getter,
697+
r#"
698+
struct Context {
699+
$0data: Data,
700+
count: usize,$0
701+
}
702+
703+
impl Context {
704+
fn data(&self) -> &Data {
705+
&self.data
706+
}
707+
}
708+
"#,
709+
);
710+
}
488711
}

‎crates/ide-assists/src/handlers/generate_new.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option
3939
};
4040

4141
// Return early if we've found an existing new fn
42-
let impl_def = find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), "new")?;
42+
let impl_def =
43+
find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), &[String::from("new")])?;
4344

4445
let current_module = ctx.sema.scope(strukt.syntax())?.module();
4546

‎crates/ide-assists/src/handlers/generate_setter.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,8 @@ pub(crate) fn generate_setter(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opt
3636

3737
// Return early if we've found an existing fn
3838
let fn_name = to_lower_snake_case(&field_name.to_string());
39-
let impl_def = find_struct_impl(
40-
ctx,
41-
&ast::Adt::Struct(strukt.clone()),
42-
format!("set_{fn_name}").as_str(),
43-
)?;
39+
let impl_def =
40+
find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), &[format!("set_{fn_name}")])?;
4441

4542
let target = field.syntax().text_range();
4643
acc.add_group(

‎crates/ide-assists/src/utils.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -331,10 +331,14 @@ fn calc_depth(pat: &ast::Pat, depth: usize) -> usize {
331331
// FIXME: change the new fn checking to a more semantic approach when that's more
332332
// viable (e.g. we process proc macros, etc)
333333
// FIXME: this partially overlaps with `find_impl_block_*`
334+
335+
/// `find_struct_impl` looks for impl of a struct, but this also has additional feature
336+
/// where it takes a list of function names and check if they exist inside impl_, if
337+
/// even one match is found, it returns None
334338
pub(crate) fn find_struct_impl(
335339
ctx: &AssistContext<'_>,
336340
adt: &ast::Adt,
337-
name: &str,
341+
names: &[String],
338342
) -> Option<Option<ast::Impl>> {
339343
let db = ctx.db();
340344
let module = adt.syntax().parent()?;
@@ -362,20 +366,20 @@ pub(crate) fn find_struct_impl(
362366
});
363367

364368
if let Some(ref impl_blk) = block {
365-
if has_fn(impl_blk, name) {
369+
if has_any_fn(impl_blk, names) {
366370
return None;
367371
}
368372
}
369373

370374
Some(block)
371375
}
372376

373-
fn has_fn(imp: &ast::Impl, rhs_name: &str) -> bool {
377+
fn has_any_fn(imp: &ast::Impl, names: &[String]) -> bool {
374378
if let Some(il) = imp.assoc_item_list() {
375379
for item in il.assoc_items() {
376380
if let ast::AssocItem::Fn(f) = item {
377381
if let Some(name) = f.name() {
378-
if name.text().eq_ignore_ascii_case(rhs_name) {
382+
if names.iter().any(|n| n.eq_ignore_ascii_case(&name.text())) {
379383
return true;
380384
}
381385
}

0 commit comments

Comments
 (0)
Please sign in to comment.