mirror of
https://github.com/rust-lang/rust.git
synced 2024-11-26 08:44:35 +00:00
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
This commit is contained in:
parent
e86c2ba545
commit
b069aac44d
@ -308,7 +308,7 @@ impl Rewrite for ast::MetaItem {
|
||||
// See #2479 for example.
|
||||
let value = rewrite_literal(context, lit.as_token_lit(), lit.span, lit_shape)
|
||||
.unwrap_or_else(|| context.snippet(lit.span).to_owned());
|
||||
format!("{} = {}", path, value)
|
||||
format!("{path} = {value}")
|
||||
}
|
||||
})
|
||||
}
|
||||
@ -342,7 +342,7 @@ impl Rewrite for ast::Attribute {
|
||||
let literal_str = literal.as_str();
|
||||
let doc_comment_formatter =
|
||||
DocCommentFormatter::new(literal_str, comment_style);
|
||||
let doc_comment = format!("{}", doc_comment_formatter);
|
||||
let doc_comment = format!("{doc_comment_formatter}");
|
||||
return rewrite_doc_comment(
|
||||
&doc_comment,
|
||||
shape.comment(context.config),
|
||||
@ -406,9 +406,9 @@ impl Rewrite for [ast::Attribute] {
|
||||
0,
|
||||
)?;
|
||||
let comment = if comment.is_empty() {
|
||||
format!("\n{}", mlb)
|
||||
format!("\n{mlb}")
|
||||
} else {
|
||||
format!("{}{}\n{}", mla, comment, mlb)
|
||||
format!("{mla}{comment}\n{mlb}")
|
||||
};
|
||||
result.push_str(&comment);
|
||||
result.push_str(&shape.indent.to_string(context.config));
|
||||
|
@ -20,15 +20,15 @@ impl Display for DocCommentFormatter<'_> {
|
||||
|
||||
// Handle `#[doc = ""]`.
|
||||
if lines.peek().is_none() {
|
||||
return write!(formatter, "{}", opener);
|
||||
return write!(formatter, "{opener}");
|
||||
}
|
||||
|
||||
while let Some(line) = lines.next() {
|
||||
let is_last_line = lines.peek().is_none();
|
||||
if is_last_line {
|
||||
write!(formatter, "{}{}", opener, line)?;
|
||||
write!(formatter, "{opener}{line}")?;
|
||||
} else {
|
||||
writeln!(formatter, "{}{}", opener, line)?;
|
||||
writeln!(formatter, "{opener}{line}")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
@ -38,7 +38,7 @@ fn main() {
|
||||
let exit_code = match execute(&opts) {
|
||||
Ok(code) => code,
|
||||
Err(e) => {
|
||||
eprintln!("{:#}", e);
|
||||
eprintln!("{e:#}");
|
||||
1
|
||||
}
|
||||
};
|
||||
@ -284,7 +284,7 @@ fn format_string(input: String, options: GetOptsOptions) -> Result<i32> {
|
||||
for f in config.file_lines().files() {
|
||||
match *f {
|
||||
FileName::Stdin => {}
|
||||
_ => eprintln!("Warning: Extra file listed in file_lines option '{}'", f),
|
||||
_ => eprintln!("Warning: Extra file listed in file_lines option '{f}'"),
|
||||
}
|
||||
}
|
||||
|
||||
@ -380,7 +380,7 @@ fn format_and_emit_report<T: Write>(session: &mut Session<'_, T>, input: Input)
|
||||
}
|
||||
}
|
||||
Err(msg) => {
|
||||
eprintln!("Error writing files: {}", msg);
|
||||
eprintln!("Error writing files: {msg}");
|
||||
session.add_operational_error();
|
||||
}
|
||||
}
|
||||
@ -403,12 +403,9 @@ fn print_usage_to_stdout(opts: &Options, reason: &str) {
|
||||
let sep = if reason.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("{}\n\n", reason)
|
||||
format!("{reason}\n\n")
|
||||
};
|
||||
let msg = format!(
|
||||
"{}Format Rust code\n\nusage: rustfmt [options] <file>...",
|
||||
sep
|
||||
);
|
||||
let msg = format!("{sep}Format Rust code\n\nusage: rustfmt [options] <file>...");
|
||||
println!("{}", opts.usage(&msg));
|
||||
}
|
||||
|
||||
@ -442,7 +439,7 @@ fn print_version() {
|
||||
include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
|
||||
);
|
||||
|
||||
println!("rustfmt {}", version_info);
|
||||
println!("rustfmt {version_info}");
|
||||
}
|
||||
|
||||
fn determine_operation(matches: &Matches) -> Result<Operation, OperationError> {
|
||||
@ -647,9 +644,9 @@ impl GetOptsOptions {
|
||||
match *f {
|
||||
FileName::Real(ref f) if files.contains(f) => {}
|
||||
FileName::Real(_) => {
|
||||
eprintln!("Warning: Extra file listed in file_lines option '{}'", f)
|
||||
eprintln!("Warning: Extra file listed in file_lines option '{f}'")
|
||||
}
|
||||
FileName::Stdin => eprintln!("Warning: Not a file '{}'", f),
|
||||
FileName::Stdin => eprintln!("Warning: Not a file '{f}'"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -200,14 +200,13 @@ fn convert_message_format_to_rustfmt_args(
|
||||
}
|
||||
"human" => Ok(()),
|
||||
_ => Err(format!(
|
||||
"invalid --message-format value: {}. Allowed values are: short|json|human",
|
||||
message_format
|
||||
"invalid --message-format value: {message_format}. Allowed values are: short|json|human"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_usage_to_stderr(reason: &str) {
|
||||
eprintln!("{}", reason);
|
||||
eprintln!("{reason}");
|
||||
let app = Opts::command();
|
||||
app.after_help("")
|
||||
.write_help(&mut io::stderr())
|
||||
@ -460,7 +459,7 @@ fn get_targets_with_hitlist(
|
||||
let package = workspace_hitlist.iter().next().unwrap();
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("package `{}` is not a member of the workspace", package),
|
||||
format!("package `{package}` is not a member of the workspace"),
|
||||
))
|
||||
}
|
||||
}
|
||||
@ -498,7 +497,7 @@ fn run_rustfmt(
|
||||
|
||||
if verbosity == Verbosity::Verbose {
|
||||
print!("rustfmt");
|
||||
print!(" --edition {}", edition);
|
||||
print!(" --edition {edition}");
|
||||
fmt_args.iter().for_each(|f| print!(" {}", f));
|
||||
files.iter().for_each(|f| print!(" {}", f.display()));
|
||||
println!();
|
||||
|
@ -296,7 +296,7 @@ impl Rewrite for ChainItem {
|
||||
rewrite_comment(comment, false, shape, context.config)?
|
||||
}
|
||||
};
|
||||
Some(format!("{}{}", rewrite, "?".repeat(self.tries)))
|
||||
Some(format!("{rewrite}{}", "?".repeat(self.tries)))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -175,7 +175,7 @@ fn rewrite_closure_with_block(
|
||||
shape,
|
||||
false,
|
||||
)?;
|
||||
Some(format!("{} {}", prefix, block))
|
||||
Some(format!("{prefix} {block}"))
|
||||
}
|
||||
|
||||
// Rewrite closure with a single expression without wrapping its body with block.
|
||||
@ -310,10 +310,7 @@ fn rewrite_closure_fn_decl(
|
||||
.tactic(tactic)
|
||||
.preserve_newline(true);
|
||||
let list_str = write_list(&item_vec, &fmt)?;
|
||||
let mut prefix = format!(
|
||||
"{}{}{}{}{}|{}|",
|
||||
binder, const_, immovable, is_async, mover, list_str
|
||||
);
|
||||
let mut prefix = format!("{binder}{const_}{immovable}{is_async}{mover}|{list_str}|");
|
||||
|
||||
if !ret_str.is_empty() {
|
||||
if prefix.contains('\n') {
|
||||
|
@ -621,7 +621,7 @@ impl<'a> CommentRewrite<'a> {
|
||||
is_prev_line_multi_line: false,
|
||||
code_block_attr: None,
|
||||
item_block: None,
|
||||
comment_line_separator: format!("{}{}", indent_str, line_start),
|
||||
comment_line_separator: format!("{indent_str}{line_start}"),
|
||||
max_width,
|
||||
indent_str,
|
||||
fmt_indent: shape.indent,
|
||||
@ -951,7 +951,7 @@ const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### ";
|
||||
fn hide_sharp_behind_comment(s: &str) -> Cow<'_, str> {
|
||||
let s_trimmed = s.trim();
|
||||
if s_trimmed.starts_with("# ") || s_trimmed == "#" {
|
||||
Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
|
||||
Cow::from(format!("{RUSTFMT_CUSTOM_COMMENT_PREFIX}{s}"))
|
||||
} else {
|
||||
Cow::from(s)
|
||||
}
|
||||
@ -1035,7 +1035,7 @@ pub(crate) fn recover_missing_comment_in_span(
|
||||
} else {
|
||||
Cow::from(" ")
|
||||
};
|
||||
Some(format!("{}{}", sep, missing_comment))
|
||||
Some(format!("{sep}{missing_comment}"))
|
||||
}
|
||||
}
|
||||
|
||||
@ -1832,8 +1832,7 @@ fn remove_comment_header(comment: &str) -> &str {
|
||||
} else {
|
||||
assert!(
|
||||
comment.starts_with("/*"),
|
||||
"string '{}' is not a comment",
|
||||
comment
|
||||
"string '{comment}' is not a comment"
|
||||
);
|
||||
&comment[2..comment.len() - 2]
|
||||
}
|
||||
@ -2069,26 +2068,13 @@ fn main() {
|
||||
expected_line_start: &str,
|
||||
) {
|
||||
let block = ItemizedBlock::new(test_input).unwrap();
|
||||
assert_eq!(1, block.lines.len(), "test_input: {:?}", test_input);
|
||||
assert_eq!(
|
||||
expected_line, &block.lines[0],
|
||||
"test_input: {:?}",
|
||||
test_input
|
||||
);
|
||||
assert_eq!(
|
||||
expected_indent, block.indent,
|
||||
"test_input: {:?}",
|
||||
test_input
|
||||
);
|
||||
assert_eq!(
|
||||
expected_opener, &block.opener,
|
||||
"test_input: {:?}",
|
||||
test_input
|
||||
);
|
||||
assert_eq!(1, block.lines.len(), "test_input: {test_input:?}");
|
||||
assert_eq!(expected_line, &block.lines[0], "test_input: {test_input:?}");
|
||||
assert_eq!(expected_indent, block.indent, "test_input: {test_input:?}");
|
||||
assert_eq!(expected_opener, &block.opener, "test_input: {test_input:?}");
|
||||
assert_eq!(
|
||||
expected_line_start, &block.line_start,
|
||||
"test_input: {:?}",
|
||||
test_input
|
||||
"test_input: {test_input:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@ -2145,8 +2131,7 @@ fn main() {
|
||||
let maybe_block = ItemizedBlock::new(line);
|
||||
assert!(
|
||||
maybe_block.is_none(),
|
||||
"The following line shouldn't be classified as a list item: {}",
|
||||
line
|
||||
"The following line shouldn't be classified as a list item: {line}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -500,18 +500,16 @@ where
|
||||
// Stable with an unstable option
|
||||
(false, false, _) => {
|
||||
eprintln!(
|
||||
"Warning: can't set `{} = {:?}`, unstable features are only \
|
||||
available in nightly channel.",
|
||||
option_name, option_value
|
||||
"Warning: can't set `{option_name} = {option_value:?}`, unstable features are only \
|
||||
available in nightly channel."
|
||||
);
|
||||
false
|
||||
}
|
||||
// Stable with a stable option, but an unstable variant
|
||||
(false, true, false) => {
|
||||
eprintln!(
|
||||
"Warning: can't set `{} = {:?}`, unstable variants are only \
|
||||
available in nightly channel.",
|
||||
option_name, option_value
|
||||
"Warning: can't set `{option_name} = {option_value:?}`, unstable variants are only \
|
||||
available in nightly channel."
|
||||
);
|
||||
false
|
||||
}
|
||||
|
@ -162,7 +162,7 @@ impl fmt::Display for FileLines {
|
||||
None => write!(f, "None")?,
|
||||
Some(map) => {
|
||||
for (file_name, ranges) in map.iter() {
|
||||
write!(f, "{}: ", file_name)?;
|
||||
write!(f, "{file_name}: ")?;
|
||||
write!(f, "{}\n", ranges.iter().format(", "))?;
|
||||
}
|
||||
}
|
||||
|
@ -123,6 +123,6 @@ mod test {
|
||||
#[test]
|
||||
fn macro_names_display() {
|
||||
let macro_names = MacroSelectors::from_str(r#"["foo", "*", "bar"]"#).unwrap();
|
||||
assert_eq!(format!("{}", macro_names), "foo, *, bar");
|
||||
assert_eq!(format!("{macro_names}"), "foo, *, bar");
|
||||
}
|
||||
}
|
||||
|
@ -216,8 +216,8 @@ impl Config {
|
||||
let required_version = self.required_version();
|
||||
if version != required_version {
|
||||
println!(
|
||||
"Error: rustfmt version ({}) doesn't match the required version ({})",
|
||||
version, required_version,
|
||||
"Error: rustfmt version ({version}) doesn't match the required version \
|
||||
({required_version})"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
@ -310,20 +310,20 @@ impl Config {
|
||||
.ok_or_else(|| String::from("Parsed config was not table"))?;
|
||||
for key in table.keys() {
|
||||
if !Config::is_valid_name(key) {
|
||||
let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
|
||||
let msg = &format!("Warning: Unknown configuration option `{key}`\n");
|
||||
err.push_str(msg)
|
||||
}
|
||||
}
|
||||
match parsed.try_into() {
|
||||
Ok(parsed_config) => {
|
||||
if !err.is_empty() {
|
||||
eprint!("{}", err);
|
||||
eprint!("{err}");
|
||||
}
|
||||
Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
|
||||
}
|
||||
Err(e) => {
|
||||
err.push_str("Error: Decoding config file failed:\n");
|
||||
err.push_str(format!("{}\n", e).as_str());
|
||||
err.push_str(format!("{e}\n").as_str());
|
||||
err.push_str("Please check your config file.");
|
||||
Err(err)
|
||||
}
|
||||
@ -563,10 +563,7 @@ mod test {
|
||||
let toml = used_options.to_toml().unwrap();
|
||||
assert_eq!(
|
||||
toml,
|
||||
format!(
|
||||
"merge_derives = {}\nskip_children = {}\n",
|
||||
merge_derives, skip_children,
|
||||
)
|
||||
format!("merge_derives = {merge_derives}\nskip_children = {skip_children}\n",)
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -243,7 +243,7 @@ pub struct WidthHeuristics {
|
||||
|
||||
impl fmt::Display for WidthHeuristics {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{:?}", self)
|
||||
write!(f, "{self:?}")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -47,6 +47,6 @@ pub(crate) trait Emitter {
|
||||
fn ensure_real_path(filename: &FileName) -> &Path {
|
||||
match *filename {
|
||||
FileName::Real(ref path) => path,
|
||||
_ => panic!("cannot format `{}` and emit to files", filename),
|
||||
_ => panic!("cannot format `{filename}` and emit to files"),
|
||||
}
|
||||
}
|
||||
|
@ -43,7 +43,7 @@ pub(crate) fn output_checkstyle_file<T>(
|
||||
where
|
||||
T: Write,
|
||||
{
|
||||
write!(writer, r#"<file name="{}">"#, filename)?;
|
||||
write!(writer, r#"<file name="{filename}">"#)?;
|
||||
for mismatch in diff {
|
||||
let begin_line = mismatch.line_number;
|
||||
let mut current_line;
|
||||
@ -82,7 +82,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(
|
||||
&writer[..],
|
||||
format!(r#"<file name="{}"></file>"#, file_name).as_bytes()
|
||||
format!(r#"<file name="{file_name}"></file>"#).as_bytes()
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -13,7 +13,7 @@ impl<'a> Display for XmlEscaped<'a> {
|
||||
'"' => write!(formatter, """),
|
||||
'\'' => write!(formatter, "'"),
|
||||
'&' => write!(formatter, "&"),
|
||||
_ => write!(formatter, "{}", char),
|
||||
_ => write!(formatter, "{char}"),
|
||||
}?;
|
||||
}
|
||||
|
||||
|
@ -28,7 +28,7 @@ impl Emitter for DiffEmitter {
|
||||
|
||||
if has_diff {
|
||||
if self.config.print_misformatted_file_names() {
|
||||
writeln!(output, "{}", filename)?;
|
||||
writeln!(output, "{filename}")?;
|
||||
} else {
|
||||
print_diff(
|
||||
mismatch,
|
||||
@ -40,7 +40,7 @@ impl Emitter for DiffEmitter {
|
||||
// This occurs when the only difference between the original and formatted values
|
||||
// is the newline style. This happens because The make_diff function compares the
|
||||
// original and formatted values line by line, independent of line endings.
|
||||
writeln!(output, "Incorrect newline style in {}", filename)?;
|
||||
writeln!(output, "Incorrect newline style in {filename}")?;
|
||||
return Ok(EmitterResult { has_diff: true });
|
||||
}
|
||||
|
||||
@ -110,7 +110,7 @@ mod tests {
|
||||
|
||||
assert_eq!(
|
||||
String::from_utf8(writer).unwrap(),
|
||||
format!("{}\n{}\n", bin_file, lib_file),
|
||||
format!("{bin_file}\n{lib_file}\n"),
|
||||
)
|
||||
}
|
||||
|
||||
|
@ -96,7 +96,7 @@ impl JsonEmitter {
|
||||
});
|
||||
}
|
||||
self.mismatched_files.push(MismatchedFile {
|
||||
name: format!("{}", filename),
|
||||
name: format!("{filename}"),
|
||||
mismatches,
|
||||
});
|
||||
Ok(())
|
||||
@ -281,7 +281,7 @@ mod tests {
|
||||
}])
|
||||
.unwrap();
|
||||
assert_eq!(result.has_diff, true);
|
||||
assert_eq!(&writer[..], format!("{}\n", exp_json).as_bytes());
|
||||
assert_eq!(&writer[..], format!("{exp_json}\n").as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -341,6 +341,6 @@ mod tests {
|
||||
};
|
||||
|
||||
let exp_json = to_json_string(&vec![exp_bin, exp_lib]).unwrap();
|
||||
assert_eq!(&writer[..], format!("{}\n", exp_json).as_bytes());
|
||||
assert_eq!(&writer[..], format!("{exp_json}\n").as_bytes());
|
||||
}
|
||||
}
|
||||
|
@ -24,9 +24,9 @@ impl Emitter for StdoutEmitter {
|
||||
}: FormattedFile<'_>,
|
||||
) -> Result<EmitterResult, io::Error> {
|
||||
if self.verbosity != Verbosity::Quiet {
|
||||
writeln!(output, "{}:\n", filename)?;
|
||||
writeln!(output, "{filename}:\n")?;
|
||||
}
|
||||
write!(output, "{}", formatted_text)?;
|
||||
write!(output, "{formatted_text}")?;
|
||||
Ok(EmitterResult::default())
|
||||
}
|
||||
}
|
||||
|
57
src/expr.rs
57
src/expr.rs
@ -187,7 +187,7 @@ pub(crate) fn format_expr(
|
||||
Some(label) => format!(" {}", label.ident),
|
||||
None => String::new(),
|
||||
};
|
||||
Some(format!("continue{}", id_str))
|
||||
Some(format!("continue{id_str}"))
|
||||
}
|
||||
ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
|
||||
let id_str = match *opt_label {
|
||||
@ -196,9 +196,9 @@ pub(crate) fn format_expr(
|
||||
};
|
||||
|
||||
if let Some(ref expr) = *opt_expr {
|
||||
rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
|
||||
rewrite_unary_prefix(context, &format!("break{id_str} "), &**expr, shape)
|
||||
} else {
|
||||
Some(format!("break{}", id_str))
|
||||
Some(format!("break{id_str}"))
|
||||
}
|
||||
}
|
||||
ast::ExprKind::Yield(ref opt_expr) => {
|
||||
@ -309,7 +309,7 @@ pub(crate) fn format_expr(
|
||||
match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
|
||||
(Some(lhs), Some(rhs)) => {
|
||||
let sp_delim = if context.config.spaces_around_ranges() {
|
||||
format!(" {} ", delim)
|
||||
format!(" {delim} ")
|
||||
} else {
|
||||
default_sp_delim(Some(lhs), Some(rhs))
|
||||
};
|
||||
@ -324,7 +324,7 @@ pub(crate) fn format_expr(
|
||||
}
|
||||
(None, Some(rhs)) => {
|
||||
let sp_delim = if context.config.spaces_around_ranges() {
|
||||
format!("{} ", delim)
|
||||
format!("{delim} ")
|
||||
} else {
|
||||
default_sp_delim(None, Some(rhs))
|
||||
};
|
||||
@ -332,7 +332,7 @@ pub(crate) fn format_expr(
|
||||
}
|
||||
(Some(lhs), None) => {
|
||||
let sp_delim = if context.config.spaces_around_ranges() {
|
||||
format!(" {}", delim)
|
||||
format!(" {delim}")
|
||||
} else {
|
||||
default_sp_delim(Some(lhs), None)
|
||||
};
|
||||
@ -375,7 +375,7 @@ pub(crate) fn format_expr(
|
||||
};
|
||||
if let rw @ Some(_) = rewrite_single_line_block(
|
||||
context,
|
||||
format!("{}{}", "async ", mover).as_str(),
|
||||
format!("async {mover}").as_str(),
|
||||
block,
|
||||
Some(&expr.attrs),
|
||||
None,
|
||||
@ -386,9 +386,7 @@ pub(crate) fn format_expr(
|
||||
// 6 = `async `
|
||||
let budget = shape.width.saturating_sub(6);
|
||||
Some(format!(
|
||||
"{}{}{}",
|
||||
"async ",
|
||||
mover,
|
||||
"async {mover}{}",
|
||||
rewrite_block(
|
||||
block,
|
||||
Some(&expr.attrs),
|
||||
@ -460,7 +458,7 @@ fn rewrite_empty_block(
|
||||
}
|
||||
|
||||
if !block_contains_comment(context, block) && shape.width >= 2 {
|
||||
return Some(format!("{}{}{{}}", prefix, label_str));
|
||||
return Some(format!("{prefix}{label_str}{{}}"));
|
||||
}
|
||||
|
||||
// If a block contains only a single-line comment, then leave it on one line.
|
||||
@ -473,7 +471,7 @@ fn rewrite_empty_block(
|
||||
&& !comment_str.starts_with("//")
|
||||
&& comment_str.len() + 4 <= shape.width
|
||||
{
|
||||
return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
|
||||
return Some(format!("{prefix}{label_str}{{ {comment_str} }}"));
|
||||
}
|
||||
}
|
||||
|
||||
@ -520,7 +518,7 @@ fn rewrite_single_line_block(
|
||||
let expr_shape = shape.offset_left(last_line_width(prefix))?;
|
||||
let expr_str = block_expr.rewrite(context, expr_shape)?;
|
||||
let label_str = rewrite_label(label);
|
||||
let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
|
||||
let result = format!("{prefix}{label_str}{{ {expr_str} }}");
|
||||
if result.len() <= shape.width && !result.contains('\n') {
|
||||
return Some(result);
|
||||
}
|
||||
@ -1100,7 +1098,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
|
||||
result?
|
||||
};
|
||||
|
||||
let mut result = format!("{}{}", cond_str, block_str);
|
||||
let mut result = format!("{cond_str}{block_str}");
|
||||
|
||||
if let Some(else_block) = self.else_block {
|
||||
let shape = Shape::indented(shape.indent, context.config);
|
||||
@ -1160,8 +1158,7 @@ fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
|
||||
fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
|
||||
match rewrite_missing_comment(span, shape, context) {
|
||||
Some(ref comment) if !comment.is_empty() => Some(format!(
|
||||
"{indent}{}{indent}",
|
||||
comment,
|
||||
"{indent}{comment}{indent}",
|
||||
indent = shape.indent.to_string_with_newline(context.config)
|
||||
)),
|
||||
_ => None,
|
||||
@ -1478,7 +1475,7 @@ pub(crate) fn rewrite_paren(
|
||||
let subexpr_str = subexpr.rewrite(context, sub_shape)?;
|
||||
let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
|
||||
if fits_single_line {
|
||||
Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
|
||||
Some(format!("({pre_comment}{subexpr_str}{post_comment})"))
|
||||
} else {
|
||||
rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
|
||||
}
|
||||
@ -1542,7 +1539,7 @@ fn rewrite_index(
|
||||
// Return if index fits in a single line.
|
||||
match orig_index_rw {
|
||||
Some(ref index_str) if !index_str.contains('\n') => {
|
||||
return Some(format!("{}[{}]", expr_str, index_str));
|
||||
return Some(format!("{expr_str}[{index_str}]"));
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
@ -1565,7 +1562,7 @@ fn rewrite_index(
|
||||
indent.to_string_with_newline(context.config),
|
||||
new_index_str,
|
||||
)),
|
||||
(Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
|
||||
(Some(ref index_str), _) => Some(format!("{expr_str}[{index_str}]")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@ -1597,9 +1594,9 @@ fn rewrite_struct_lit<'a>(
|
||||
let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;
|
||||
|
||||
let has_base_or_rest = match struct_rest {
|
||||
ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)),
|
||||
ast::StructRest::None if fields.is_empty() => return Some(format!("{path_str} {{}}")),
|
||||
ast::StructRest::Rest(_) if fields.is_empty() => {
|
||||
return Some(format!("{} {{ .. }}", path_str));
|
||||
return Some(format!("{path_str} {{ .. }}"));
|
||||
}
|
||||
ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true,
|
||||
_ => false,
|
||||
@ -1690,7 +1687,7 @@ fn rewrite_struct_lit<'a>(
|
||||
|
||||
let fields_str =
|
||||
wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?;
|
||||
Some(format!("{} {{{}}}", path_str, fields_str))
|
||||
Some(format!("{path_str} {{{fields_str}}}"))
|
||||
|
||||
// FIXME if context.config.indent_style() == Visual, but we run out
|
||||
// of space, we should fall back to BlockIndent.
|
||||
@ -1720,7 +1717,7 @@ pub(crate) fn wrap_struct_field(
|
||||
))
|
||||
} else {
|
||||
// One liner or visual indent.
|
||||
Some(format!(" {} ", fields_str))
|
||||
Some(format!(" {fields_str} "))
|
||||
}
|
||||
} else {
|
||||
Some(format!(
|
||||
@ -1769,7 +1766,7 @@ pub(crate) fn rewrite_field(
|
||||
{
|
||||
Some(attrs_str + name)
|
||||
}
|
||||
Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
|
||||
Some(e) => Some(format!("{attrs_str}{name}{separator}{e}")),
|
||||
None => {
|
||||
let expr_offset = shape.indent.block_indent(context.config);
|
||||
let expr = field
|
||||
@ -1834,7 +1831,7 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
|
||||
.ends_with_newline(false);
|
||||
let list_str = write_list(&item_vec, &fmt)?;
|
||||
|
||||
Some(format!("({})", list_str))
|
||||
Some(format!("({list_str})"))
|
||||
}
|
||||
|
||||
pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
|
||||
@ -2076,7 +2073,7 @@ fn choose_rhs<R: Rewrite>(
|
||||
Some(ref new_str)
|
||||
if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
|
||||
{
|
||||
Some(format!(" {}", new_str))
|
||||
Some(format!(" {new_str}"))
|
||||
}
|
||||
_ => {
|
||||
// Expression did not fit on the same line as the identifier.
|
||||
@ -2093,21 +2090,21 @@ fn choose_rhs<R: Rewrite>(
|
||||
(Some(ref orig_rhs), Some(ref new_rhs))
|
||||
if !filtered_str_fits(&new_rhs, context.config.max_width(), new_shape) =>
|
||||
{
|
||||
Some(format!("{}{}", before_space_str, orig_rhs))
|
||||
Some(format!("{before_space_str}{orig_rhs}"))
|
||||
}
|
||||
(Some(ref orig_rhs), Some(ref new_rhs))
|
||||
if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
|
||||
{
|
||||
Some(format!("{}{}", new_indent_str, new_rhs))
|
||||
Some(format!("{new_indent_str}{new_rhs}"))
|
||||
}
|
||||
(None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
|
||||
(None, Some(ref new_rhs)) => Some(format!("{new_indent_str}{new_rhs}")),
|
||||
(None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
|
||||
let shape = shape.infinite_width();
|
||||
expr.rewrite(context, shape)
|
||||
.map(|s| format!("{}{}", before_space_str, s))
|
||||
}
|
||||
(None, None) => None,
|
||||
(Some(orig_rhs), _) => Some(format!("{}{}", before_space_str, orig_rhs)),
|
||||
(Some(orig_rhs), _) => Some(format!("{before_space_str}{orig_rhs}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -69,7 +69,7 @@ fn main() {
|
||||
.init();
|
||||
let opts = Opts::parse();
|
||||
if let Err(e) = run(opts) {
|
||||
println!("{}", e);
|
||||
println!("{e}");
|
||||
Opts::command()
|
||||
.print_help()
|
||||
.expect("cannot write to stdout");
|
||||
@ -113,7 +113,7 @@ fn run_rustfmt(files: &HashSet<String>, ranges: &[Range]) -> Result<(), FormatDi
|
||||
if !exit_status.success() {
|
||||
return Err(FormatDiffError::IoError(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("rustfmt failed with {}", exit_status),
|
||||
format!("rustfmt failed with {exit_status}"),
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
@ -129,12 +129,12 @@ fn scan_diff<R>(
|
||||
where
|
||||
R: io::Read,
|
||||
{
|
||||
let diff_pattern = format!(r"^\+\+\+\s(?:.*?/){{{}}}(\S*)", skip_prefix);
|
||||
let diff_pattern = format!(r"^\+\+\+\s(?:.*?/){{{skip_prefix}}}(\S*)");
|
||||
let diff_pattern = Regex::new(&diff_pattern).unwrap();
|
||||
|
||||
let lines_pattern = Regex::new(r"^@@.*\+(\d+)(,(\d+))?").unwrap();
|
||||
|
||||
let file_filter = Regex::new(&format!("^{}$", file_filter))?;
|
||||
let file_filter = Regex::new(&format!("^{file_filter}$"))?;
|
||||
|
||||
let mut current_file = None;
|
||||
|
||||
|
@ -296,7 +296,7 @@ impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
|
||||
Ok(ref result) if result.has_diff => report.add_diff(),
|
||||
Err(e) => {
|
||||
// Create a new error with path_str to help users see which files failed
|
||||
let err_msg = format!("{}: {}", path, e);
|
||||
let err_msg = format!("{path}: {e}");
|
||||
return Err(io::Error::new(e.kind(), err_msg).into());
|
||||
}
|
||||
_ => {}
|
||||
|
@ -43,7 +43,7 @@ fn git_diff(commits: &str) -> String {
|
||||
let mut cmd = Command::new("git");
|
||||
cmd.arg("diff");
|
||||
if commits != "0" {
|
||||
cmd.arg(format!("HEAD~{}", commits));
|
||||
cmd.arg(format!("HEAD~{commits}"));
|
||||
}
|
||||
let output = cmd.output().expect("Couldn't execute `git diff`");
|
||||
String::from_utf8_lossy(&output.stdout).into_owned()
|
||||
@ -108,7 +108,7 @@ fn check_uncommitted() {
|
||||
if !uncommitted.is_empty() {
|
||||
println!("Found untracked changes:");
|
||||
for f in &uncommitted {
|
||||
println!(" {}", f);
|
||||
println!(" {f}");
|
||||
}
|
||||
println!("Commit your work, or run with `-u`.");
|
||||
println!("Exiting.");
|
||||
|
@ -191,7 +191,7 @@ impl UseSegment {
|
||||
"crate" => UseSegmentKind::Crate(None),
|
||||
_ => {
|
||||
let mod_sep = if modsep { "::" } else { "" };
|
||||
UseSegmentKind::Ident(format!("{}{}", mod_sep, name), None)
|
||||
UseSegmentKind::Ident(format!("{mod_sep}{name}"), None)
|
||||
}
|
||||
};
|
||||
|
||||
@ -295,8 +295,8 @@ impl fmt::Display for UseSegmentKind {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
UseSegmentKind::Glob => write!(f, "*"),
|
||||
UseSegmentKind::Ident(ref s, Some(ref alias)) => write!(f, "{} as {}", s, alias),
|
||||
UseSegmentKind::Ident(ref s, None) => write!(f, "{}", s),
|
||||
UseSegmentKind::Ident(ref s, Some(ref alias)) => write!(f, "{s} as {alias}"),
|
||||
UseSegmentKind::Ident(ref s, None) => write!(f, "{s}"),
|
||||
UseSegmentKind::Slf(..) => write!(f, "self"),
|
||||
UseSegmentKind::Super(..) => write!(f, "super"),
|
||||
UseSegmentKind::Crate(..) => write!(f, "crate"),
|
||||
@ -306,7 +306,7 @@ impl fmt::Display for UseSegmentKind {
|
||||
if i != 0 {
|
||||
write!(f, ", ")?;
|
||||
}
|
||||
write!(f, "{}", item)?;
|
||||
write!(f, "{item}")?;
|
||||
}
|
||||
write!(f, "}}")
|
||||
}
|
||||
@ -319,7 +319,7 @@ impl fmt::Display for UseTree {
|
||||
if i != 0 {
|
||||
write!(f, "::")?;
|
||||
}
|
||||
write!(f, "{}", segment)?;
|
||||
write!(f, "{segment}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@ -1042,7 +1042,7 @@ fn rewrite_nested_use_tree(
|
||||
shape.indent.to_string(context.config)
|
||||
)
|
||||
} else {
|
||||
format!("{{{}}}", list_str)
|
||||
format!("{{{list_str}}}")
|
||||
};
|
||||
|
||||
Some(result)
|
||||
@ -1052,14 +1052,14 @@ impl Rewrite for UseSegment {
|
||||
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
|
||||
Some(match self.kind {
|
||||
UseSegmentKind::Ident(ref ident, Some(ref rename)) => {
|
||||
format!("{} as {}", ident, rename)
|
||||
format!("{ident} as {rename}")
|
||||
}
|
||||
UseSegmentKind::Ident(ref ident, None) => ident.clone(),
|
||||
UseSegmentKind::Slf(Some(ref rename)) => format!("self as {}", rename),
|
||||
UseSegmentKind::Slf(Some(ref rename)) => format!("self as {rename}"),
|
||||
UseSegmentKind::Slf(None) => "self".to_owned(),
|
||||
UseSegmentKind::Super(Some(ref rename)) => format!("super as {}", rename),
|
||||
UseSegmentKind::Super(Some(ref rename)) => format!("super as {rename}"),
|
||||
UseSegmentKind::Super(None) => "super".to_owned(),
|
||||
UseSegmentKind::Crate(Some(ref rename)) => format!("crate as {}", rename),
|
||||
UseSegmentKind::Crate(Some(ref rename)) => format!("crate as {rename}"),
|
||||
UseSegmentKind::Crate(None) => "crate".to_owned(),
|
||||
UseSegmentKind::Glob => "*".to_owned(),
|
||||
UseSegmentKind::List(ref use_tree_list) => rewrite_nested_use_tree(
|
||||
|
40
src/items.rs
40
src/items.rs
@ -470,7 +470,7 @@ impl<'a> FmtVisitor<'a> {
|
||||
&& self.block_indent.width() + fn_str.len() + 3 <= self.config.max_width()
|
||||
&& !last_line_contains_single_line_comment(fn_str)
|
||||
{
|
||||
return Some(format!("{} {{}}", fn_str));
|
||||
return Some(format!("{fn_str} {{}}"));
|
||||
}
|
||||
|
||||
if !self.config.fn_single_line() || !is_simple_block_stmt(&context, block, None) {
|
||||
@ -482,7 +482,7 @@ impl<'a> FmtVisitor<'a> {
|
||||
|
||||
let width = self.block_indent.width() + fn_str.len() + res.len() + 5;
|
||||
if !res.contains('\n') && width <= self.config.max_width() {
|
||||
Some(format!("{} {{ {} }}", fn_str, res))
|
||||
Some(format!("{fn_str} {{ {res} }}"))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@ -664,7 +664,7 @@ impl<'a> FmtVisitor<'a> {
|
||||
};
|
||||
|
||||
let variant_body = if let Some(ref expr) = field.disr_expr {
|
||||
let lhs = format!("{:1$} =", variant_body, pad_discrim_ident_to);
|
||||
let lhs = format!("{variant_body:pad_discrim_ident_to$} =");
|
||||
let ex = &*expr.value;
|
||||
rewrite_assign_rhs_with(
|
||||
&context,
|
||||
@ -827,7 +827,7 @@ pub(crate) fn format_impl(
|
||||
if generics.where_clause.predicates.len() == 1 {
|
||||
result.push(',');
|
||||
}
|
||||
result.push_str(&format!("{}{{{}}}", sep, sep));
|
||||
result.push_str(&format!("{sep}{{{sep}}}"));
|
||||
} else {
|
||||
result.push_str(" {}");
|
||||
}
|
||||
@ -1018,7 +1018,7 @@ fn rewrite_trait_ref(
|
||||
let shape = Shape::indented(offset + used_space, context.config);
|
||||
if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
|
||||
if !trait_ref_str.contains('\n') {
|
||||
return Some(format!(" {}{}", polarity_str, trait_ref_str));
|
||||
return Some(format!(" {polarity_str}{trait_ref_str}"));
|
||||
}
|
||||
}
|
||||
// We could not make enough space for trait_ref, so put it on new line.
|
||||
@ -1320,7 +1320,7 @@ impl<'a> Rewrite for TraitAliasBounds<'a> {
|
||||
shape.indent.to_string_with_newline(context.config)
|
||||
};
|
||||
|
||||
Some(format!("{}{}{}", generic_bounds_str, space, where_str))
|
||||
Some(format!("{generic_bounds_str}{space}{where_str}"))
|
||||
}
|
||||
}
|
||||
|
||||
@ -1337,7 +1337,7 @@ pub(crate) fn format_trait_alias(
|
||||
let g_shape = shape.offset_left(6)?.sub_width(2)?;
|
||||
let generics_str = rewrite_generics(context, alias, generics, g_shape)?;
|
||||
let vis_str = format_visibility(context, vis);
|
||||
let lhs = format!("{}trait {} =", vis_str, generics_str);
|
||||
let lhs = format!("{vis_str}trait {generics_str} =");
|
||||
// 1 = ";"
|
||||
let trait_alias_bounds = TraitAliasBounds {
|
||||
generic_bounds,
|
||||
@ -1374,7 +1374,7 @@ fn format_unit_struct(
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
Some(format!("{}{};", header_str, generics_str))
|
||||
Some(format!("{header_str}{generics_str};"))
|
||||
}
|
||||
|
||||
pub(crate) fn format_struct_struct(
|
||||
@ -1464,7 +1464,7 @@ pub(crate) fn format_struct_struct(
|
||||
&& items_str.len() <= one_line_budget
|
||||
&& !last_line_contains_single_line_comment(&items_str)
|
||||
{
|
||||
Some(format!("{} {} }}", result, items_str))
|
||||
Some(format!("{result} {items_str} }}"))
|
||||
} else {
|
||||
Some(format!(
|
||||
"{}\n{}{}\n{}}}",
|
||||
@ -1694,7 +1694,7 @@ pub(crate) fn rewrite_type_alias<'a, 'b>(
|
||||
rewrite_ty(rw_info, Some(bounds), ty_opt, vis)
|
||||
}?;
|
||||
match defaultness {
|
||||
ast::Defaultness::Default(..) => Some(format!("default {}", result)),
|
||||
ast::Defaultness::Default(..) => Some(format!("default {result}")),
|
||||
_ => Some(result),
|
||||
}
|
||||
}
|
||||
@ -1801,14 +1801,14 @@ fn rewrite_ty<R: Rewrite>(
|
||||
true,
|
||||
)?
|
||||
}
|
||||
_ => format!("{}=", result),
|
||||
_ => format!("{result}="),
|
||||
};
|
||||
|
||||
// 1 = `;`
|
||||
let shape = Shape::indented(indent, context.config).sub_width(1)?;
|
||||
rewrite_assign_rhs(context, lhs, &*ty, &RhsAssignKind::Ty, shape).map(|s| s + ";")
|
||||
} else {
|
||||
Some(format!("{};", result))
|
||||
Some(format!("{result};"))
|
||||
}
|
||||
}
|
||||
|
||||
@ -2017,7 +2017,7 @@ fn rewrite_static(
|
||||
let expr_lo = expr.span.lo();
|
||||
let comments_span = mk_sp(comments_lo, expr_lo);
|
||||
|
||||
let lhs = format!("{}{} =", prefix, ty_str);
|
||||
let lhs = format!("{prefix}{ty_str} =");
|
||||
|
||||
// 1 = ;
|
||||
let remaining_width = context.budget(offset.block_indent + 1);
|
||||
@ -2034,7 +2034,7 @@ fn rewrite_static(
|
||||
.and_then(|res| recover_comment_removed(res, static_parts.span, context))
|
||||
.map(|s| if s.ends_with(';') { s } else { s + ";" })
|
||||
} else {
|
||||
Some(format!("{}{};", prefix, ty_str))
|
||||
Some(format!("{prefix}{ty_str};"))
|
||||
}
|
||||
}
|
||||
|
||||
@ -2227,7 +2227,7 @@ fn rewrite_explicit_self(
|
||||
Some(combine_strs_with_missing_comments(
|
||||
context,
|
||||
param_attrs,
|
||||
&format!("&{} {}self", lifetime_str, mut_str),
|
||||
&format!("&{lifetime_str} {mut_str}self"),
|
||||
span,
|
||||
shape,
|
||||
!has_multiple_attr_lines,
|
||||
@ -2236,7 +2236,7 @@ fn rewrite_explicit_self(
|
||||
None => Some(combine_strs_with_missing_comments(
|
||||
context,
|
||||
param_attrs,
|
||||
&format!("&{}self", mut_str),
|
||||
&format!("&{mut_str}self"),
|
||||
span,
|
||||
shape,
|
||||
!has_multiple_attr_lines,
|
||||
@ -2906,7 +2906,7 @@ fn rewrite_where_clause_rfc_style(
|
||||
clause_shape.indent.to_string_with_newline(context.config)
|
||||
};
|
||||
|
||||
Some(format!("{}{}{}", where_keyword, clause_sep, preds_str))
|
||||
Some(format!("{where_keyword}{clause_sep}{preds_str}"))
|
||||
}
|
||||
|
||||
/// Rewrite `where` and comment around it.
|
||||
@ -2946,8 +2946,8 @@ fn rewrite_where_keyword(
|
||||
let newline_before_where = comment_separator(&comment_before, shape);
|
||||
let newline_after_where = comment_separator(&comment_after, clause_shape);
|
||||
let result = format!(
|
||||
"{}{}{}where{}{}",
|
||||
starting_newline, comment_before, newline_before_where, newline_after_where, comment_after
|
||||
"{starting_newline}{comment_before}{newline_before_where}where\
|
||||
{newline_after_where}{comment_after}"
|
||||
);
|
||||
let allow_single_line = where_clause_option.allow_single_line
|
||||
&& comment_before.is_empty()
|
||||
@ -3102,7 +3102,7 @@ fn rewrite_where_clause(
|
||||
preds_str
|
||||
))
|
||||
} else {
|
||||
Some(format!(" where {}", preds_str))
|
||||
Some(format!(" where {preds_str}"))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -103,7 +103,7 @@ fn rewrite_macro_name(
|
||||
format!("{}!", pprust::path_to_string(path))
|
||||
};
|
||||
match extra_ident {
|
||||
Some(ident) if ident.name != kw::Empty => format!("{} {}", name, ident),
|
||||
Some(ident) if ident.name != kw::Empty => format!("{name} {ident}"),
|
||||
_ => name,
|
||||
}
|
||||
}
|
||||
@ -214,14 +214,14 @@ fn rewrite_macro_inner(
|
||||
if ts.is_empty() && !has_comment {
|
||||
return match style {
|
||||
Delimiter::Parenthesis if position == MacroPosition::Item => {
|
||||
Some(format!("{}();", macro_name))
|
||||
Some(format!("{macro_name}();"))
|
||||
}
|
||||
Delimiter::Bracket if position == MacroPosition::Item => {
|
||||
Some(format!("{}[];", macro_name))
|
||||
Some(format!("{macro_name}[];"))
|
||||
}
|
||||
Delimiter::Parenthesis => Some(format!("{}()", macro_name)),
|
||||
Delimiter::Bracket => Some(format!("{}[]", macro_name)),
|
||||
Delimiter::Brace => Some(format!("{} {{}}", macro_name)),
|
||||
Delimiter::Parenthesis => Some(format!("{macro_name}()")),
|
||||
Delimiter::Bracket => Some(format!("{macro_name}[]")),
|
||||
Delimiter::Brace => Some(format!("{macro_name} {{}}")),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
}
|
||||
@ -321,7 +321,7 @@ fn rewrite_macro_inner(
|
||||
_ => "",
|
||||
};
|
||||
|
||||
Some(format!("{}{}", rewrite, comma))
|
||||
Some(format!("{rewrite}{comma}"))
|
||||
}
|
||||
}
|
||||
Delimiter::Brace => {
|
||||
@ -330,8 +330,8 @@ fn rewrite_macro_inner(
|
||||
// anything in between the braces (for now).
|
||||
let snippet = context.snippet(mac.span()).trim_start_matches(|c| c != '{');
|
||||
match trim_left_preserve_layout(snippet, shape.indent, context.config) {
|
||||
Some(macro_body) => Some(format!("{} {}", macro_name, macro_body)),
|
||||
None => Some(format!("{} {}", macro_name, snippet)),
|
||||
Some(macro_body) => Some(format!("{macro_name} {macro_body}")),
|
||||
None => Some(format!("{macro_name} {snippet}")),
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
@ -362,7 +362,7 @@ fn handle_vec_semi(
|
||||
&& lhs.len() + rhs.len() + total_overhead <= shape.width
|
||||
{
|
||||
// macro_name(lhs; rhs) or macro_name[lhs; rhs]
|
||||
Some(format!("{}{}{}; {}{}", macro_name, left, lhs, rhs, right))
|
||||
Some(format!("{macro_name}{left}{lhs}; {rhs}{right}"))
|
||||
} else {
|
||||
// macro_name(\nlhs;\nrhs\n) or macro_name[\nlhs;\nrhs\n]
|
||||
Some(format!(
|
||||
@ -596,8 +596,8 @@ fn delim_token_to_str(
|
||||
.block_indent(context.config)
|
||||
.to_string_with_newline(context.config);
|
||||
(
|
||||
format!("{}{}", lhs, nested_indent_str),
|
||||
format!("{}{}", indent_str, rhs),
|
||||
format!("{lhs}{nested_indent_str}"),
|
||||
format!("{indent_str}{rhs}"),
|
||||
)
|
||||
} else {
|
||||
(lhs.to_owned(), rhs.to_owned())
|
||||
@ -654,7 +654,7 @@ impl MacroArgKind {
|
||||
};
|
||||
|
||||
match *self {
|
||||
MacroArgKind::MetaVariable(ty, ref name) => Some(format!("${}:{}", name, ty)),
|
||||
MacroArgKind::MetaVariable(ty, ref name) => Some(format!("${name}:{ty}")),
|
||||
MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
|
||||
let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
|
||||
let another = another
|
||||
@ -663,14 +663,14 @@ impl MacroArgKind {
|
||||
.unwrap_or_else(|| "".to_owned());
|
||||
let repeat_tok = pprust::token_to_string(tok);
|
||||
|
||||
Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
|
||||
Some(format!("${lhs}{inner}{rhs}{another}{repeat_tok}"))
|
||||
}
|
||||
MacroArgKind::Delimited(delim_tok, ref args) => {
|
||||
rewrite_delimited_inner(delim_tok, args)
|
||||
.map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
|
||||
}
|
||||
MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
|
||||
MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
|
||||
MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{prefix}{sep} ")),
|
||||
MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{prefix}{inner}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -124,7 +124,7 @@ pub(crate) fn rewrite_match(
|
||||
if arms.is_empty() {
|
||||
let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
|
||||
if snippet.trim().is_empty() {
|
||||
Some(format!("match {} {{}}", cond_str))
|
||||
Some(format!("match {cond_str} {{}}"))
|
||||
} else {
|
||||
// Empty match with comments or inner attributes? We are not going to bother, sorry ;)
|
||||
Some(context.snippet(span).to_owned())
|
||||
@ -274,7 +274,7 @@ fn rewrite_match_arm(
|
||||
let lhs_str = combine_strs_with_missing_comments(
|
||||
context,
|
||||
&attrs_str,
|
||||
&format!("{}{}{}", pipe_str, pats_str, guard_str),
|
||||
&format!("{pipe_str}{pats_str}{guard_str}"),
|
||||
missing_span,
|
||||
shape,
|
||||
false,
|
||||
@ -543,7 +543,7 @@ fn rewrite_guard(
|
||||
if let Some(cond_shape) = cond_shape {
|
||||
if let Some(cond_str) = guard.rewrite(context, cond_shape) {
|
||||
if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
|
||||
return Some(format!(" if {}", cond_str));
|
||||
return Some(format!(" if {cond_str}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -234,8 +234,8 @@ where
|
||||
let rhs_result = rhs.rewrite(context, rhs_shape)?;
|
||||
let indent_str = rhs_shape.indent.to_string_with_newline(context.config);
|
||||
let infix_with_sep = match separator_place {
|
||||
SeparatorPlace::Back => format!("{}{}", infix, indent_str),
|
||||
SeparatorPlace::Front => format!("{}{}", indent_str, infix),
|
||||
SeparatorPlace::Back => format!("{infix}{indent_str}"),
|
||||
SeparatorPlace::Front => format!("{indent_str}{infix}"),
|
||||
};
|
||||
Some(format!(
|
||||
"{}{}{}{}",
|
||||
|
@ -331,8 +331,7 @@ impl LineRangeUtils for ParseSess {
|
||||
|
||||
debug_assert_eq!(
|
||||
lo.sf.name, hi.sf.name,
|
||||
"span crossed file boundary: lo: {:?}, hi: {:?}",
|
||||
lo, hi
|
||||
"span crossed file boundary: lo: {lo:?}, hi: {hi:?}"
|
||||
);
|
||||
|
||||
// in case the span starts with a newline, the line range is off by 1 without the
|
||||
|
@ -208,7 +208,7 @@ impl Rewrite for Pat {
|
||||
None => "",
|
||||
Some(_) => " ",
|
||||
};
|
||||
format!("{}{}{}", lhs_spacing, infix, rhs_spacing)
|
||||
format!("{lhs_spacing}{infix}{rhs_spacing}")
|
||||
} else {
|
||||
infix.to_owned()
|
||||
};
|
||||
@ -283,7 +283,7 @@ fn rewrite_struct_pat(
|
||||
let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;
|
||||
|
||||
if fields.is_empty() && !ellipsis {
|
||||
return Some(format!("{} {{}}", path_str));
|
||||
return Some(format!("{path_str} {{}}"));
|
||||
}
|
||||
|
||||
let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };
|
||||
@ -344,7 +344,7 @@ fn rewrite_struct_pat(
|
||||
|
||||
// ast::Pat doesn't have attrs so use &[]
|
||||
let fields_str = wrap_struct_field(context, &[], &fields_str, shape, v_shape, one_line_width)?;
|
||||
Some(format!("{} {{{}}}", path_str, fields_str))
|
||||
Some(format!("{path_str} {{{fields_str}}}"))
|
||||
}
|
||||
|
||||
impl Rewrite for PatField {
|
||||
@ -376,7 +376,7 @@ impl Rewrite for PatField {
|
||||
let id_str = rewrite_ident(context, self.ident);
|
||||
let one_line_width = id_str.len() + 2 + pat_str.len();
|
||||
let pat_and_id_str = if one_line_width <= shape.width {
|
||||
format!("{}: {}", id_str, pat_str)
|
||||
format!("{id_str}: {pat_str}")
|
||||
} else {
|
||||
format!(
|
||||
"{}:\n{}{}",
|
||||
|
@ -95,7 +95,7 @@ impl fmt::Display for ModifiedLines {
|
||||
)?;
|
||||
|
||||
for line in &chunk.lines {
|
||||
writeln!(f, "{}", line)?;
|
||||
writeln!(f, "{line}")?;
|
||||
}
|
||||
}
|
||||
|
||||
@ -166,12 +166,12 @@ impl OutputWriter {
|
||||
if let Some(color) = color {
|
||||
t.fg(color).unwrap();
|
||||
}
|
||||
writeln!(t, "{}", msg).unwrap();
|
||||
writeln!(t, "{msg}").unwrap();
|
||||
if color.is_some() {
|
||||
t.reset().unwrap();
|
||||
}
|
||||
}
|
||||
None => println!("{}", msg),
|
||||
None => println!("{msg}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -265,16 +265,15 @@ where
|
||||
for line in mismatch.lines {
|
||||
match line {
|
||||
DiffLine::Context(ref str) => {
|
||||
writer.writeln(&format!(" {}{}", str, line_terminator), None)
|
||||
writer.writeln(&format!(" {str}{line_terminator}"), None)
|
||||
}
|
||||
DiffLine::Expected(ref str) => writer.writeln(
|
||||
&format!("+{}{}", str, line_terminator),
|
||||
&format!("+{str}{line_terminator}"),
|
||||
Some(term::color::GREEN),
|
||||
),
|
||||
DiffLine::Resulting(ref str) => writer.writeln(
|
||||
&format!("-{}{}", str, line_terminator),
|
||||
Some(term::color::RED),
|
||||
),
|
||||
DiffLine::Resulting(ref str) => {
|
||||
writer.writeln(&format!("-{str}{line_terminator}"), Some(term::color::RED))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -105,7 +105,7 @@ pub(crate) fn is_skip_attr(segments: &[ast::PathSegment]) -> bool {
|
||||
|
||||
fn get_skip_names(kind: &str, attrs: &[ast::Attribute]) -> Vec<String> {
|
||||
let mut skip_names = vec![];
|
||||
let path = format!("{}::{}::{}", RUSTFMT, SKIP, kind);
|
||||
let path = format!("{RUSTFMT}::{SKIP}::{kind}");
|
||||
for attr in attrs {
|
||||
// rustc_ast::ast::Path is implemented partialEq
|
||||
// but it is designed for segments.len() == 1
|
||||
|
@ -62,7 +62,7 @@ where
|
||||
fn ensure_real_path(filename: &FileName) -> &Path {
|
||||
match *filename {
|
||||
FileName::Real(ref path) => path,
|
||||
_ => panic!("cannot format `{}` and emit to files", filename),
|
||||
_ => panic!("cannot format `{filename}` and emit to files"),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -233,13 +233,11 @@ impl ConfigCodeBlock {
|
||||
Some(ConfigurationSection::ConfigName(name)) => {
|
||||
assert!(
|
||||
Config::is_valid_name(&name),
|
||||
"an unknown configuration option was found: {}",
|
||||
name
|
||||
"an unknown configuration option was found: {name}"
|
||||
);
|
||||
assert!(
|
||||
hash_set.remove(&name),
|
||||
"multiple configuration guides found for option {}",
|
||||
name
|
||||
"multiple configuration guides found for option {name}"
|
||||
);
|
||||
code_block.set_config_name(Some(name));
|
||||
}
|
||||
@ -266,7 +264,7 @@ fn configuration_snippet_tests() {
|
||||
|
||||
// Display results.
|
||||
println!("Ran {} configurations tests.", blocks.len());
|
||||
assert_eq!(failures, 0, "{} configurations tests failed", failures);
|
||||
assert_eq!(failures, 0, "{failures} configurations tests failed");
|
||||
}
|
||||
|
||||
// Read Configurations.md and build a `Vec` of `ConfigCodeBlock` structs with one
|
||||
@ -289,7 +287,7 @@ fn get_code_blocks() -> Vec<ConfigCodeBlock> {
|
||||
|
||||
for name in hash_set {
|
||||
if !Config::is_hidden_option(&name) {
|
||||
panic!("{} does not have a configuration guide", name);
|
||||
panic!("{name} does not have a configuration guide");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -203,8 +203,8 @@ fn coverage_tests() {
|
||||
let files = get_test_files(Path::new("tests/coverage/source"), true);
|
||||
let (_reports, count, fails) = check_files(files, &None);
|
||||
|
||||
println!("Ran {} tests in coverage mode.", count);
|
||||
assert_eq!(fails, 0, "{} tests failed", fails);
|
||||
println!("Ran {count} tests in coverage mode.");
|
||||
assert_eq!(fails, 0, "{fails} tests failed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -396,8 +396,8 @@ fn self_tests() {
|
||||
let mut warnings = 0;
|
||||
|
||||
// Display results.
|
||||
println!("Ran {} self tests.", count);
|
||||
assert_eq!(fails, 0, "{} self tests failed", fails);
|
||||
println!("Ran {count} self tests.");
|
||||
assert_eq!(fails, 0, "{fails} self tests failed");
|
||||
|
||||
for format_report in reports {
|
||||
println!(
|
||||
@ -407,11 +407,7 @@ fn self_tests() {
|
||||
warnings += format_report.warning_count();
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
warnings, 0,
|
||||
"Rustfmt's code generated {} warnings",
|
||||
warnings
|
||||
);
|
||||
assert_eq!(warnings, 0, "Rustfmt's code generated {warnings} warnings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -606,7 +602,7 @@ fn stdin_handles_mod_inner_ignore_attr() {
|
||||
fn format_lines_errors_are_reported() {
|
||||
init_log();
|
||||
let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
|
||||
let input = Input::Text(format!("fn {}() {{}}", long_identifier));
|
||||
let input = Input::Text(format!("fn {long_identifier}() {{}}"));
|
||||
let mut config = Config::default();
|
||||
config.set().error_on_line_overflow(true);
|
||||
let mut session = Session::<io::Stdout>::new(config, None);
|
||||
@ -618,7 +614,7 @@ fn format_lines_errors_are_reported() {
|
||||
fn format_lines_errors_are_reported_with_tabs() {
|
||||
init_log();
|
||||
let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
|
||||
let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
|
||||
let input = Input::Text(format!("fn a() {{\n\t{long_identifier}\n}}"));
|
||||
let mut config = Config::default();
|
||||
config.set().error_on_line_overflow(true);
|
||||
config.set().hard_tabs(true);
|
||||
@ -829,11 +825,11 @@ fn handle_result(
|
||||
for (file_name, fmt_text) in result {
|
||||
// If file is in tests/source, compare to file with same name in tests/target.
|
||||
let target = get_target(&file_name, target);
|
||||
let open_error = format!("couldn't open target {:?}", target);
|
||||
let open_error = format!("couldn't open target {target:?}");
|
||||
let mut f = fs::File::open(&target).expect(&open_error);
|
||||
|
||||
let mut text = String::new();
|
||||
let read_error = format!("failed reading target {:?}", target);
|
||||
let read_error = format!("failed reading target {target:?}");
|
||||
f.read_to_string(&mut text).expect(&read_error);
|
||||
|
||||
// Ignore LF and CRLF difference for Windows.
|
||||
|
16
src/types.rs
16
src/types.rs
@ -301,7 +301,7 @@ where
|
||||
let output = match *output {
|
||||
FnRetTy::Ty(ref ty) => {
|
||||
let type_str = ty.rewrite(context, ty_shape)?;
|
||||
format!(" -> {}", type_str)
|
||||
format!(" -> {type_str}")
|
||||
}
|
||||
FnRetTy::Default(..) => String::new(),
|
||||
};
|
||||
@ -373,7 +373,7 @@ where
|
||||
|| !context.use_block_indent()
|
||||
|| is_inputs_empty
|
||||
{
|
||||
format!("({})", list_str)
|
||||
format!("({list_str})")
|
||||
} else {
|
||||
format!(
|
||||
"({}{}{})",
|
||||
@ -383,7 +383,7 @@ where
|
||||
)
|
||||
};
|
||||
if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
|
||||
Some(format!("{}{}", args, output))
|
||||
Some(format!("{args}{output}"))
|
||||
} else {
|
||||
Some(format!(
|
||||
"{}\n{}{}",
|
||||
@ -429,9 +429,9 @@ impl Rewrite for ast::WherePredicate {
|
||||
let lhs = if let Some(binder_str) =
|
||||
rewrite_bound_params(context, shape, bound_generic_params)
|
||||
{
|
||||
format!("for<{}> {}{}", binder_str, type_str, colon)
|
||||
format!("for<{binder_str}> {type_str}{colon}")
|
||||
} else {
|
||||
format!("{}{}", type_str, colon)
|
||||
format!("{type_str}{colon}")
|
||||
};
|
||||
|
||||
rewrite_assign_rhs(context, lhs, bounds, &RhsAssignKind::Bounds, shape)?
|
||||
@ -665,7 +665,7 @@ impl Rewrite for ast::PolyTraitRef {
|
||||
.trait_ref
|
||||
.rewrite(context, shape.offset_left(extra_offset)?)?;
|
||||
|
||||
Some(format!("for<{}> {}", lifetime_str, path_str))
|
||||
Some(format!("for<{lifetime_str}> {path_str}"))
|
||||
} else {
|
||||
self.trait_ref.rewrite(context, shape)
|
||||
}
|
||||
@ -695,7 +695,7 @@ impl Rewrite for ast::Ty {
|
||||
res.push('+');
|
||||
}
|
||||
}
|
||||
Some(format!("{}{}", prefix, res))
|
||||
Some(format!("{prefix}{res}"))
|
||||
}
|
||||
ast::TyKind::Ptr(ref mt) => {
|
||||
let prefix = match mt.mutbl {
|
||||
@ -791,7 +791,7 @@ impl Rewrite for ast::Ty {
|
||||
if let Some(sh) = shape.sub_width(2) {
|
||||
if let Some(ref s) = ty.rewrite(context, sh) {
|
||||
if !s.contains('\n') {
|
||||
return Some(format!("({})", s));
|
||||
return Some(format!("({s})"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -69,7 +69,7 @@ pub(crate) fn format_visibility(
|
||||
let path = segments_iter.collect::<Vec<_>>().join("::");
|
||||
let in_str = if is_keyword(&path) { "" } else { "in " };
|
||||
|
||||
Cow::from(format!("pub({}{}) ", in_str, path))
|
||||
Cow::from(format!("pub({in_str}{path}) "))
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -147,7 +147,7 @@ pub(crate) fn format_extern(
|
||||
} else if abi == "C" && !explicit_abi {
|
||||
Cow::from("extern ")
|
||||
} else {
|
||||
Cow::from(format!(r#"extern "{}" "#, abi))
|
||||
Cow::from(format!(r#"extern "{abi}" "#))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -26,7 +26,7 @@ fn cargo_fmt(args: &[&str]) -> (String, String) {
|
||||
String::from_utf8(output.stdout).expect("utf-8"),
|
||||
String::from_utf8(output.stderr).expect("utf-8"),
|
||||
),
|
||||
Err(e) => panic!("failed to run `{:?} {:?}`: {}", cmd, args, e),
|
||||
Err(e) => panic!("failed to run `{cmd:?} {args:?}`: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -27,7 +27,7 @@ fn rustfmt(args: &[&str]) -> (String, String) {
|
||||
String::from_utf8(output.stdout).expect("utf-8"),
|
||||
String::from_utf8(output.stderr).expect("utf-8"),
|
||||
),
|
||||
Err(e) => panic!("failed to run `{:?} {:?}`: {}", cmd, args, e),
|
||||
Err(e) => panic!("failed to run `{cmd:?} {args:?}`: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
@ -71,9 +71,7 @@ fn print_config() {
|
||||
]);
|
||||
assert!(
|
||||
Path::new("minimal-config").exists(),
|
||||
"stdout:\n{}\nstderr:\n{}",
|
||||
stdout,
|
||||
stderr
|
||||
"stdout:\n{stdout}\nstderr:\n{stderr}"
|
||||
);
|
||||
remove_file("minimal-config").unwrap();
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user