Prettify rustc_session fmt with capturing args (nfc)

This commit is contained in:
Jubilee Young 2022-03-24 22:11:05 -07:00
parent 7941b3f147
commit de66e08957
8 changed files with 64 additions and 86 deletions

View file

@ -52,7 +52,7 @@ impl CguReuseTracker {
pub fn set_actual_reuse(&self, cgu_name: &str, kind: CguReuse) { pub fn set_actual_reuse(&self, cgu_name: &str, kind: CguReuse) {
if let Some(ref data) = self.data { if let Some(ref data) = self.data {
debug!("set_actual_reuse({:?}, {:?})", cgu_name, kind); debug!("set_actual_reuse({cgu_name:?}, {kind:?})");
let prev_reuse = data.lock().unwrap().actual_reuse.insert(cgu_name.to_string(), kind); let prev_reuse = data.lock().unwrap().actual_reuse.insert(cgu_name.to_string(), kind);
@ -74,7 +74,7 @@ impl CguReuseTracker {
comparison_kind: ComparisonKind, comparison_kind: ComparisonKind,
) { ) {
if let Some(ref data) = self.data { if let Some(ref data) = self.data {
debug!("set_expectation({:?}, {:?}, {:?})", cgu_name, expected_reuse, comparison_kind); debug!("set_expectation({cgu_name:?}, {expected_reuse:?}, {comparison_kind:?})");
let mut data = data.lock().unwrap(); let mut data = data.lock().unwrap();
data.expected_reuse.insert( data.expected_reuse.insert(
@ -100,17 +100,15 @@ impl CguReuseTracker {
if error { if error {
let at_least = if at_least { "at least " } else { "" }; let at_least = if at_least { "at least " } else { "" };
let msg = format!( let msg = format!(
"CGU-reuse for `{}` is `{:?}` but \ "CGU-reuse for `{cgu_user_name}` is `{actual_reuse:?}` but \
should be {}`{:?}`", should be {at_least}`{expected_reuse:?}`"
cgu_user_name, actual_reuse, at_least, expected_reuse
); );
diag.span_err(error_span.0, &msg); diag.span_err(error_span.0, &msg);
} }
} else { } else {
let msg = format!( let msg = format!(
"CGU-reuse for `{}` (mangled: `{}`) was \ "CGU-reuse for `{cgu_user_name}` (mangled: `{cgu_name}`) was \
not recorded", not recorded"
cgu_user_name, cgu_name
); );
diag.span_fatal(error_span.0, &msg) diag.span_fatal(error_span.0, &msg)
} }

View file

@ -99,7 +99,7 @@ impl CodeStats {
let indent = " "; let indent = " ";
let discr_size = if let Some(discr_size) = info.opt_discr_size { let discr_size = if let Some(discr_size) = info.opt_discr_size {
println!("print-type-size {}discriminant: {} bytes", indent, discr_size); println!("print-type-size {indent}discriminant: {discr_size} bytes");
discr_size discr_size
} else { } else {
0 0
@ -123,10 +123,8 @@ impl CodeStats {
None => i.to_string(), None => i.to_string(),
}; };
println!( println!(
"print-type-size {}variant `{}`: {} bytes", "print-type-size {indent}variant `{name}`: {diff} bytes",
indent, diff = size - discr_size
name,
size - discr_size
); );
" " " "
} else { } else {
@ -149,25 +147,23 @@ impl CodeStats {
if offset > min_offset { if offset > min_offset {
let pad = offset - min_offset; let pad = offset - min_offset;
println!("print-type-size {}padding: {} bytes", indent, pad); println!("print-type-size {indent}padding: {pad} bytes");
} }
if offset < min_offset { if offset < min_offset {
// If this happens it's probably a union. // If this happens it's probably a union.
println!( println!(
"print-type-size {}field `.{}`: {} bytes, \ "print-type-size {indent}field `.{name}`: {size} bytes, \
offset: {} bytes, \ offset: {offset} bytes, \
alignment: {} bytes", alignment: {align} bytes"
indent, name, size, offset, align
); );
} else if info.packed || offset == min_offset { } else if info.packed || offset == min_offset {
println!("print-type-size {}field `.{}`: {} bytes", indent, name, size); println!("print-type-size {indent}field `.{name}`: {size} bytes");
} else { } else {
// Include field alignment in output only if it caused padding injection // Include field alignment in output only if it caused padding injection
println!( println!(
"print-type-size {}field `.{}`: {} bytes, \ "print-type-size {indent}field `.{name}`: {size} bytes, \
alignment: {} bytes", alignment: {align} bytes"
indent, name, size, align
); );
} }

View file

@ -659,7 +659,7 @@ impl OutputFilenames {
single_output_file, single_output_file,
temps_directory, temps_directory,
outputs, outputs,
filestem: format!("{}{}", out_filestem, extra), filestem: format!("{out_filestem}{extra}"),
} }
} }
@ -1514,7 +1514,7 @@ pub fn get_cmd_lint_options(
let lint_cap = matches.opt_str("cap-lints").map(|cap| { let lint_cap = matches.opt_str("cap-lints").map(|cap| {
lint::Level::from_str(&cap) lint::Level::from_str(&cap)
.unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{}`", cap))) .unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{cap}`")))
}); });
(lint_opts, describe_lints, lint_cap) (lint_opts, describe_lints, lint_cap)
@ -1533,8 +1533,7 @@ pub fn parse_color(matches: &getopts::Matches) -> ColorConfig {
ErrorOutputType::default(), ErrorOutputType::default(),
&format!( &format!(
"argument for `--color` must be auto, \ "argument for `--color` must be auto, \
always or never (instead was `{}`)", always or never (instead was `{arg}`)"
arg
), ),
), ),
} }
@ -1579,7 +1578,7 @@ pub fn parse_json(matches: &getopts::Matches) -> JsonConfig {
"future-incompat" => json_future_incompat = true, "future-incompat" => json_future_incompat = true,
s => early_error( s => early_error(
ErrorOutputType::default(), ErrorOutputType::default(),
&format!("unknown `--json` option `{}`", s), &format!("unknown `--json` option `{s}`"),
), ),
} }
} }
@ -1619,8 +1618,7 @@ pub fn parse_error_format(
ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)), ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)),
&format!( &format!(
"argument for `--error-format` must be `human`, `json` or \ "argument for `--error-format` must be `human`, `json` or \
`short` (instead was `{}`)", `short` (instead was `{arg}`)"
arg
), ),
), ),
} }
@ -1654,8 +1652,7 @@ pub fn parse_crate_edition(matches: &getopts::Matches) -> Edition {
ErrorOutputType::default(), ErrorOutputType::default(),
&format!( &format!(
"argument for `--edition` must be one of: \ "argument for `--edition` must be one of: \
{}. (instead was `{}`)", {EDITION_NAME_LIST}. (instead was `{arg}`)"
EDITION_NAME_LIST, arg
), ),
) )
}), }),
@ -1670,7 +1667,7 @@ pub fn parse_crate_edition(matches: &getopts::Matches) -> Edition {
edition, LATEST_STABLE_EDITION edition, LATEST_STABLE_EDITION
) )
} else { } else {
format!("edition {} is unstable and only available with -Z unstable-options", edition) format!("edition {edition} is unstable and only available with -Z unstable-options")
}; };
early_error(ErrorOutputType::default(), &msg) early_error(ErrorOutputType::default(), &msg)
} }
@ -1718,9 +1715,8 @@ fn parse_output_types(
early_error( early_error(
error_format, error_format,
&format!( &format!(
"unknown emission type: `{}` - expected one of: {}", "unknown emission type: `{shorthand}` - expected one of: {display}",
shorthand, display = OutputType::shorthands_display(),
OutputType::shorthands_display(),
), ),
) )
}); });
@ -1758,9 +1754,8 @@ fn should_override_cgus_and_disable_thinlto(
early_warn( early_warn(
error_format, error_format,
&format!( &format!(
"`--emit={}` with `-o` incompatible with \ "`--emit={ot}` with `-o` incompatible with \
`-C codegen-units=N` for N > 1", `-C codegen-units=N` for N > 1",
ot
), ),
); );
} }
@ -1835,7 +1830,7 @@ fn collect_print_requests(
} }
} }
"link-args" => PrintRequest::LinkArgs, "link-args" => PrintRequest::LinkArgs,
req => early_error(error_format, &format!("unknown print request `{}`", req)), req => early_error(error_format, &format!("unknown print request `{req}`")),
})); }));
prints prints
@ -1849,7 +1844,7 @@ pub fn parse_target_triple(
Some(target) if target.ends_with(".json") => { Some(target) if target.ends_with(".json") => {
let path = Path::new(&target); let path = Path::new(&target);
TargetTriple::from_path(&path).unwrap_or_else(|_| { TargetTriple::from_path(&path).unwrap_or_else(|_| {
early_error(error_format, &format!("target file {:?} does not exist", path)) early_error(error_format, &format!("target file {path:?} does not exist"))
}) })
} }
Some(target) => TargetTriple::TargetTriple(target), Some(target) => TargetTriple::TargetTriple(target),
@ -1892,8 +1887,7 @@ fn parse_opt_level(
error_format, error_format,
&format!( &format!(
"optimization level needs to be \ "optimization level needs to be \
between 0-3, s or z (instead was `{}`)", between 0-3, s or z (instead was `{arg}`)"
arg
), ),
); );
} }
@ -1927,8 +1921,7 @@ fn select_debuginfo(
error_format, error_format,
&format!( &format!(
"debug info level needs to be between \ "debug info level needs to be between \
0-2 (instead was `{}`)", 0-2 (instead was `{arg}`)"
arg
), ),
); );
} }
@ -1943,10 +1936,9 @@ crate fn parse_assert_incr_state(
match opt_assertion { match opt_assertion {
Some(s) if s.as_str() == "loaded" => Some(IncrementalStateAssertion::Loaded), Some(s) if s.as_str() == "loaded" => Some(IncrementalStateAssertion::Loaded),
Some(s) if s.as_str() == "not-loaded" => Some(IncrementalStateAssertion::NotLoaded), Some(s) if s.as_str() == "not-loaded" => Some(IncrementalStateAssertion::NotLoaded),
Some(s) => early_error( Some(s) => {
error_format, early_error(error_format, &format!("unexpected incremental state assertion value: {s}"))
&format!("unexpected incremental state assertion value: {}", s), }
),
None => None, None => None,
} }
} }
@ -1991,7 +1983,7 @@ fn parse_native_lib_kind(
} }
s => early_error( s => early_error(
error_format, error_format,
&format!("unknown library kind `{}`, expected one of dylib, framework, or static", s), &format!("unknown library kind `{s}`, expected one of dylib, framework, or static"),
), ),
}; };
match modifiers { match modifiers {
@ -2066,9 +2058,8 @@ fn parse_native_lib_modifiers(
_ => early_error( _ => early_error(
error_format, error_format,
&format!( &format!(
"unrecognized linking modifier `{}`, expected one \ "unrecognized linking modifier `{modifier}`, expected one \
of: bundle, verbatim, whole-archive, as-needed", of: bundle, verbatim, whole-archive, as-needed"
modifier
), ),
), ),
} }
@ -2109,7 +2100,7 @@ fn parse_borrowck_mode(dopts: &DebuggingOptions, error_format: ErrorOutputType)
match dopts.borrowck.as_ref() { match dopts.borrowck.as_ref() {
"migrate" => BorrowckMode::Migrate, "migrate" => BorrowckMode::Migrate,
"mir" => BorrowckMode::Mir, "mir" => BorrowckMode::Mir,
m => early_error(error_format, &format!("unknown borrowck mode `{}`", m)), m => early_error(error_format, &format!("unknown borrowck mode `{m}`")),
} }
} }
@ -2197,7 +2188,7 @@ pub fn parse_externs(
); );
} }
} }
_ => early_error(error_format, &format!("unknown --extern option `{}`", opt)), _ => early_error(error_format, &format!("unknown --extern option `{opt}`")),
} }
} }
} }
@ -2234,7 +2225,7 @@ fn parse_extern_dep_specs(
let loc = parts.next().unwrap_or_else(|| { let loc = parts.next().unwrap_or_else(|| {
early_error( early_error(
error_format, error_format,
&format!("`--extern-location`: specify location for extern crate `{}`", name), &format!("`--extern-location`: specify location for extern crate `{name}`"),
) )
}); });
@ -2255,14 +2246,14 @@ fn parse_extern_dep_specs(
let json = json::from_str(raw).unwrap_or_else(|_| { let json = json::from_str(raw).unwrap_or_else(|_| {
early_error( early_error(
error_format, error_format,
&format!("`--extern-location`: malformed json location `{}`", raw), &format!("`--extern-location`: malformed json location `{raw}`"),
) )
}); });
ExternDepSpec::Json(json) ExternDepSpec::Json(json)
} }
[bad, ..] => early_error( [bad, ..] => early_error(
error_format, error_format,
&format!("unknown location type `{}`: use `raw` or `json`", bad), &format!("unknown location type `{bad}`: use `raw` or `json`"),
), ),
[] => early_error(error_format, "missing location specification"), [] => early_error(error_format, "missing location specification"),
}; };
@ -2527,9 +2518,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
&& !target_triple.triple().contains("apple") && !target_triple.triple().contains("apple")
&& cg.split_debuginfo.is_some() && cg.split_debuginfo.is_some()
{ {
{ early_error(error_format, "`-Csplit-debuginfo` is unstable on this platform");
early_error(error_format, "`-Csplit-debuginfo` is unstable on this platform");
}
} }
// Try to find a directory containing the Rust `src`, for more details see // Try to find a directory containing the Rust `src`, for more details see
@ -2561,7 +2550,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
}; };
let working_dir = std::env::current_dir().unwrap_or_else(|e| { let working_dir = std::env::current_dir().unwrap_or_else(|e| {
early_error(error_format, &format!("Current directory is invalid: {}", e)); early_error(error_format, &format!("Current directory is invalid: {e}"));
}); });
let (path, remapped) = let (path, remapped) =
@ -2636,12 +2625,11 @@ fn parse_pretty(debugging_opts: &DebuggingOptions, efmt: ErrorOutputType) -> Opt
"argument to `unpretty` must be one of `normal`, `identified`, \ "argument to `unpretty` must be one of `normal`, `identified`, \
`expanded`, `expanded,identified`, `expanded,hygiene`, \ `expanded`, `expanded,identified`, `expanded,hygiene`, \
`ast-tree`, `ast-tree,expanded`, `hir`, `hir,identified`, \ `ast-tree`, `ast-tree,expanded`, `hir`, `hir,identified`, \
`hir,typed`, `hir-tree`, `thir-tree`, `mir` or `mir-cfg`; got {}", `hir,typed`, `hir-tree`, `thir-tree`, `mir` or `mir-cfg`; got {name}"
name
), ),
), ),
}; };
tracing::debug!("got unpretty option: {:?}", first); tracing::debug!("got unpretty option: {first:?}");
Some(first) Some(first)
} }
@ -2667,7 +2655,7 @@ pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateTy
"cdylib" => CrateType::Cdylib, "cdylib" => CrateType::Cdylib,
"bin" => CrateType::Executable, "bin" => CrateType::Executable,
"proc-macro" => CrateType::ProcMacro, "proc-macro" => CrateType::ProcMacro,
_ => return Err(format!("unknown crate type: `{}`", part)), _ => return Err(format!("unknown crate type: `{part}`")),
}; };
if !crate_types.contains(&new_part) { if !crate_types.contains(&new_part) {
crate_types.push(new_part) crate_types.push(new_part)

View file

@ -85,7 +85,7 @@ pub fn get_or_default_sysroot() -> PathBuf {
p.pop(); p.pop();
p p
} }
Err(e) => panic!("failed to get current_exe: {}", e), Err(e) => panic!("failed to get current_exe: {e}"),
} }
} }

View file

@ -345,14 +345,13 @@ fn build_options<O: Default>(
Some(value) => early_error( Some(value) => early_error(
error_format, error_format,
&format!( &format!(
"incorrect value `{}` for {} option `{}` - {} was expected", "incorrect value `{value}` for {outputname} option `{key}` - {type_desc} was expected"
value, outputname, key, type_desc
), ),
), ),
} }
} }
} }
None => early_error(error_format, &format!("unknown {} option: `{}`", outputname, key)), None => early_error(error_format, &format!("unknown {outputname} option: `{key}`")),
} }
} }
return op; return op;

View file

@ -63,8 +63,7 @@ pub fn find_crate_name(sess: &Session, attrs: &[ast::Attribute], input: &Input)
if name.as_str() != s { if name.as_str() != s {
let msg = format!( let msg = format!(
"`--crate-name` and `#[crate_name]` are \ "`--crate-name` and `#[crate_name]` are \
required to match, but `{}` != `{}`", required to match, but `{s}` != `{name}`"
s, name
); );
sess.span_err(attr.span, &msg); sess.span_err(attr.span, &msg);
} }
@ -80,8 +79,7 @@ pub fn find_crate_name(sess: &Session, attrs: &[ast::Attribute], input: &Input)
if s.starts_with('-') { if s.starts_with('-') {
let msg = format!( let msg = format!(
"crate names cannot start with a `-`, but \ "crate names cannot start with a `-`, but \
`{}` has a leading hyphen", `{s}` has a leading hyphen"
s
); );
sess.err(&msg); sess.err(&msg);
} else { } else {
@ -113,7 +111,7 @@ pub fn validate_crate_name(sess: &Session, s: &str, sp: Option<Span>) {
if c == '_' { if c == '_' {
continue; continue;
} }
say(&format!("invalid character `{}` in crate name: `{}`", c, s)); say(&format!("invalid character `{c}` in crate name: `{s}`"));
} }
} }
@ -137,7 +135,7 @@ pub fn filename_for_metadata(
let out_filename = outputs let out_filename = outputs
.single_output_file .single_output_file
.clone() .clone()
.unwrap_or_else(|| outputs.out_directory.join(&format!("lib{}.rmeta", libname))); .unwrap_or_else(|| outputs.out_directory.join(&format!("lib{libname}.rmeta")));
check_file_is_writeable(&out_filename, sess); check_file_is_writeable(&out_filename, sess);
@ -153,14 +151,14 @@ pub fn filename_for_input(
let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename); let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
match crate_type { match crate_type {
CrateType::Rlib => outputs.out_directory.join(&format!("lib{}.rlib", libname)), CrateType::Rlib => outputs.out_directory.join(&format!("lib{libname}.rlib")),
CrateType::Cdylib | CrateType::ProcMacro | CrateType::Dylib => { CrateType::Cdylib | CrateType::ProcMacro | CrateType::Dylib => {
let (prefix, suffix) = (&sess.target.dll_prefix, &sess.target.dll_suffix); let (prefix, suffix) = (&sess.target.dll_prefix, &sess.target.dll_suffix);
outputs.out_directory.join(&format!("{}{}{}", prefix, libname, suffix)) outputs.out_directory.join(&format!("{prefix}{libname}{suffix}"))
} }
CrateType::Staticlib => { CrateType::Staticlib => {
let (prefix, suffix) = (&sess.target.staticlib_prefix, &sess.target.staticlib_suffix); let (prefix, suffix) = (&sess.target.staticlib_prefix, &sess.target.staticlib_suffix);
outputs.out_directory.join(&format!("{}{}{}", prefix, libname, suffix)) outputs.out_directory.join(&format!("{prefix}{libname}{suffix}"))
} }
CrateType::Executable => { CrateType::Executable => {
let suffix = &sess.target.exe_suffix; let suffix = &sess.target.exe_suffix;

View file

@ -120,14 +120,13 @@ pub fn add_feature_diagnostics_for_issue<'a>(
) { ) {
if let Some(n) = find_feature_issue(feature, issue) { if let Some(n) = find_feature_issue(feature, issue) {
err.note(&format!( err.note(&format!(
"see issue #{} <https://github.com/rust-lang/rust/issues/{}> for more information", "see issue #{n} <https://github.com/rust-lang/rust/issues/{n}> for more information"
n, n,
)); ));
} }
// #23973: do not suggest `#![feature(...)]` if we are in beta/stable // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
if sess.unstable_features.is_nightly_build() { if sess.unstable_features.is_nightly_build() {
err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature)); err.help(&format!("add `#![feature({feature})]` to the crate attributes to enable"));
} }
} }

View file

@ -88,7 +88,7 @@ impl From<usize> for Limit {
impl fmt::Display for Limit { impl fmt::Display for Limit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0) self.0.fmt(f)
} }
} }
@ -252,8 +252,8 @@ impl Session {
let mut diag = self.struct_warn("skipping const checks"); let mut diag = self.struct_warn("skipping const checks");
for &(span, feature_gate) in unleashed_features.iter() { for &(span, feature_gate) in unleashed_features.iter() {
// FIXME: `span_label` doesn't do anything, so we use "help" as a hack. // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
if let Some(feature_gate) = feature_gate { if let Some(gate) = feature_gate {
diag.span_help(span, &format!("skipping check for `{}` feature", feature_gate)); diag.span_help(span, &format!("skipping check for `{gate}` feature"));
// The unleash flag must *not* be used to just "hack around" feature gates. // The unleash flag must *not* be used to just "hack around" feature gates.
must_err = true; must_err = true;
} else { } else {
@ -1204,7 +1204,7 @@ pub fn build_session(
let target_cfg = config::build_target_config(&sopts, target_override, &sysroot); let target_cfg = config::build_target_config(&sopts, target_override, &sysroot);
let host_triple = TargetTriple::from_triple(config::host_triple()); let host_triple = TargetTriple::from_triple(config::host_triple());
let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| { let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| {
early_error(sopts.error_format, &format!("Error loading host specification: {}", e)) early_error(sopts.error_format, &format!("Error loading host specification: {e}"))
}); });
for warning in target_warnings.warning_messages() { for warning in target_warnings.warning_messages() {
early_warn(sopts.error_format, &warning) early_warn(sopts.error_format, &warning)
@ -1243,7 +1243,7 @@ pub fn build_session(
match profiler { match profiler {
Ok(profiler) => Some(Arc::new(profiler)), Ok(profiler) => Some(Arc::new(profiler)),
Err(e) => { Err(e) => {
early_warn(sopts.error_format, &format!("failed to create profiler: {}", e)); early_warn(sopts.error_format, &format!("failed to create profiler: {e}"));
None None
} }
} }
@ -1407,7 +1407,7 @@ fn validate_commandline_args_with_session_available(sess: &Session) {
// Cannot mix and match sanitizers. // Cannot mix and match sanitizers.
let mut sanitizer_iter = sess.opts.debugging_opts.sanitizer.into_iter(); let mut sanitizer_iter = sess.opts.debugging_opts.sanitizer.into_iter();
if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) { if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) {
sess.err(&format!("`-Zsanitizer={}` is incompatible with `-Zsanitizer={}`", first, second)); sess.err(&format!("`-Zsanitizer={first}` is incompatible with `-Zsanitizer={second}`"));
} }
// Cannot enable crt-static with sanitizers on Linux // Cannot enable crt-static with sanitizers on Linux