Skip to content

Commit a2e4f78

Browse files
committed
Auto merge of #13399 - DropDemBits:assists-format-args-capture-pt2, r=Veykril
Migrate assists to format args captures, part 2 Continuation of #13379 Migrates: - `generate_constant` - `generate_default_from_enum_variant` - `generate_default_from_new` - `generate_delegate_methods` - `generate_deref` - `generate_documentation_template` - `generate_enum_is_method` - `generate_enum_projection_method` - `generate_from_impl_for_enum` - `generate_function` - `generate_getter` - `generate_impl` - `generate_new` - `generate_setter`
2 parents 0531aab + d7fb8d5 commit a2e4f78

14 files changed

+150
-157
lines changed

crates/ide-assists/src/handlers/generate_constant.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ pub(crate) fn generate_constant(acc: &mut Assists, ctx: &AssistContext<'_>) -> O
7777
target_data_for_generate_constant(ctx, current_module, constant_module).unwrap_or_else(
7878
|| {
7979
let indent = IndentLevel::from_node(statement.syntax());
80-
(statement.syntax().text_range().start(), indent, None, format!("\n{}", indent))
80+
(statement.syntax().text_range().start(), indent, None, format!("\n{indent}"))
8181
},
8282
);
8383

@@ -90,7 +90,7 @@ pub(crate) fn generate_constant(acc: &mut Assists, ctx: &AssistContext<'_>) -> O
9090
if let Some(file_id) = file_id {
9191
builder.edit_file(file_id);
9292
}
93-
builder.insert(offset, format!("{}{}", text, post_string));
93+
builder.insert(offset, format!("{text}{post_string}"));
9494
},
9595
)
9696
}
@@ -103,13 +103,13 @@ fn get_text_for_generate_constant(
103103
) -> Option<String> {
104104
let constant_token = not_exist_name_ref.pop()?;
105105
let vis = if not_exist_name_ref.len() == 0 && !outer_exists { "" } else { "\npub " };
106-
let mut text = format!("{}const {}: {} = $0;", vis, constant_token, type_name);
106+
let mut text = format!("{vis}const {constant_token}: {type_name} = $0;");
107107
while let Some(name_ref) = not_exist_name_ref.pop() {
108108
let vis = if not_exist_name_ref.len() == 0 && !outer_exists { "" } else { "\npub " };
109109
text = text.replace("\n", "\n ");
110-
text = format!("{}mod {} {{{}\n}}", vis, name_ref.to_string(), text);
110+
text = format!("{vis}mod {name_ref} {{{text}\n}}");
111111
}
112-
Some(text.replace("\n", &format!("\n{}", indent)))
112+
Some(text.replace("\n", &format!("\n{indent}")))
113113
}
114114

115115
fn target_data_for_generate_constant(
@@ -134,7 +134,7 @@ fn target_data_for_generate_constant(
134134
.find(|it| it.kind() == SyntaxKind::WHITESPACE && it.to_string().contains("\n"))
135135
.is_some();
136136
let post_string =
137-
if siblings_has_newline { format!("{}", indent) } else { format!("\n{}", indent) };
137+
if siblings_has_newline { format!("{indent}") } else { format!("\n{indent}") };
138138
Some((offset, indent + 1, Some(file_id), post_string))
139139
}
140140
_ => Some((TextSize::from(0), 0.into(), Some(file_id), "\n".into())),

crates/ide-assists/src/handlers/generate_default_from_enum_variant.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,11 @@ pub(crate) fn generate_default_from_enum_variant(
5555
let buf = format!(
5656
r#"
5757
58-
impl Default for {0} {{
58+
impl Default for {enum_name} {{
5959
fn default() -> Self {{
60-
Self::{1}
60+
Self::{variant_name}
6161
}}
6262
}}"#,
63-
enum_name, variant_name
6463
);
6564
edit.insert(start_offset, buf);
6665
},

crates/ide-assists/src/handlers/generate_default_from_new.rs

+31-30
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
use ide_db::famous_defs::FamousDefs;
2-
use itertools::Itertools;
32
use stdx::format_to;
43
use syntax::{
5-
ast::{self, HasGenericParams, HasName, HasTypeBounds, Impl},
4+
ast::{self, make, HasGenericParams, HasName, Impl},
65
AstNode,
76
};
87

@@ -77,45 +76,47 @@ pub(crate) fn generate_default_from_new(acc: &mut Assists, ctx: &AssistContext<'
7776
)
7877
}
7978

79+
// FIXME: based on from utils::generate_impl_text_inner
8080
fn generate_trait_impl_text_from_impl(impl_: &ast::Impl, trait_text: &str, code: &str) -> String {
81-
let generic_params = impl_.generic_param_list();
82-
let mut buf = String::with_capacity(code.len());
83-
buf.push_str("\n\n");
84-
buf.push_str("impl");
85-
86-
if let Some(generic_params) = &generic_params {
87-
let lifetimes = generic_params.lifetime_params().map(|lt| format!("{}", lt.syntax()));
88-
let toc_params = generic_params.type_or_const_params().map(|toc_param| match toc_param {
89-
ast::TypeOrConstParam::Type(type_param) => {
90-
let mut buf = String::new();
91-
if let Some(it) = type_param.name() {
92-
format_to!(buf, "{}", it.syntax());
93-
}
94-
if let Some(it) = type_param.colon_token() {
95-
format_to!(buf, "{} ", it);
81+
let impl_ty = impl_.self_ty().unwrap();
82+
let generic_params = impl_.generic_param_list().map(|generic_params| {
83+
let lifetime_params =
84+
generic_params.lifetime_params().map(ast::GenericParam::LifetimeParam);
85+
let ty_or_const_params = generic_params.type_or_const_params().filter_map(|param| {
86+
// remove defaults since they can't be specified in impls
87+
match param {
88+
ast::TypeOrConstParam::Type(param) => {
89+
let param = param.clone_for_update();
90+
param.remove_default();
91+
Some(ast::GenericParam::TypeParam(param))
9692
}
97-
if let Some(it) = type_param.type_bound_list() {
98-
format_to!(buf, "{}", it.syntax());
93+
ast::TypeOrConstParam::Const(param) => {
94+
let param = param.clone_for_update();
95+
param.remove_default();
96+
Some(ast::GenericParam::ConstParam(param))
9997
}
100-
buf
10198
}
102-
ast::TypeOrConstParam::Const(const_param) => const_param.syntax().to_string(),
10399
});
104-
let generics = lifetimes.chain(toc_params).format(", ");
105-
format_to!(buf, "<{}>", generics);
106-
}
107100

108-
buf.push(' ');
109-
buf.push_str(trait_text);
110-
buf.push_str(" for ");
111-
buf.push_str(&impl_.self_ty().unwrap().syntax().text().to_string());
101+
make::generic_param_list(itertools::chain(lifetime_params, ty_or_const_params))
102+
});
103+
104+
let mut buf = String::with_capacity(code.len());
105+
buf.push_str("\n\n");
106+
107+
// `impl{generic_params} {trait_text} for {impl_.self_ty()}`
108+
buf.push_str("impl");
109+
if let Some(generic_params) = &generic_params {
110+
format_to!(buf, "{generic_params}")
111+
}
112+
format_to!(buf, " {trait_text} for {impl_ty}");
112113

113114
match impl_.where_clause() {
114115
Some(where_clause) => {
115-
format_to!(buf, "\n{}\n{{\n{}\n}}", where_clause, code);
116+
format_to!(buf, "\n{where_clause}\n{{\n{code}\n}}");
116117
}
117118
None => {
118-
format_to!(buf, " {{\n{}\n}}", code);
119+
format_to!(buf, " {{\n{code}\n}}");
119120
}
120121
}
121122

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

+7-5
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+
(format!("{field_name}"), 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+
(format!("{field_list_index}"), field_ty, field.syntax().text_range())
6262
}
6363
};
6464

@@ -78,10 +78,12 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<'
7878
let adt = ast::Adt::Struct(strukt.clone());
7979
let name = method.name(ctx.db()).to_string();
8080
let impl_def = find_struct_impl(ctx, &adt, &name).flatten();
81+
let method_name = method.name(ctx.db());
82+
8183
acc.add_group(
8284
&GroupLabel("Generate delegate methods…".to_owned()),
8385
AssistId("generate_delegate_methods", AssistKind::Generate),
84-
format!("Generate delegate for `{}.{}()`", field_name, method.name(ctx.db())),
86+
format!("Generate delegate for `{field_name}.{method_name}()`"),
8587
target,
8688
|builder| {
8789
// Create the function
@@ -151,12 +153,12 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<'
151153
Some(cap) => {
152154
let offset = strukt.syntax().text_range().end();
153155
let snippet = render_snippet(cap, impl_def.syntax(), cursor);
154-
let snippet = format!("\n\n{}", snippet);
156+
let snippet = format!("\n\n{snippet}");
155157
builder.insert_snippet(cap, offset, snippet);
156158
}
157159
None => {
158160
let offset = strukt.syntax().text_range().end();
159-
let snippet = format!("\n\n{}", impl_def.syntax());
161+
let snippet = format!("\n\n{impl_def}");
160162
builder.insert(offset, snippet);
161163
}
162164
}

crates/ide-assists/src/handlers/generate_deref.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ fn generate_record_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<(
6666
let target = field.syntax().text_range();
6767
acc.add(
6868
AssistId("generate_deref", AssistKind::Generate),
69-
format!("Generate `{:?}` impl using `{}`", deref_type_to_generate, field_name),
69+
format!("Generate `{deref_type_to_generate:?}` impl using `{field_name}`"),
7070
target,
7171
|edit| {
7272
generate_edit(
@@ -106,7 +106,7 @@ fn generate_tuple_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()
106106
let target = field.syntax().text_range();
107107
acc.add(
108108
AssistId("generate_deref", AssistKind::Generate),
109-
format!("Generate `{:?}` impl using `{}`", deref_type_to_generate, field.syntax()),
109+
format!("Generate `{deref_type_to_generate:?}` impl using `{field}`"),
110110
target,
111111
|edit| {
112112
generate_edit(
@@ -132,18 +132,16 @@ fn generate_edit(
132132
let start_offset = strukt.syntax().text_range().end();
133133
let impl_code = match deref_type {
134134
DerefType::Deref => format!(
135-
r#" type Target = {0};
135+
r#" type Target = {field_type_syntax};
136136
137137
fn deref(&self) -> &Self::Target {{
138-
&self.{1}
138+
&self.{field_name}
139139
}}"#,
140-
field_type_syntax, field_name
141140
),
142141
DerefType::DerefMut => format!(
143142
r#" fn deref_mut(&mut self) -> &mut Self::Target {{
144-
&mut self.{}
143+
&mut self.{field_name}
145144
}}"#,
146-
field_name
147145
),
148146
};
149147
let strukt_adt = ast::Adt::Struct(strukt);

crates/ide-assists/src/handlers/generate_documentation_template.rs

+31-21
Original file line numberDiff line numberDiff line change
@@ -139,40 +139,44 @@ fn make_example_for_fn(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option<St
139139

140140
let mut example = String::new();
141141

142+
let use_path = build_path(ast_func, ctx)?;
142143
let is_unsafe = ast_func.unsafe_token().is_some();
143144
let param_list = ast_func.param_list()?;
144145
let ref_mut_params = ref_mut_params(&param_list);
145146
let self_name = self_name(ast_func);
146147

147-
format_to!(example, "use {};\n\n", build_path(ast_func, ctx)?);
148+
format_to!(example, "use {use_path};\n\n");
148149
if let Some(self_name) = &self_name {
149-
if let Some(mtbl) = is_ref_mut_self(ast_func) {
150-
let mtbl = if mtbl == true { " mut" } else { "" };
151-
format_to!(example, "let{} {} = ;\n", mtbl, self_name);
150+
if let Some(mut_) = is_ref_mut_self(ast_func) {
151+
let mut_ = if mut_ == true { "mut " } else { "" };
152+
format_to!(example, "let {mut_}{self_name} = ;\n");
152153
}
153154
}
154155
for param_name in &ref_mut_params {
155-
format_to!(example, "let mut {} = ;\n", param_name);
156+
format_to!(example, "let mut {param_name} = ;\n");
156157
}
157158
// Call the function, check result
158159
let function_call = function_call(ast_func, &param_list, self_name.as_deref(), is_unsafe)?;
159160
if returns_a_value(ast_func, ctx) {
160161
if count_parameters(&param_list) < 3 {
161-
format_to!(example, "assert_eq!({}, );\n", function_call);
162+
format_to!(example, "assert_eq!({function_call}, );\n");
162163
} else {
163-
format_to!(example, "let result = {};\n", function_call);
164+
format_to!(example, "let result = {function_call};\n");
164165
example.push_str("assert_eq!(result, );\n");
165166
}
166167
} else {
167-
format_to!(example, "{};\n", function_call);
168+
format_to!(example, "{function_call};\n");
168169
}
169170
// Check the mutated values
170-
if is_ref_mut_self(ast_func) == Some(true) {
171-
format_to!(example, "assert_eq!({}, );", self_name?);
171+
if let Some(self_name) = &self_name {
172+
if is_ref_mut_self(ast_func) == Some(true) {
173+
format_to!(example, "assert_eq!({self_name}, );");
174+
}
172175
}
173176
for param_name in &ref_mut_params {
174-
format_to!(example, "assert_eq!({}, );", param_name);
177+
format_to!(example, "assert_eq!({param_name}, );");
175178
}
179+
176180
Some(example)
177181
}
178182

@@ -189,7 +193,8 @@ fn introduction_builder(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option<S
189193
let intro_for_new = || {
190194
let is_new = name == "new";
191195
if is_new && ret_ty == self_ty {
192-
Some(format!("Creates a new [`{}`].", linkable_self_ty?))
196+
let self_ty = linkable_self_ty?;
197+
Some(format!("Creates a new [`{self_ty}`]."))
193198
} else {
194199
None
195200
}
@@ -214,7 +219,9 @@ fn introduction_builder(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option<S
214219
} else {
215220
""
216221
};
217-
Some(format!("Returns{reference} the {what} of this [`{}`].", linkable_self_ty?))
222+
223+
let self_ty = linkable_self_ty?;
224+
Some(format!("Returns{reference} the {what} of this [`{self_ty}`]."))
218225
}
219226
_ => None,
220227
};
@@ -228,7 +235,9 @@ fn introduction_builder(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option<S
228235
if what == "len" {
229236
what = "length".into()
230237
};
231-
Some(format!("Sets the {what} of this [`{}`].", linkable_self_ty?))
238+
239+
let self_ty = linkable_self_ty?;
240+
Some(format!("Sets the {what} of this [`{self_ty}`]."))
232241
};
233242

234243
if let Some(intro) = intro_for_new() {
@@ -404,7 +413,7 @@ fn arguments_from_params(param_list: &ast::ParamList) -> String {
404413
// instance `TuplePat`) could be managed later.
405414
Some(ast::Pat::IdentPat(ident_pat)) => match ident_pat.name() {
406415
Some(name) => match is_a_ref_mut_param(&param) {
407-
true => format!("&mut {}", name),
416+
true => format!("&mut {name}"),
408417
false => name.to_string(),
409418
},
410419
None => "_".to_string(),
@@ -424,14 +433,15 @@ fn function_call(
424433
let name = ast_func.name()?;
425434
let arguments = arguments_from_params(param_list);
426435
let function_call = if param_list.self_param().is_some() {
427-
format!("{}.{}({})", self_name?, name, arguments)
436+
let self_ = self_name?;
437+
format!("{self_}.{name}({arguments})")
428438
} else if let Some(implementation) = self_partial_type(ast_func) {
429-
format!("{}::{}({})", implementation, name, arguments)
439+
format!("{implementation}::{name}({arguments})")
430440
} else {
431-
format!("{}({})", name, arguments)
441+
format!("{name}({arguments})")
432442
};
433443
match is_unsafe {
434-
true => Some(format!("unsafe {{ {} }}", function_call)),
444+
true => Some(format!("unsafe {{ {function_call} }}")),
435445
false => Some(function_call),
436446
}
437447
}
@@ -469,8 +479,8 @@ fn build_path(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option<String> {
469479
.unwrap_or_else(|| "*".into());
470480
let module_def: ModuleDef = ctx.sema.to_def(ast_func)?.module(ctx.db()).into();
471481
match module_def.canonical_path(ctx.db()) {
472-
Some(path) => Some(format!("{}::{}::{}", crate_name, path, leaf)),
473-
None => Some(format!("{}::{}", crate_name, leaf)),
482+
Some(path) => Some(format!("{crate_name}::{path}::{leaf}")),
483+
None => Some(format!("{crate_name}::{leaf}")),
474484
}
475485
}
476486

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

+5-11
Original file line numberDiff line numberDiff line change
@@ -61,21 +61,15 @@ pub(crate) fn generate_enum_is_method(acc: &mut Assists, ctx: &AssistContext<'_>
6161
"Generate an `is_` method for this enum variant",
6262
target,
6363
|builder| {
64-
let vis = parent_enum.visibility().map_or(String::new(), |v| format!("{} ", v));
64+
let vis = parent_enum.visibility().map_or(String::new(), |v| format!("{v} "));
6565
let method = format!(
66-
" /// Returns `true` if the {} is [`{variant}`].
66+
" /// Returns `true` if the {enum_lowercase_name} is [`{variant_name}`].
6767
///
68-
/// [`{variant}`]: {}::{variant}
68+
/// [`{variant_name}`]: {enum_name}::{variant_name}
6969
#[must_use]
70-
{}fn {}(&self) -> bool {{
71-
matches!(self, Self::{variant}{})
70+
{vis}fn {fn_name}(&self) -> bool {{
71+
matches!(self, Self::{variant_name}{pattern_suffix})
7272
}}",
73-
enum_lowercase_name,
74-
enum_name,
75-
vis,
76-
fn_name,
77-
pattern_suffix,
78-
variant = variant_name
7973
);
8074

8175
add_method_to_adt(builder, &parent_enum, impl_def, &method);

0 commit comments

Comments
 (0)