Skip to content

Commit b069aac

Browse files
authored
Inline format arguments for easier reading (#5881)
* Inline format arguments for easier reading Code becomes shorter and often easier to read when format args are inlined. Note that I skipped the mixed cases to make it more straightforward (could be done separatelly). Also, there are two FIXME comments - for some reasons inlining makes format string exceed 100 char line width and crash. ``` cargo clippy --workspace --allow-dirty --fix --benches --tests --bins -- -A clippy::all -W clippy::uninlined_format_args ``` * address feedback
1 parent e86c2ba commit b069aac

38 files changed

+183
-223
lines changed

Diff for: src/attr.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ impl Rewrite for ast::MetaItem {
308308
// See #2479 for example.
309309
let value = rewrite_literal(context, lit.as_token_lit(), lit.span, lit_shape)
310310
.unwrap_or_else(|| context.snippet(lit.span).to_owned());
311-
format!("{} = {}", path, value)
311+
format!("{path} = {value}")
312312
}
313313
})
314314
}
@@ -342,7 +342,7 @@ impl Rewrite for ast::Attribute {
342342
let literal_str = literal.as_str();
343343
let doc_comment_formatter =
344344
DocCommentFormatter::new(literal_str, comment_style);
345-
let doc_comment = format!("{}", doc_comment_formatter);
345+
let doc_comment = format!("{doc_comment_formatter}");
346346
return rewrite_doc_comment(
347347
&doc_comment,
348348
shape.comment(context.config),
@@ -406,9 +406,9 @@ impl Rewrite for [ast::Attribute] {
406406
0,
407407
)?;
408408
let comment = if comment.is_empty() {
409-
format!("\n{}", mlb)
409+
format!("\n{mlb}")
410410
} else {
411-
format!("{}{}\n{}", mla, comment, mlb)
411+
format!("{mla}{comment}\n{mlb}")
412412
};
413413
result.push_str(&comment);
414414
result.push_str(&shape.indent.to_string(context.config));

Diff for: src/attr/doc_comment.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,15 @@ impl Display for DocCommentFormatter<'_> {
2020

2121
// Handle `#[doc = ""]`.
2222
if lines.peek().is_none() {
23-
return write!(formatter, "{}", opener);
23+
return write!(formatter, "{opener}");
2424
}
2525

2626
while let Some(line) = lines.next() {
2727
let is_last_line = lines.peek().is_none();
2828
if is_last_line {
29-
write!(formatter, "{}{}", opener, line)?;
29+
write!(formatter, "{opener}{line}")?;
3030
} else {
31-
writeln!(formatter, "{}{}", opener, line)?;
31+
writeln!(formatter, "{opener}{line}")?;
3232
}
3333
}
3434
Ok(())

Diff for: src/bin/main.rs

+8-11
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ fn main() {
3838
let exit_code = match execute(&opts) {
3939
Ok(code) => code,
4040
Err(e) => {
41-
eprintln!("{:#}", e);
41+
eprintln!("{e:#}");
4242
1
4343
}
4444
};
@@ -284,7 +284,7 @@ fn format_string(input: String, options: GetOptsOptions) -> Result<i32> {
284284
for f in config.file_lines().files() {
285285
match *f {
286286
FileName::Stdin => {}
287-
_ => eprintln!("Warning: Extra file listed in file_lines option '{}'", f),
287+
_ => eprintln!("Warning: Extra file listed in file_lines option '{f}'"),
288288
}
289289
}
290290

@@ -380,7 +380,7 @@ fn format_and_emit_report<T: Write>(session: &mut Session<'_, T>, input: Input)
380380
}
381381
}
382382
Err(msg) => {
383-
eprintln!("Error writing files: {}", msg);
383+
eprintln!("Error writing files: {msg}");
384384
session.add_operational_error();
385385
}
386386
}
@@ -403,12 +403,9 @@ fn print_usage_to_stdout(opts: &Options, reason: &str) {
403403
let sep = if reason.is_empty() {
404404
String::new()
405405
} else {
406-
format!("{}\n\n", reason)
406+
format!("{reason}\n\n")
407407
};
408-
let msg = format!(
409-
"{}Format Rust code\n\nusage: rustfmt [options] <file>...",
410-
sep
411-
);
408+
let msg = format!("{sep}Format Rust code\n\nusage: rustfmt [options] <file>...");
412409
println!("{}", opts.usage(&msg));
413410
}
414411

@@ -442,7 +439,7 @@ fn print_version() {
442439
include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
443440
);
444441

445-
println!("rustfmt {}", version_info);
442+
println!("rustfmt {version_info}");
446443
}
447444

448445
fn determine_operation(matches: &Matches) -> Result<Operation, OperationError> {
@@ -647,9 +644,9 @@ impl GetOptsOptions {
647644
match *f {
648645
FileName::Real(ref f) if files.contains(f) => {}
649646
FileName::Real(_) => {
650-
eprintln!("Warning: Extra file listed in file_lines option '{}'", f)
647+
eprintln!("Warning: Extra file listed in file_lines option '{f}'")
651648
}
652-
FileName::Stdin => eprintln!("Warning: Not a file '{}'", f),
649+
FileName::Stdin => eprintln!("Warning: Not a file '{f}'"),
653650
}
654651
}
655652
}

Diff for: src/cargo-fmt/main.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -200,14 +200,13 @@ fn convert_message_format_to_rustfmt_args(
200200
}
201201
"human" => Ok(()),
202202
_ => Err(format!(
203-
"invalid --message-format value: {}. Allowed values are: short|json|human",
204-
message_format
203+
"invalid --message-format value: {message_format}. Allowed values are: short|json|human"
205204
)),
206205
}
207206
}
208207

209208
fn print_usage_to_stderr(reason: &str) {
210-
eprintln!("{}", reason);
209+
eprintln!("{reason}");
211210
let app = Opts::command();
212211
app.after_help("")
213212
.write_help(&mut io::stderr())
@@ -460,7 +459,7 @@ fn get_targets_with_hitlist(
460459
let package = workspace_hitlist.iter().next().unwrap();
461460
Err(io::Error::new(
462461
io::ErrorKind::InvalidInput,
463-
format!("package `{}` is not a member of the workspace", package),
462+
format!("package `{package}` is not a member of the workspace"),
464463
))
465464
}
466465
}
@@ -498,7 +497,7 @@ fn run_rustfmt(
498497

499498
if verbosity == Verbosity::Verbose {
500499
print!("rustfmt");
501-
print!(" --edition {}", edition);
500+
print!(" --edition {edition}");
502501
fmt_args.iter().for_each(|f| print!(" {}", f));
503502
files.iter().for_each(|f| print!(" {}", f.display()));
504503
println!();

Diff for: src/chains.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ impl Rewrite for ChainItem {
296296
rewrite_comment(comment, false, shape, context.config)?
297297
}
298298
};
299-
Some(format!("{}{}", rewrite, "?".repeat(self.tries)))
299+
Some(format!("{rewrite}{}", "?".repeat(self.tries)))
300300
}
301301
}
302302

Diff for: src/closures.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ fn rewrite_closure_with_block(
175175
shape,
176176
false,
177177
)?;
178-
Some(format!("{} {}", prefix, block))
178+
Some(format!("{prefix} {block}"))
179179
}
180180

181181
// Rewrite closure with a single expression without wrapping its body with block.
@@ -310,10 +310,7 @@ fn rewrite_closure_fn_decl(
310310
.tactic(tactic)
311311
.preserve_newline(true);
312312
let list_str = write_list(&item_vec, &fmt)?;
313-
let mut prefix = format!(
314-
"{}{}{}{}{}|{}|",
315-
binder, const_, immovable, is_async, mover, list_str
316-
);
313+
let mut prefix = format!("{binder}{const_}{immovable}{is_async}{mover}|{list_str}|");
317314

318315
if !ret_str.is_empty() {
319316
if prefix.contains('\n') {

Diff for: src/comment.rs

+10-25
Original file line numberDiff line numberDiff line change
@@ -621,7 +621,7 @@ impl<'a> CommentRewrite<'a> {
621621
is_prev_line_multi_line: false,
622622
code_block_attr: None,
623623
item_block: None,
624-
comment_line_separator: format!("{}{}", indent_str, line_start),
624+
comment_line_separator: format!("{indent_str}{line_start}"),
625625
max_width,
626626
indent_str,
627627
fmt_indent: shape.indent,
@@ -951,7 +951,7 @@ const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### ";
951951
fn hide_sharp_behind_comment(s: &str) -> Cow<'_, str> {
952952
let s_trimmed = s.trim();
953953
if s_trimmed.starts_with("# ") || s_trimmed == "#" {
954-
Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
954+
Cow::from(format!("{RUSTFMT_CUSTOM_COMMENT_PREFIX}{s}"))
955955
} else {
956956
Cow::from(s)
957957
}
@@ -1035,7 +1035,7 @@ pub(crate) fn recover_missing_comment_in_span(
10351035
} else {
10361036
Cow::from(" ")
10371037
};
1038-
Some(format!("{}{}", sep, missing_comment))
1038+
Some(format!("{sep}{missing_comment}"))
10391039
}
10401040
}
10411041

@@ -1832,8 +1832,7 @@ fn remove_comment_header(comment: &str) -> &str {
18321832
} else {
18331833
assert!(
18341834
comment.starts_with("/*"),
1835-
"string '{}' is not a comment",
1836-
comment
1835+
"string '{comment}' is not a comment"
18371836
);
18381837
&comment[2..comment.len() - 2]
18391838
}
@@ -2069,26 +2068,13 @@ fn main() {
20692068
expected_line_start: &str,
20702069
) {
20712070
let block = ItemizedBlock::new(test_input).unwrap();
2072-
assert_eq!(1, block.lines.len(), "test_input: {:?}", test_input);
2073-
assert_eq!(
2074-
expected_line, &block.lines[0],
2075-
"test_input: {:?}",
2076-
test_input
2077-
);
2078-
assert_eq!(
2079-
expected_indent, block.indent,
2080-
"test_input: {:?}",
2081-
test_input
2082-
);
2083-
assert_eq!(
2084-
expected_opener, &block.opener,
2085-
"test_input: {:?}",
2086-
test_input
2087-
);
2071+
assert_eq!(1, block.lines.len(), "test_input: {test_input:?}");
2072+
assert_eq!(expected_line, &block.lines[0], "test_input: {test_input:?}");
2073+
assert_eq!(expected_indent, block.indent, "test_input: {test_input:?}");
2074+
assert_eq!(expected_opener, &block.opener, "test_input: {test_input:?}");
20882075
assert_eq!(
20892076
expected_line_start, &block.line_start,
2090-
"test_input: {:?}",
2091-
test_input
2077+
"test_input: {test_input:?}"
20922078
);
20932079
}
20942080

@@ -2145,8 +2131,7 @@ fn main() {
21452131
let maybe_block = ItemizedBlock::new(line);
21462132
assert!(
21472133
maybe_block.is_none(),
2148-
"The following line shouldn't be classified as a list item: {}",
2149-
line
2134+
"The following line shouldn't be classified as a list item: {line}"
21502135
);
21512136
}
21522137
}

Diff for: src/config/config_type.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -500,18 +500,16 @@ where
500500
// Stable with an unstable option
501501
(false, false, _) => {
502502
eprintln!(
503-
"Warning: can't set `{} = {:?}`, unstable features are only \
504-
available in nightly channel.",
505-
option_name, option_value
503+
"Warning: can't set `{option_name} = {option_value:?}`, unstable features are only \
504+
available in nightly channel."
506505
);
507506
false
508507
}
509508
// Stable with a stable option, but an unstable variant
510509
(false, true, false) => {
511510
eprintln!(
512-
"Warning: can't set `{} = {:?}`, unstable variants are only \
513-
available in nightly channel.",
514-
option_name, option_value
511+
"Warning: can't set `{option_name} = {option_value:?}`, unstable variants are only \
512+
available in nightly channel."
515513
);
516514
false
517515
}

Diff for: src/config/file_lines.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ impl fmt::Display for FileLines {
162162
None => write!(f, "None")?,
163163
Some(map) => {
164164
for (file_name, ranges) in map.iter() {
165-
write!(f, "{}: ", file_name)?;
165+
write!(f, "{file_name}: ")?;
166166
write!(f, "{}\n", ranges.iter().format(", "))?;
167167
}
168168
}

Diff for: src/config/macro_names.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,6 @@ mod test {
123123
#[test]
124124
fn macro_names_display() {
125125
let macro_names = MacroSelectors::from_str(r#"["foo", "*", "bar"]"#).unwrap();
126-
assert_eq!(format!("{}", macro_names), "foo, *, bar");
126+
assert_eq!(format!("{macro_names}"), "foo, *, bar");
127127
}
128128
}

Diff for: src/config/mod.rs

+6-9
Original file line numberDiff line numberDiff line change
@@ -216,8 +216,8 @@ impl Config {
216216
let required_version = self.required_version();
217217
if version != required_version {
218218
println!(
219-
"Error: rustfmt version ({}) doesn't match the required version ({})",
220-
version, required_version,
219+
"Error: rustfmt version ({version}) doesn't match the required version \
220+
({required_version})"
221221
);
222222
return false;
223223
}
@@ -310,20 +310,20 @@ impl Config {
310310
.ok_or_else(|| String::from("Parsed config was not table"))?;
311311
for key in table.keys() {
312312
if !Config::is_valid_name(key) {
313-
let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
313+
let msg = &format!("Warning: Unknown configuration option `{key}`\n");
314314
err.push_str(msg)
315315
}
316316
}
317317
match parsed.try_into() {
318318
Ok(parsed_config) => {
319319
if !err.is_empty() {
320-
eprint!("{}", err);
320+
eprint!("{err}");
321321
}
322322
Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
323323
}
324324
Err(e) => {
325325
err.push_str("Error: Decoding config file failed:\n");
326-
err.push_str(format!("{}\n", e).as_str());
326+
err.push_str(format!("{e}\n").as_str());
327327
err.push_str("Please check your config file.");
328328
Err(err)
329329
}
@@ -563,10 +563,7 @@ mod test {
563563
let toml = used_options.to_toml().unwrap();
564564
assert_eq!(
565565
toml,
566-
format!(
567-
"merge_derives = {}\nskip_children = {}\n",
568-
merge_derives, skip_children,
569-
)
566+
format!("merge_derives = {merge_derives}\nskip_children = {skip_children}\n",)
570567
);
571568
}
572569

Diff for: src/config/options.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ pub struct WidthHeuristics {
243243

244244
impl fmt::Display for WidthHeuristics {
245245
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246-
write!(f, "{:?}", self)
246+
write!(f, "{self:?}")
247247
}
248248
}
249249

Diff for: src/emitter.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,6 @@ pub(crate) trait Emitter {
4747
fn ensure_real_path(filename: &FileName) -> &Path {
4848
match *filename {
4949
FileName::Real(ref path) => path,
50-
_ => panic!("cannot format `{}` and emit to files", filename),
50+
_ => panic!("cannot format `{filename}` and emit to files"),
5151
}
5252
}

Diff for: src/emitter/checkstyle.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ pub(crate) fn output_checkstyle_file<T>(
4343
where
4444
T: Write,
4545
{
46-
write!(writer, r#"<file name="{}">"#, filename)?;
46+
write!(writer, r#"<file name="{filename}">"#)?;
4747
for mismatch in diff {
4848
let begin_line = mismatch.line_number;
4949
let mut current_line;
@@ -82,7 +82,7 @@ mod tests {
8282
);
8383
assert_eq!(
8484
&writer[..],
85-
format!(r#"<file name="{}"></file>"#, file_name).as_bytes()
85+
format!(r#"<file name="{file_name}"></file>"#).as_bytes()
8686
);
8787
}
8888

Diff for: src/emitter/checkstyle/xml.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ impl<'a> Display for XmlEscaped<'a> {
1313
'"' => write!(formatter, "&quot;"),
1414
'\'' => write!(formatter, "&apos;"),
1515
'&' => write!(formatter, "&amp;"),
16-
_ => write!(formatter, "{}", char),
16+
_ => write!(formatter, "{char}"),
1717
}?;
1818
}
1919

0 commit comments

Comments
 (0)