Skip to content

Commit afe8f6b

Browse files
committed
Auto merge of #13379 - DropDemBits:ide-assists-format-args-capture, r=Veykril
internal: Migrate `ide_assists::utils` and `ide_assists::handlers` to use format arg captures (part 1) This not only serves as making future migration to mutable syntax trees easier, it also finds out what needs to be migrated in the first place. ~~Aside from the first commit, subsequent commits are structured to only deal with one file/handler at a time.~~ This is the first of 3 PRs, migrating: Utils: - `gen_trait_fn_body` - `render_snippet` - `ReferenceConversion` - `convert_type` - `getter` Handlers: - `add_explicit_type` - `add_return_type` - `add_turbo_fish` - `apply_demorgan` - `auto_import` - `convert_comment_block` - `convert_integer_literal` - `convert_into_to_from` - `convert_iter_for_each_to_for` - `convert_let_else_to_match` - `convert_tuple_struct_to_named_struct` - `convert_two_arm_bool_match_to_matches_macro` - `destructure_tuple_binding` - `extract_function` - `extract_module` - `extract_struct_from_enum_variant` - `extract_type_alias` - `extract_variable` - `fix_visibility`
2 parents 2c37e7d + d439fb2 commit afe8f6b

21 files changed

+158
-165
lines changed

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -69,14 +69,14 @@ pub(crate) fn add_explicit_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> O
6969
let inferred_type = ty.display_source_code(ctx.db(), module.into()).ok()?;
7070
acc.add(
7171
AssistId("add_explicit_type", AssistKind::RefactorRewrite),
72-
format!("Insert explicit type `{}`", inferred_type),
72+
format!("Insert explicit type `{inferred_type}`"),
7373
pat_range,
7474
|builder| match ascribed_ty {
7575
Some(ascribed_ty) => {
7676
builder.replace(ascribed_ty.syntax().text_range(), inferred_type);
7777
}
7878
None => {
79-
builder.insert(pat_range.end(), format!(": {}", inferred_type));
79+
builder.insert(pat_range.end(), format!(": {inferred_type}"));
8080
}
8181
},
8282
)

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

+3-3
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,16 @@ pub(crate) fn add_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opt
3535
match builder_edit_pos {
3636
InsertOrReplace::Insert(insert_pos, needs_whitespace) => {
3737
let preceeding_whitespace = if needs_whitespace { " " } else { "" };
38-
builder.insert(insert_pos, &format!("{}-> {} ", preceeding_whitespace, ty))
38+
builder.insert(insert_pos, &format!("{preceeding_whitespace}-> {ty} "))
3939
}
4040
InsertOrReplace::Replace(text_range) => {
41-
builder.replace(text_range, &format!("-> {}", ty))
41+
builder.replace(text_range, &format!("-> {ty}"))
4242
}
4343
}
4444
if let FnType::Closure { wrap_expr: true } = fn_type {
4545
cov_mark::hit!(wrap_closure_non_block_expr);
4646
// `|x| x` becomes `|x| -> T x` which is invalid, so wrap it in a block
47-
builder.replace(tail_expr.syntax().text_range(), &format!("{{{}}}", tail_expr));
47+
builder.replace(tail_expr.syntax().text_range(), &format!("{{{tail_expr}}}"));
4848
}
4949
},
5050
)

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

+4-3
Original file line numberDiff line numberDiff line change
@@ -93,12 +93,13 @@ pub(crate) fn add_turbo_fish(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti
9393
builder.trigger_signature_help();
9494
match ctx.config.snippet_cap {
9595
Some(cap) => {
96-
let snip = format!("::<{}>", get_snippet_fish_head(number_of_arguments));
96+
let fish_head = get_snippet_fish_head(number_of_arguments);
97+
let snip = format!("::<{fish_head}>");
9798
builder.insert_snippet(cap, ident.text_range().end(), snip)
9899
}
99100
None => {
100101
let fish_head = std::iter::repeat("_").take(number_of_arguments).format(", ");
101-
let snip = format!("::<{}>", fish_head);
102+
let snip = format!("::<{fish_head}>");
102103
builder.insert(ident.text_range().end(), snip);
103104
}
104105
}
@@ -109,7 +110,7 @@ pub(crate) fn add_turbo_fish(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti
109110
/// This will create a snippet string with tabstops marked
110111
fn get_snippet_fish_head(number_of_arguments: usize) -> String {
111112
let mut fish_head = (1..number_of_arguments)
112-
.format_with("", |i, f| f(&format_args!("${{{}:_}}, ", i)))
113+
.format_with("", |i, f| f(&format_args!("${{{i}:_}}, ")))
113114
.to_string();
114115

115116
// tabstop 0 is a special case and always the last one

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

+3-3
Original file line numberDiff line numberDiff line change
@@ -123,20 +123,20 @@ pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti
123123
let lhs_range = lhs.syntax().text_range();
124124
let not_lhs = invert_boolean_expression(lhs);
125125

126-
edit.replace(lhs_range, format!("!({}", not_lhs.syntax().text()));
126+
edit.replace(lhs_range, format!("!({not_lhs}"));
127127
}
128128

129129
if let Some(rhs) = terms.pop_back() {
130130
let rhs_range = rhs.syntax().text_range();
131131
let not_rhs = invert_boolean_expression(rhs);
132132

133-
edit.replace(rhs_range, format!("{})", not_rhs.syntax().text()));
133+
edit.replace(rhs_range, format!("{not_rhs})"));
134134
}
135135

136136
for term in terms {
137137
let term_range = term.syntax().text_range();
138138
let not_term = invert_boolean_expression(term);
139-
edit.replace(term_range, not_term.syntax().text());
139+
edit.replace(term_range, not_term.to_string());
140140
}
141141
}
142142
},

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

+4-2
Original file line numberDiff line numberDiff line change
@@ -127,18 +127,20 @@ pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<
127127
.sort_by_key(|import| Reverse(relevance_score(ctx, import, current_module.as_ref())));
128128

129129
for import in proposed_imports {
130+
let import_path = import.import_path;
131+
130132
acc.add_group(
131133
&group_label,
132134
AssistId("auto_import", AssistKind::QuickFix),
133-
format!("Import `{}`", import.import_path),
135+
format!("Import `{import_path}`"),
134136
range,
135137
|builder| {
136138
let scope = match scope.clone() {
137139
ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
138140
ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
139141
ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
140142
};
141-
insert_use(&scope, mod_path_to_ast(&import.import_path), &ctx.config.insert_use);
143+
insert_use(&scope, mod_path_to_ast(&import_path), &ctx.config.insert_use);
142144
},
143145
);
144146
}

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

+7-6
Original file line numberDiff line numberDiff line change
@@ -54,16 +54,17 @@ fn block_to_line(acc: &mut Assists, comment: ast::Comment) -> Option<()> {
5454

5555
let indent_spaces = indentation.to_string();
5656
let output = lines
57-
.map(|l| l.trim_start_matches(&indent_spaces))
58-
.map(|l| {
57+
.map(|line| {
58+
let line = line.trim_start_matches(&indent_spaces);
59+
5960
// Don't introduce trailing whitespace
60-
if l.is_empty() {
61+
if line.is_empty() {
6162
line_prefix.to_string()
6263
} else {
63-
format!("{} {}", line_prefix, l.trim_start_matches(&indent_spaces))
64+
format!("{line_prefix} {line}")
6465
}
6566
})
66-
.join(&format!("\n{}", indent_spaces));
67+
.join(&format!("\n{indent_spaces}"));
6768

6869
edit.replace(target, output)
6970
},
@@ -96,7 +97,7 @@ fn line_to_block(acc: &mut Assists, comment: ast::Comment) -> Option<()> {
9697
let block_prefix =
9798
CommentKind { shape: CommentShape::Block, ..comment.kind() }.prefix();
9899

99-
let output = format!("{}\n{}\n{}*/", block_prefix, block_comment_body, indentation);
100+
let output = format!("{block_prefix}\n{block_comment_body}\n{indentation}*/");
100101

101102
edit.replace(target, output)
102103
},

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

+5-5
Original file line numberDiff line numberDiff line change
@@ -32,19 +32,19 @@ pub(crate) fn convert_integer_literal(acc: &mut Assists, ctx: &AssistContext<'_>
3232
}
3333

3434
let mut converted = match target_radix {
35-
Radix::Binary => format!("0b{:b}", value),
36-
Radix::Octal => format!("0o{:o}", value),
35+
Radix::Binary => format!("0b{value:b}"),
36+
Radix::Octal => format!("0o{value:o}"),
3737
Radix::Decimal => value.to_string(),
38-
Radix::Hexadecimal => format!("0x{:X}", value),
38+
Radix::Hexadecimal => format!("0x{value:X}"),
3939
};
4040

41-
let label = format!("Convert {} to {}{}", literal, converted, suffix.unwrap_or_default());
42-
4341
// Appends the type suffix back into the new literal if it exists.
4442
if let Some(suffix) = suffix {
4543
converted.push_str(suffix);
4644
}
4745

46+
let label = format!("Convert {literal} to {converted}");
47+
4848
acc.add_group(
4949
&group_id,
5050
AssistId("convert_integer_literal", AssistKind::RefactorInline),

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -86,9 +86,9 @@ pub(crate) fn convert_into_to_from(acc: &mut Assists, ctx: &AssistContext<'_>) -
8686
impl_.syntax().text_range(),
8787
|builder| {
8888
builder.replace(src_type.syntax().text_range(), dest_type.to_string());
89-
builder.replace(ast_trait.syntax().text_range(), format!("From<{}>", src_type));
89+
builder.replace(ast_trait.syntax().text_range(), format!("From<{src_type}>"));
9090
builder.replace(into_fn_return.syntax().text_range(), "-> Self");
91-
builder.replace(into_fn_params.syntax().text_range(), format!("(val: {})", src_type));
91+
builder.replace(into_fn_params.syntax().text_range(), format!("(val: {src_type})"));
9292
builder.replace(into_fn_name.syntax().text_range(), "from");
9393

9494
for s in selfs {

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

+6-6
Original file line numberDiff line numberDiff line change
@@ -119,19 +119,19 @@ pub(crate) fn convert_for_loop_with_for_each(
119119
{
120120
// We have either "for x in &col" and col implements a method called iter
121121
// or "for x in &mut col" and col implements a method called iter_mut
122-
format_to!(buf, "{}.{}()", expr_behind_ref, method);
122+
format_to!(buf, "{expr_behind_ref}.{method}()");
123123
} else if let ast::Expr::RangeExpr(..) = iterable {
124124
// range expressions need to be parenthesized for the syntax to be correct
125-
format_to!(buf, "({})", iterable);
125+
format_to!(buf, "({iterable})");
126126
} else if impls_core_iter(&ctx.sema, &iterable) {
127-
format_to!(buf, "{}", iterable);
127+
format_to!(buf, "{iterable}");
128128
} else if let ast::Expr::RefExpr(_) = iterable {
129-
format_to!(buf, "({}).into_iter()", iterable);
129+
format_to!(buf, "({iterable}).into_iter()");
130130
} else {
131-
format_to!(buf, "{}.into_iter()", iterable);
131+
format_to!(buf, "{iterable}.into_iter()");
132132
}
133133

134-
format_to!(buf, ".for_each(|{}| {});", pat, body);
134+
format_to!(buf, ".for_each(|{pat}| {body});");
135135

136136
builder.replace(for_loop.syntax().text_range(), buf)
137137
},

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

+3-3
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ fn binders_to_str(binders: &[(Name, bool)], addmut: bool) -> String {
8080
.map(
8181
|(ident, ismut)| {
8282
if *ismut && addmut {
83-
format!("mut {}", ident)
83+
format!("mut {ident}")
8484
} else {
8585
ident.to_string()
8686
}
@@ -93,7 +93,7 @@ fn binders_to_str(binders: &[(Name, bool)], addmut: bool) -> String {
9393
} else if binders.len() == 1 {
9494
vars
9595
} else {
96-
format!("({})", vars)
96+
format!("({vars})")
9797
}
9898
}
9999

@@ -153,7 +153,7 @@ pub(crate) fn convert_let_else_to_match(acc: &mut Assists, ctx: &AssistContext<'
153153

154154
let only_expr = let_else_block.statements().next().is_none();
155155
let branch2 = match &let_else_block.tail_expr() {
156-
Some(tail) if only_expr => format!("{},", tail.syntax().text()),
156+
Some(tail) if only_expr => format!("{tail},"),
157157
_ => let_else_block.syntax().text().to_string(),
158158
};
159159
let replace = if binders.is_empty() {

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

+7-1
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,13 @@ fn edit_field_references(
226226
}
227227

228228
fn generate_names(fields: impl Iterator<Item = ast::TupleField>) -> Vec<ast::Name> {
229-
fields.enumerate().map(|(i, _)| ast::make::name(&format!("field{}", i + 1))).collect()
229+
fields
230+
.enumerate()
231+
.map(|(i, _)| {
232+
let idx = i + 1;
233+
ast::make::name(&format!("field{idx}"))
234+
})
235+
.collect()
230236
}
231237

232238
#[cfg(test)]

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

+5-5
Original file line numberDiff line numberDiff line change
@@ -58,16 +58,16 @@ pub(crate) fn convert_two_arm_bool_match_to_matches_macro(
5858
target_range,
5959
|builder| {
6060
let mut arm_str = String::new();
61-
if let Some(ref pat) = first_arm.pat() {
61+
if let Some(pat) = &first_arm.pat() {
6262
arm_str += &pat.to_string();
6363
}
64-
if let Some(ref guard) = first_arm.guard() {
65-
arm_str += &format!(" {}", &guard.to_string());
64+
if let Some(guard) = &first_arm.guard() {
65+
arm_str += &format!(" {guard}");
6666
}
6767
if invert_matches {
68-
builder.replace(target_range, format!("!matches!({}, {})", expr, arm_str));
68+
builder.replace(target_range, format!("!matches!({expr}, {arm_str})"));
6969
} else {
70-
builder.replace(target_range, format!("matches!({}, {})", expr, arm_str));
70+
builder.replace(target_range, format!("matches!({expr}, {arm_str})"));
7171
}
7272
},
7373
)

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

+6-6
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ fn generate_name(
133133
_usages: &Option<UsageSearchResult>,
134134
) -> String {
135135
// FIXME: detect if name already used
136-
format!("_{}", index)
136+
format!("_{index}")
137137
}
138138

139139
enum RefType {
@@ -168,12 +168,12 @@ fn edit_tuple_assignment(
168168
let add_cursor = |text: &str| {
169169
// place cursor on first tuple item
170170
let first_tuple = &data.field_names[0];
171-
text.replacen(first_tuple, &format!("$0{}", first_tuple), 1)
171+
text.replacen(first_tuple, &format!("$0{first_tuple}"), 1)
172172
};
173173

174174
// with sub_pattern: keep original tuple and add subpattern: `tup @ (_0, _1)`
175175
if in_sub_pattern {
176-
let text = format!(" @ {}", tuple_pat);
176+
let text = format!(" @ {tuple_pat}");
177177
match ctx.config.snippet_cap {
178178
Some(cap) => {
179179
let snip = add_cursor(&text);
@@ -314,9 +314,9 @@ struct RefData {
314314
impl RefData {
315315
fn format(&self, field_name: &str) -> String {
316316
match (self.needs_deref, self.needs_parentheses) {
317-
(true, true) => format!("(*{})", field_name),
318-
(true, false) => format!("*{}", field_name),
319-
(false, true) => format!("({})", field_name),
317+
(true, true) => format!("(*{field_name})"),
318+
(true, false) => format!("*{field_name}"),
319+
(false, true) => format!("({field_name})"),
320320
(false, false) => field_name.to_string(),
321321
}
322322
}

0 commit comments

Comments
 (0)