inline format!() args up to and including rustc_codegen_llvm

This commit is contained in:
Matthias Krüger 2023-07-25 23:04:01 +02:00
parent 2e0136a131
commit 3ce90b1649
72 changed files with 411 additions and 481 deletions

View File

@ -444,7 +444,7 @@ pub fn from_fn_attrs<'ll, 'tcx>(
let mut function_features = function_features let mut function_features = function_features
.iter() .iter()
.flat_map(|feat| { .flat_map(|feat| {
llvm_util::to_llvm_features(cx.tcx.sess, feat).into_iter().map(|f| format!("+{}", f)) llvm_util::to_llvm_features(cx.tcx.sess, feat).into_iter().map(|f| format!("+{f}"))
}) })
.chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x { .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(), InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),

View File

@ -56,7 +56,7 @@ fn llvm_machine_type(cpu: &str) -> LLVMMachineType {
"x86" => LLVMMachineType::I386, "x86" => LLVMMachineType::I386,
"aarch64" => LLVMMachineType::ARM64, "aarch64" => LLVMMachineType::ARM64,
"arm" => LLVMMachineType::ARM, "arm" => LLVMMachineType::ARM,
_ => panic!("unsupported cpu type {}", cpu), _ => panic!("unsupported cpu type {cpu}"),
} }
} }
@ -128,7 +128,7 @@ impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
let name_suffix = if is_direct_dependency { "_imports" } else { "_imports_indirect" }; let name_suffix = if is_direct_dependency { "_imports" } else { "_imports_indirect" };
let output_path = { let output_path = {
let mut output_path: PathBuf = tmpdir.to_path_buf(); let mut output_path: PathBuf = tmpdir.to_path_buf();
output_path.push(format!("{}{}", lib_name, name_suffix)); output_path.push(format!("{lib_name}{name_suffix}"));
output_path.with_extension("lib") output_path.with_extension("lib")
}; };
@ -156,7 +156,7 @@ impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
// functions. Therefore, use binutils to create the import library instead, // functions. Therefore, use binutils to create the import library instead,
// by writing a .DEF file to the temp dir and calling binutils's dlltool. // by writing a .DEF file to the temp dir and calling binutils's dlltool.
let def_file_path = let def_file_path =
tmpdir.join(format!("{}{}", lib_name, name_suffix)).with_extension("def"); tmpdir.join(format!("{lib_name}{name_suffix}")).with_extension("def");
let def_file_content = format!( let def_file_content = format!(
"EXPORTS\n{}", "EXPORTS\n{}",
@ -164,7 +164,7 @@ impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
.into_iter() .into_iter()
.map(|(name, ordinal)| { .map(|(name, ordinal)| {
match ordinal { match ordinal {
Some(n) => format!("{} @{} NONAME", name, n), Some(n) => format!("{name} @{n} NONAME"),
None => name, None => name,
} }
}) })
@ -435,7 +435,7 @@ impl<'a> LlvmArchiveBuilder<'a> {
} }
fn string_to_io_error(s: String) -> io::Error { fn string_to_io_error(s: String) -> io::Error {
io::Error::new(io::ErrorKind::Other, format!("bad archive: {}", s)) io::Error::new(io::ErrorKind::Other, format!("bad archive: {s}"))
} }
fn find_binutils_dlltool(sess: &Session) -> OsString { fn find_binutils_dlltool(sess: &Session) -> OsString {

View File

@ -332,7 +332,7 @@ fn fat_lto(
let _timer = cgcx let _timer = cgcx
.prof .prof
.generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| { .generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| {
recorder.record_arg(format!("{:?}", name)) recorder.record_arg(format!("{name:?}"))
}); });
info!("linking {:?}", name); info!("linking {:?}", name);
let data = bc_decoded.data(); let data = bc_decoded.data();
@ -787,7 +787,7 @@ impl ThinLTOKeysMap {
let file = File::create(path)?; let file = File::create(path)?;
let mut writer = io::BufWriter::new(file); let mut writer = io::BufWriter::new(file);
for (module, key) in &self.keys { for (module, key) in &self.keys {
writeln!(writer, "{} {}", module, key)?; writeln!(writer, "{module} {key}")?;
} }
Ok(()) Ok(())
} }
@ -801,7 +801,7 @@ impl ThinLTOKeysMap {
let mut split = line.split(' '); let mut split = line.split(' ');
let module = split.next().unwrap(); let module = split.next().unwrap();
let key = split.next().unwrap(); let key = split.next().unwrap();
assert_eq!(split.next(), None, "Expected two space-separated values, found {:?}", line); assert_eq!(split.next(), None, "Expected two space-separated values, found {line:?}");
keys.insert(module.to_string(), key.to_string()); keys.insert(module.to_string(), key.to_string());
} }
Ok(Self { keys }) Ok(Self { keys })

View File

@ -259,7 +259,7 @@ pub(crate) fn save_temp_bitcode(
return; return;
} }
unsafe { unsafe {
let ext = format!("{}.bc", name); let ext = format!("{name}.bc");
let cgu = Some(&module.name[..]); let cgu = Some(&module.name[..]);
let path = cgcx.output_filenames.temp_path_ext(&ext, cgu); let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
let cstr = path_to_c_string(&path); let cstr = path_to_c_string(&path);
@ -713,7 +713,7 @@ pub(crate) unsafe fn codegen(
let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 }; let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 };
if write!(cursor, "{:#}", demangled).is_err() { if write!(cursor, "{demangled:#}").is_err() {
// Possible only if provided buffer is not big enough // Possible only if provided buffer is not big enough
return 0; return 0;
} }
@ -834,7 +834,7 @@ pub(crate) unsafe fn codegen(
} }
fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: &[u8]) -> Vec<u8> { fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: &[u8]) -> Vec<u8> {
let mut asm = format!(".section {},\"{}\"\n", section_name, section_flags).into_bytes(); let mut asm = format!(".section {section_name},\"{section_flags}\"\n").into_bytes();
asm.extend_from_slice(b".ascii \""); asm.extend_from_slice(b".ascii \"");
asm.reserve(data.len()); asm.reserve(data.len());
for &byte in data { for &byte in data {

View File

@ -1415,9 +1415,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
) -> Cow<'b, [&'ll Value]> { ) -> Cow<'b, [&'ll Value]> {
assert!( assert!(
self.cx.type_kind(fn_ty) == TypeKind::Function, self.cx.type_kind(fn_ty) == TypeKind::Function,
"builder::{} not passed a function, but {:?}", "builder::{typ} not passed a function, but {fn_ty:?}"
typ,
fn_ty
); );
let param_tys = self.cx.func_params_types(fn_ty); let param_tys = self.cx.func_params_types(fn_ty);
@ -1509,12 +1507,9 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
let instr = if signed { "fptosi" } else { "fptoui" }; let instr = if signed { "fptosi" } else { "fptoui" };
let name = if let Some(vector_length) = vector_length { let name = if let Some(vector_length) = vector_length {
format!( format!("llvm.{instr}.sat.v{vector_length}i{int_width}.v{vector_length}f{float_width}")
"llvm.{}.sat.v{}i{}.v{}f{}",
instr, vector_length, int_width, vector_length, float_width
)
} else { } else {
format!("llvm.{}.sat.i{}.f{}", instr, int_width, float_width) format!("llvm.{instr}.sat.i{int_width}.f{float_width}")
}; };
let f = self.declare_cfn(&name, llvm::UnnamedAddr::No, self.type_func(&[src_ty], dest_ty)); let f = self.declare_cfn(&name, llvm::UnnamedAddr::No, self.type_func(&[src_ty], dest_ty));
self.call(self.type_func(&[src_ty], dest_ty), None, None, f, &[val], None) self.call(self.type_func(&[src_ty], dest_ty), None, None, f, &[val], None)

View File

@ -420,10 +420,10 @@ pub(crate) fn i686_decorated_name(
DllCallingConvention::C => {} DllCallingConvention::C => {}
DllCallingConvention::Stdcall(arg_list_size) DllCallingConvention::Stdcall(arg_list_size)
| DllCallingConvention::Fastcall(arg_list_size) => { | DllCallingConvention::Fastcall(arg_list_size) => {
write!(&mut decorated_name, "@{}", arg_list_size).unwrap(); write!(&mut decorated_name, "@{arg_list_size}").unwrap();
} }
DllCallingConvention::Vectorcall(arg_list_size) => { DllCallingConvention::Vectorcall(arg_list_size) => {
write!(&mut decorated_name, "@@{}", arg_list_size).unwrap(); write!(&mut decorated_name, "@@{arg_list_size}").unwrap();
} }
} }
} }

View File

@ -238,8 +238,7 @@ impl<'ll> CodegenCx<'ll, '_> {
assert!( assert!(
!defined_in_current_codegen_unit, !defined_in_current_codegen_unit,
"consts::get_static() should always hit the cache for \ "consts::get_static() should always hit the cache for \
statics defined in the same CGU, but did not for `{:?}`", statics defined in the same CGU, but did not for `{def_id:?}`"
def_id
); );
let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all()); let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());

View File

@ -54,7 +54,7 @@ pub fn get_or_insert_gdb_debug_scripts_section_global<'ll>(cx: &CodegenCx<'ll, '
// The initial byte `4` instructs GDB that the following pretty printer // The initial byte `4` instructs GDB that the following pretty printer
// is defined inline as opposed to in a standalone file. // is defined inline as opposed to in a standalone file.
section_contents.extend_from_slice(b"\x04"); section_contents.extend_from_slice(b"\x04");
let vis_name = format!("pretty-printer-{}-{}\n", crate_name, index); let vis_name = format!("pretty-printer-{crate_name}-{index}\n");
section_contents.extend_from_slice(vis_name.as_bytes()); section_contents.extend_from_slice(vis_name.as_bytes());
section_contents.extend_from_slice(&visualizer.src); section_contents.extend_from_slice(&visualizer.src);

View File

@ -184,9 +184,7 @@ fn build_pointer_or_reference_di_node<'ll, 'tcx>(
debug_assert_eq!( debug_assert_eq!(
(data_layout.pointer_size, data_layout.pointer_align.abi), (data_layout.pointer_size, data_layout.pointer_align.abi),
cx.size_and_align_of(ptr_type), cx.size_and_align_of(ptr_type),
"ptr_type={}, pointee_type={}", "ptr_type={ptr_type}, pointee_type={pointee_type}",
ptr_type,
pointee_type,
); );
let di_node = unsafe { let di_node = unsafe {
@ -521,7 +519,7 @@ fn recursion_marker_type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> &'ll D
fn hex_encode(data: &[u8]) -> String { fn hex_encode(data: &[u8]) -> String {
let mut hex_string = String::with_capacity(data.len() * 2); let mut hex_string = String::with_capacity(data.len() * 2);
for byte in data.iter() { for byte in data.iter() {
write!(&mut hex_string, "{:02x}", byte).unwrap(); write!(&mut hex_string, "{byte:02x}").unwrap();
} }
hex_string hex_string
} }
@ -766,7 +764,7 @@ fn build_param_type_di_node<'ll, 'tcx>(
t: Ty<'tcx>, t: Ty<'tcx>,
) -> DINodeCreationResult<'ll> { ) -> DINodeCreationResult<'ll> {
debug!("build_param_type_di_node: {:?}", t); debug!("build_param_type_di_node: {:?}", t);
let name = format!("{:?}", t); let name = format!("{t:?}");
DINodeCreationResult { DINodeCreationResult {
di_node: unsafe { di_node: unsafe {
llvm::LLVMRustDIBuilderCreateBasicType( llvm::LLVMRustDIBuilderCreateBasicType(
@ -814,7 +812,7 @@ pub fn build_compile_unit_di_node<'ll, 'tcx>(
debug!("build_compile_unit_di_node: {:?}", name_in_debuginfo); debug!("build_compile_unit_di_node: {:?}", name_in_debuginfo);
let rustc_producer = format!("rustc version {}", tcx.sess.cfg_version); let rustc_producer = format!("rustc version {}", tcx.sess.cfg_version);
// FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice. // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
let producer = format!("clang LLVM ({})", rustc_producer); let producer = format!("clang LLVM ({rustc_producer})");
let name_in_debuginfo = name_in_debuginfo.to_string_lossy(); let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
let work_dir = tcx.sess.opts.working_dir.to_string_lossy(FileNameDisplayPreference::Remapped); let work_dir = tcx.sess.opts.working_dir.to_string_lossy(FileNameDisplayPreference::Remapped);
@ -1331,10 +1329,10 @@ fn build_vtable_type_di_node<'ll, 'tcx>(
// Note: This code does not try to give a proper name to each method // Note: This code does not try to give a proper name to each method
// because their might be multiple methods with the same name // because their might be multiple methods with the same name
// (coming from different traits). // (coming from different traits).
(format!("__method{}", index), void_pointer_type_di_node) (format!("__method{index}"), void_pointer_type_di_node)
} }
ty::VtblEntry::TraitVPtr(_) => { ty::VtblEntry::TraitVPtr(_) => {
(format!("__super_trait_ptr{}", index), void_pointer_type_di_node) (format!("__super_trait_ptr{index}"), void_pointer_type_di_node)
} }
ty::VtblEntry::MetadataAlign => ("align".to_string(), usize_di_node), ty::VtblEntry::MetadataAlign => ("align".to_string(), usize_di_node),
ty::VtblEntry::MetadataSize => ("size".to_string(), usize_di_node), ty::VtblEntry::MetadataSize => ("size".to_string(), usize_di_node),
@ -1504,5 +1502,5 @@ pub fn tuple_field_name(field_index: usize) -> Cow<'static, str> {
TUPLE_FIELD_NAMES TUPLE_FIELD_NAMES
.get(field_index) .get(field_index)
.map(|s| Cow::from(*s)) .map(|s| Cow::from(*s))
.unwrap_or_else(|| Cow::from(format!("__{}", field_index))) .unwrap_or_else(|| Cow::from(format!("__{field_index}")))
} }

View File

@ -91,8 +91,7 @@ pub(crate) fn fat_pointer_kind<'ll, 'tcx>(
// For all other pointee types we should already have returned None // For all other pointee types we should already have returned None
// at the beginning of the function. // at the beginning of the function.
panic!( panic!(
"fat_pointer_kind() - Encountered unexpected `pointee_tail_ty`: {:?}", "fat_pointer_kind() - Encountered unexpected `pointee_tail_ty`: {pointee_tail_ty:?}"
pointee_tail_ty
) )
} }
} }

View File

@ -230,22 +230,22 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> {
sym::ctlz | sym::cttz => { sym::ctlz | sym::cttz => {
let y = self.const_bool(false); let y = self.const_bool(false);
self.call_intrinsic( self.call_intrinsic(
&format!("llvm.{}.i{}", name, width), &format!("llvm.{name}.i{width}"),
&[args[0].immediate(), y], &[args[0].immediate(), y],
) )
} }
sym::ctlz_nonzero => { sym::ctlz_nonzero => {
let y = self.const_bool(true); let y = self.const_bool(true);
let llvm_name = &format!("llvm.ctlz.i{}", width); let llvm_name = &format!("llvm.ctlz.i{width}");
self.call_intrinsic(llvm_name, &[args[0].immediate(), y]) self.call_intrinsic(llvm_name, &[args[0].immediate(), y])
} }
sym::cttz_nonzero => { sym::cttz_nonzero => {
let y = self.const_bool(true); let y = self.const_bool(true);
let llvm_name = &format!("llvm.cttz.i{}", width); let llvm_name = &format!("llvm.cttz.i{width}");
self.call_intrinsic(llvm_name, &[args[0].immediate(), y]) self.call_intrinsic(llvm_name, &[args[0].immediate(), y])
} }
sym::ctpop => self.call_intrinsic( sym::ctpop => self.call_intrinsic(
&format!("llvm.ctpop.i{}", width), &format!("llvm.ctpop.i{width}"),
&[args[0].immediate()], &[args[0].immediate()],
), ),
sym::bswap => { sym::bswap => {
@ -253,13 +253,13 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> {
args[0].immediate() // byte swap a u8/i8 is just a no-op args[0].immediate() // byte swap a u8/i8 is just a no-op
} else { } else {
self.call_intrinsic( self.call_intrinsic(
&format!("llvm.bswap.i{}", width), &format!("llvm.bswap.i{width}"),
&[args[0].immediate()], &[args[0].immediate()],
) )
} }
} }
sym::bitreverse => self.call_intrinsic( sym::bitreverse => self.call_intrinsic(
&format!("llvm.bitreverse.i{}", width), &format!("llvm.bitreverse.i{width}"),
&[args[0].immediate()], &[args[0].immediate()],
), ),
sym::rotate_left | sym::rotate_right => { sym::rotate_left | sym::rotate_right => {
@ -1283,7 +1283,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
sym::simd_trunc => ("trunc", bx.type_func(&[vec_ty], vec_ty)), sym::simd_trunc => ("trunc", bx.type_func(&[vec_ty], vec_ty)),
_ => return_error!(InvalidMonomorphization::UnrecognizedIntrinsic { span, name }), _ => return_error!(InvalidMonomorphization::UnrecognizedIntrinsic { span, name }),
}; };
let llvm_name = &format!("llvm.{0}.v{1}{2}", intr_name, in_len, elem_ty_str); let llvm_name = &format!("llvm.{intr_name}.v{in_len}{elem_ty_str}");
let f = bx.declare_cfn(llvm_name, llvm::UnnamedAddr::No, fn_ty); let f = bx.declare_cfn(llvm_name, llvm::UnnamedAddr::No, fn_ty);
let c = bx.call( let c = bx.call(
fn_ty, fn_ty,
@ -1498,7 +1498,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1, bx); let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1, bx);
let llvm_intrinsic = let llvm_intrinsic =
format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str); format!("llvm.masked.gather.{llvm_elem_vec_str}.{llvm_pointer_vec_str}");
let fn_ty = bx.type_func( let fn_ty = bx.type_func(
&[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty], &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
llvm_elem_vec_ty, llvm_elem_vec_ty,
@ -1642,7 +1642,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1, bx); let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1, bx);
let llvm_intrinsic = let llvm_intrinsic =
format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str); format!("llvm.masked.scatter.{llvm_elem_vec_str}.{llvm_pointer_vec_str}");
let fn_ty = let fn_ty =
bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t); bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t);
let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty); let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);

View File

@ -298,21 +298,21 @@ impl CodegenBackend for LlvmCodegenBackend {
"ropi-rwpi", "ropi-rwpi",
"default", "default",
] { ] {
writeln!(out, " {}", name); writeln!(out, " {name}");
} }
writeln!(out); writeln!(out);
} }
PrintKind::CodeModels => { PrintKind::CodeModels => {
writeln!(out, "Available code models:"); writeln!(out, "Available code models:");
for name in &["tiny", "small", "kernel", "medium", "large"] { for name in &["tiny", "small", "kernel", "medium", "large"] {
writeln!(out, " {}", name); writeln!(out, " {name}");
} }
writeln!(out); writeln!(out);
} }
PrintKind::TlsModels => { PrintKind::TlsModels => {
writeln!(out, "Available TLS models:"); writeln!(out, "Available TLS models:");
for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] { for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
writeln!(out, " {}", name); writeln!(out, " {name}");
} }
writeln!(out); writeln!(out);
} }

View File

@ -315,7 +315,7 @@ pub fn target_features(sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
pub fn print_version() { pub fn print_version() {
let (major, minor, patch) = get_version(); let (major, minor, patch) = get_version();
println!("LLVM version: {}.{}.{}", major, minor, patch); println!("LLVM version: {major}.{minor}.{patch}");
} }
pub fn get_version() -> (u32, u32, u32) { pub fn get_version() -> (u32, u32, u32) {
@ -390,11 +390,11 @@ fn print_target_features(out: &mut dyn PrintBackendInfo, sess: &Session, tm: &ll
writeln!(out, "Features supported by rustc for this target:"); writeln!(out, "Features supported by rustc for this target:");
for (feature, desc) in &rustc_target_features { for (feature, desc) in &rustc_target_features {
writeln!(out, " {1:0$} - {2}.", max_feature_len, feature, desc); writeln!(out, " {feature:max_feature_len$} - {desc}.");
} }
writeln!(out, "\nCode-generation features supported by LLVM for this target:"); writeln!(out, "\nCode-generation features supported by LLVM for this target:");
for (feature, desc) in &llvm_target_features { for (feature, desc) in &llvm_target_features {
writeln!(out, " {1:0$} - {2}.", max_feature_len, feature, desc); writeln!(out, " {feature:max_feature_len$} - {desc}.");
} }
if llvm_target_features.is_empty() { if llvm_target_features.is_empty() {
writeln!(out, " Target features listing is not supported by this LLVM version."); writeln!(out, " Target features listing is not supported by this LLVM version.");
@ -573,7 +573,7 @@ pub(crate) fn global_llvm_features(sess: &Session, diagnostics: bool) -> Vec<Str
match (enable_disable, feat) { match (enable_disable, feat) {
('-' | '+', TargetFeatureFoldStrength::Both(f)) ('-' | '+', TargetFeatureFoldStrength::Both(f))
| ('+', TargetFeatureFoldStrength::EnableOnly(f)) => { | ('+', TargetFeatureFoldStrength::EnableOnly(f)) => {
Some(format!("{}{}", enable_disable, f)) Some(format!("{enable_disable}{f}"))
} }
_ => None, _ => None,
} }

View File

@ -748,7 +748,7 @@ fn link_natively<'a>(
for print in &sess.opts.prints { for print in &sess.opts.prints {
if print.kind == PrintKind::LinkArgs { if print.kind == PrintKind::LinkArgs {
let content = format!("{:?}", cmd); let content = format!("{cmd:?}");
print.out.overwrite(&content, sess); print.out.overwrite(&content, sess);
} }
} }
@ -1236,22 +1236,21 @@ fn link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str) {
} }
} }
let channel = option_env!("CFG_RELEASE_CHANNEL") let channel =
.map(|channel| format!("-{}", channel)) option_env!("CFG_RELEASE_CHANNEL").map(|channel| format!("-{channel}")).unwrap_or_default();
.unwrap_or_default();
if sess.target.is_like_osx { if sess.target.is_like_osx {
// On Apple platforms, the sanitizer is always built as a dylib, and // On Apple platforms, the sanitizer is always built as a dylib, and
// LLVM will link to `@rpath/*.dylib`, so we need to specify an // LLVM will link to `@rpath/*.dylib`, so we need to specify an
// rpath to the library as well (the rpath should be absolute, see // rpath to the library as well (the rpath should be absolute, see
// PR #41352 for details). // PR #41352 for details).
let filename = format!("rustc{}_rt.{}", channel, name); let filename = format!("rustc{channel}_rt.{name}");
let path = find_sanitizer_runtime(&sess, &filename); let path = find_sanitizer_runtime(&sess, &filename);
let rpath = path.to_str().expect("non-utf8 component in path"); let rpath = path.to_str().expect("non-utf8 component in path");
linker.args(&["-Wl,-rpath", "-Xlinker", rpath]); linker.args(&["-Wl,-rpath", "-Xlinker", rpath]);
linker.link_dylib(&filename, false, true); linker.link_dylib(&filename, false, true);
} else { } else {
let filename = format!("librustc{}_rt.{}.a", channel, name); let filename = format!("librustc{channel}_rt.{name}.a");
let path = find_sanitizer_runtime(&sess, &filename).join(&filename); let path = find_sanitizer_runtime(&sess, &filename).join(&filename);
linker.link_whole_rlib(&path); linker.link_whole_rlib(&path);
} }
@ -1415,12 +1414,12 @@ fn print_native_static_libs(
} else if sess.target.linker_flavor.is_gnu() { } else if sess.target.linker_flavor.is_gnu() {
Some(format!("-l{}{}", if verbatim { ":" } else { "" }, name)) Some(format!("-l{}{}", if verbatim { ":" } else { "" }, name))
} else { } else {
Some(format!("-l{}", name)) Some(format!("-l{name}"))
} }
} }
NativeLibKind::Framework { .. } => { NativeLibKind::Framework { .. } => {
// ld-only syntax, since there are no frameworks in MSVC // ld-only syntax, since there are no frameworks in MSVC
Some(format!("-framework {}", name)) Some(format!("-framework {name}"))
} }
// These are included, no need to print them // These are included, no need to print them
NativeLibKind::Static { bundle: None | Some(true), .. } NativeLibKind::Static { bundle: None | Some(true), .. }
@ -1457,12 +1456,12 @@ fn print_native_static_libs(
// `foo.lib` file if the dll doesn't actually export any symbols, so we // `foo.lib` file if the dll doesn't actually export any symbols, so we
// check to see if the file is there and just omit linking to it if it's // check to see if the file is there and just omit linking to it if it's
// not present. // not present.
let name = format!("{}.dll.lib", lib); let name = format!("{lib}.dll.lib");
if path.join(&name).exists() { if path.join(&name).exists() {
lib_args.push(name); lib_args.push(name);
} }
} else { } else {
lib_args.push(format!("-l{}", lib)); lib_args.push(format!("-l{lib}"));
} }
} }
@ -1628,8 +1627,8 @@ fn exec_linker(
write!(f, "\"")?; write!(f, "\"")?;
for c in self.arg.chars() { for c in self.arg.chars() {
match c { match c {
'"' => write!(f, "\\{}", c)?, '"' => write!(f, "\\{c}")?,
c => write!(f, "{}", c)?, c => write!(f, "{c}")?,
} }
} }
write!(f, "\"")?; write!(f, "\"")?;
@ -1646,8 +1645,8 @@ fn exec_linker(
// ensure the line is interpreted as one whole argument. // ensure the line is interpreted as one whole argument.
for c in self.arg.chars() { for c in self.arg.chars() {
match c { match c {
'\\' | ' ' => write!(f, "\\{}", c)?, '\\' | ' ' => write!(f, "\\{c}")?,
c => write!(f, "{}", c)?, c => write!(f, "{c}")?,
} }
} }
} }
@ -2284,7 +2283,7 @@ fn add_order_independent_options(
} else { } else {
"" ""
}; };
cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix)); cmd.arg(format!("--dynamic-linker={prefix}ld.so.1"));
} }
if sess.target.eh_frame_header { if sess.target.eh_frame_header {

View File

@ -309,7 +309,7 @@ impl<'a> GccLinker<'a> {
self.linker_arg(&format!("-plugin-opt=sample-profile={}", path.display())); self.linker_arg(&format!("-plugin-opt=sample-profile={}", path.display()));
}; };
self.linker_args(&[ self.linker_args(&[
&format!("-plugin-opt={}", opt_level), &format!("-plugin-opt={opt_level}"),
&format!("-plugin-opt=mcpu={}", self.target_cpu), &format!("-plugin-opt=mcpu={}", self.target_cpu),
]); ]);
} }
@ -487,7 +487,7 @@ impl<'a> Linker for GccLinker<'a> {
fn link_rust_dylib(&mut self, lib: &str, _path: &Path) { fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
self.hint_dynamic(); self.hint_dynamic();
self.cmd.arg(format!("-l{}", lib)); self.cmd.arg(format!("-l{lib}"));
} }
fn link_framework(&mut self, framework: &str, as_needed: bool) { fn link_framework(&mut self, framework: &str, as_needed: bool) {
@ -671,8 +671,8 @@ impl<'a> Linker for GccLinker<'a> {
let res: io::Result<()> = try { let res: io::Result<()> = try {
let mut f = BufWriter::new(File::create(&path)?); let mut f = BufWriter::new(File::create(&path)?);
for sym in symbols { for sym in symbols {
debug!(" _{}", sym); debug!(" _{sym}");
writeln!(f, "_{}", sym)?; writeln!(f, "_{sym}")?;
} }
}; };
if let Err(error) = res { if let Err(error) = res {
@ -686,8 +686,8 @@ impl<'a> Linker for GccLinker<'a> {
// because LD doesn't like when it's empty // because LD doesn't like when it's empty
writeln!(f, "EXPORTS")?; writeln!(f, "EXPORTS")?;
for symbol in symbols { for symbol in symbols {
debug!(" _{}", symbol); debug!(" _{symbol}");
writeln!(f, " {}", symbol)?; writeln!(f, " {symbol}")?;
} }
}; };
if let Err(error) = res { if let Err(error) = res {
@ -701,8 +701,8 @@ impl<'a> Linker for GccLinker<'a> {
if !symbols.is_empty() { if !symbols.is_empty() {
writeln!(f, " global:")?; writeln!(f, " global:")?;
for sym in symbols { for sym in symbols {
debug!(" {};", sym); debug!(" {sym};");
writeln!(f, " {};", sym)?; writeln!(f, " {sym};")?;
} }
} }
writeln!(f, "\n local:\n *;\n}};")?; writeln!(f, "\n local:\n *;\n}};")?;
@ -837,7 +837,7 @@ impl<'a> Linker for MsvcLinker<'a> {
// `foo.lib` file if the dll doesn't actually export any symbols, so we // `foo.lib` file if the dll doesn't actually export any symbols, so we
// check to see if the file is there and just omit linking to it if it's // check to see if the file is there and just omit linking to it if it's
// not present. // not present.
let name = format!("{}.dll.lib", lib); let name = format!("{lib}.dll.lib");
if path.join(&name).exists() { if path.join(&name).exists() {
self.cmd.arg(name); self.cmd.arg(name);
} }
@ -977,8 +977,8 @@ impl<'a> Linker for MsvcLinker<'a> {
writeln!(f, "LIBRARY")?; writeln!(f, "LIBRARY")?;
writeln!(f, "EXPORTS")?; writeln!(f, "EXPORTS")?;
for symbol in symbols { for symbol in symbols {
debug!(" _{}", symbol); debug!(" _{symbol}");
writeln!(f, " {}", symbol)?; writeln!(f, " {symbol}")?;
} }
}; };
if let Err(error) = res { if let Err(error) = res {
@ -992,7 +992,7 @@ impl<'a> Linker for MsvcLinker<'a> {
fn subsystem(&mut self, subsystem: &str) { fn subsystem(&mut self, subsystem: &str) {
// Note that previous passes of the compiler validated this subsystem, // Note that previous passes of the compiler validated this subsystem,
// so we just blindly pass it to the linker. // so we just blindly pass it to the linker.
self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem)); self.cmd.arg(&format!("/SUBSYSTEM:{subsystem}"));
// Windows has two subsystems we're interested in right now, the console // Windows has two subsystems we're interested in right now, the console
// and windows subsystems. These both implicitly have different entry // and windows subsystems. These both implicitly have different entry
@ -1147,7 +1147,7 @@ impl<'a> Linker for EmLinker<'a> {
&symbols.iter().map(|sym| "_".to_owned() + sym).collect::<Vec<_>>(), &symbols.iter().map(|sym| "_".to_owned() + sym).collect::<Vec<_>>(),
) )
.unwrap(); .unwrap();
debug!("{}", encoded); debug!("{encoded}");
arg.push(encoded); arg.push(encoded);
@ -1350,7 +1350,7 @@ impl<'a> Linker for L4Bender<'a> {
} }
fn link_staticlib(&mut self, lib: &str, _verbatim: bool) { fn link_staticlib(&mut self, lib: &str, _verbatim: bool) {
self.hint_static(); self.hint_static();
self.cmd.arg(format!("-PC{}", lib)); self.cmd.arg(format!("-PC{lib}"));
} }
fn link_rlib(&mut self, lib: &Path) { fn link_rlib(&mut self, lib: &Path) {
self.hint_static(); self.hint_static();
@ -1399,7 +1399,7 @@ impl<'a> Linker for L4Bender<'a> {
fn link_whole_staticlib(&mut self, lib: &str, _verbatim: bool, _search_path: &[PathBuf]) { fn link_whole_staticlib(&mut self, lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
self.hint_static(); self.hint_static();
self.cmd.arg("--whole-archive").arg(format!("-l{}", lib)); self.cmd.arg("--whole-archive").arg(format!("-l{lib}"));
self.cmd.arg("--no-whole-archive"); self.cmd.arg("--no-whole-archive");
} }
@ -1453,7 +1453,7 @@ impl<'a> Linker for L4Bender<'a> {
} }
fn subsystem(&mut self, subsystem: &str) { fn subsystem(&mut self, subsystem: &str) {
self.cmd.arg(&format!("--subsystem {}", subsystem)); self.cmd.arg(&format!("--subsystem {subsystem}"));
} }
fn reset_per_library_state(&mut self) { fn reset_per_library_state(&mut self) {
@ -1518,12 +1518,12 @@ impl<'a> AixLinker<'a> {
impl<'a> Linker for AixLinker<'a> { impl<'a> Linker for AixLinker<'a> {
fn link_dylib(&mut self, lib: &str, _verbatim: bool, _as_needed: bool) { fn link_dylib(&mut self, lib: &str, _verbatim: bool, _as_needed: bool) {
self.hint_dynamic(); self.hint_dynamic();
self.cmd.arg(format!("-l{}", lib)); self.cmd.arg(format!("-l{lib}"));
} }
fn link_staticlib(&mut self, lib: &str, _verbatim: bool) { fn link_staticlib(&mut self, lib: &str, _verbatim: bool) {
self.hint_static(); self.hint_static();
self.cmd.arg(format!("-l{}", lib)); self.cmd.arg(format!("-l{lib}"));
} }
fn link_rlib(&mut self, lib: &Path) { fn link_rlib(&mut self, lib: &Path) {
@ -1573,7 +1573,7 @@ impl<'a> Linker for AixLinker<'a> {
fn link_rust_dylib(&mut self, lib: &str, _: &Path) { fn link_rust_dylib(&mut self, lib: &str, _: &Path) {
self.hint_dynamic(); self.hint_dynamic();
self.cmd.arg(format!("-l{}", lib)); self.cmd.arg(format!("-l{lib}"));
} }
fn link_framework(&mut self, _framework: &str, _as_needed: bool) { fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
@ -1626,12 +1626,12 @@ impl<'a> Linker for AixLinker<'a> {
let mut f = BufWriter::new(File::create(&path)?); let mut f = BufWriter::new(File::create(&path)?);
// FIXME: use llvm-nm to generate export list. // FIXME: use llvm-nm to generate export list.
for symbol in symbols { for symbol in symbols {
debug!(" _{}", symbol); debug!(" _{symbol}");
writeln!(f, " {}", symbol)?; writeln!(f, " {symbol}")?;
} }
}; };
if let Err(e) = res { if let Err(e) = res {
self.sess.fatal(format!("failed to write export file: {}", e)); self.sess.fatal(format!("failed to write export file: {e}"));
} }
self.cmd.arg(format!("-bE:{}", path.to_str().unwrap())); self.cmd.arg(format!("-bE:{}", path.to_str().unwrap()));
} }
@ -1908,7 +1908,7 @@ impl<'a> Linker for BpfLinker<'a> {
let res: io::Result<()> = try { let res: io::Result<()> = try {
let mut f = BufWriter::new(File::create(&path)?); let mut f = BufWriter::new(File::create(&path)?);
for sym in symbols { for sym in symbols {
writeln!(f, "{}", sym)?; writeln!(f, "{sym}")?;
} }
}; };
if let Err(error) = res { if let Err(error) = res {

View File

@ -158,20 +158,19 @@ pub(super) fn get_metadata_xcoff<'a>(path: &Path, data: &'a [u8]) -> Result<&'a
{ {
let offset = metadata_symbol.address() as usize; let offset = metadata_symbol.address() as usize;
if offset < 4 { if offset < 4 {
return Err(format!("Invalid metadata symbol offset: {}", offset)); return Err(format!("Invalid metadata symbol offset: {offset}"));
} }
// The offset specifies the location of rustc metadata in the comment section. // The offset specifies the location of rustc metadata in the comment section.
// The metadata is preceded by a 4-byte length field. // The metadata is preceded by a 4-byte length field.
let len = u32::from_be_bytes(info_data[(offset - 4)..offset].try_into().unwrap()) as usize; let len = u32::from_be_bytes(info_data[(offset - 4)..offset].try_into().unwrap()) as usize;
if offset + len > (info_data.len() as usize) { if offset + len > (info_data.len() as usize) {
return Err(format!( return Err(format!(
"Metadata at offset {} with size {} is beyond .info section", "Metadata at offset {offset} with size {len} is beyond .info section"
offset, len
)); ));
} }
return Ok(&info_data[offset..(offset + len)]); return Ok(&info_data[offset..(offset + len)]);
} else { } else {
return Err(format!("Unable to find symbol {}", AIX_METADATA_SYMBOL_NAME)); return Err(format!("Unable to find symbol {AIX_METADATA_SYMBOL_NAME}"));
}; };
} }

View File

@ -86,7 +86,7 @@ fn get_rpath_relative_to_output(config: &mut RPathConfig<'_>, lib: &Path) -> Str
output.pop(); // strip filename output.pop(); // strip filename
let output = fs::canonicalize(&output).unwrap_or(output); let output = fs::canonicalize(&output).unwrap_or(output);
let relative = path_relative_from(&lib, &output) let relative = path_relative_from(&lib, &output)
.unwrap_or_else(|| panic!("couldn't create relative path from {:?} to {:?}", output, lib)); .unwrap_or_else(|| panic!("couldn't create relative path from {output:?} to {lib:?}"));
// FIXME (#9639): This needs to handle non-utf8 paths // FIXME (#9639): This needs to handle non-utf8 paths
format!("{}/{}", prefix, relative.to_str().expect("non-utf8 component in path")) format!("{}/{}", prefix, relative.to_str().expect("non-utf8 component in path"))
} }

View File

@ -1471,7 +1471,7 @@ fn start_executing_work<B: ExtraBackendMethods>(
} }
} }
Err(e) => { Err(e) => {
let msg = &format!("failed to acquire jobserver token: {}", e); let msg = &format!("failed to acquire jobserver token: {e}");
shared_emitter.fatal(msg); shared_emitter.fatal(msg);
codegen_state = Aborted; codegen_state = Aborted;
} }
@ -2041,7 +2041,7 @@ pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
} }
pub fn pre_lto_bitcode_filename(module_name: &str) -> String { pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
format!("{}.{}", module_name, PRE_LTO_BC_EXT) format!("{module_name}.{PRE_LTO_BC_EXT}")
} }
fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool { fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {

View File

@ -414,7 +414,7 @@ fn push_debuginfo_type_name<'tcx>(
} }
// Type parameters from polymorphized functions. // Type parameters from polymorphized functions.
ty::Param(_) => { ty::Param(_) => {
write!(output, "{:?}", t).unwrap(); write!(output, "{t:?}").unwrap();
} }
ty::Error(_) ty::Error(_)
| ty::Infer(_) | ty::Infer(_)
@ -565,9 +565,9 @@ fn push_disambiguated_special_name(
output: &mut String, output: &mut String,
) { ) {
if cpp_like_debuginfo { if cpp_like_debuginfo {
write!(output, "{}${}", label, disambiguator).unwrap(); write!(output, "{label}${disambiguator}").unwrap();
} else { } else {
write!(output, "{{{}#{}}}", label, disambiguator).unwrap(); write!(output, "{{{label}#{disambiguator}}}").unwrap();
} }
} }
@ -651,15 +651,15 @@ fn push_const_param<'tcx>(tcx: TyCtxt<'tcx>, ct: ty::Const<'tcx>, output: &mut S
ty::Int(ity) => { ty::Int(ity) => {
let bits = ct.eval_bits(tcx, ty::ParamEnv::reveal_all(), ct.ty()); let bits = ct.eval_bits(tcx, ty::ParamEnv::reveal_all(), ct.ty());
let val = Integer::from_int_ty(&tcx, *ity).size().sign_extend(bits) as i128; let val = Integer::from_int_ty(&tcx, *ity).size().sign_extend(bits) as i128;
write!(output, "{}", val) write!(output, "{val}")
} }
ty::Uint(_) => { ty::Uint(_) => {
let val = ct.eval_bits(tcx, ty::ParamEnv::reveal_all(), ct.ty()); let val = ct.eval_bits(tcx, ty::ParamEnv::reveal_all(), ct.ty());
write!(output, "{}", val) write!(output, "{val}")
} }
ty::Bool => { ty::Bool => {
let val = ct.try_eval_bool(tcx, ty::ParamEnv::reveal_all()).unwrap(); let val = ct.try_eval_bool(tcx, ty::ParamEnv::reveal_all()).unwrap();
write!(output, "{}", val) write!(output, "{val}")
} }
_ => { _ => {
// If we cannot evaluate the constant to a known type, we fall back // If we cannot evaluate the constant to a known type, we fall back
@ -678,9 +678,9 @@ fn push_const_param<'tcx>(tcx: TyCtxt<'tcx>, ct: ty::Const<'tcx>, output: &mut S
}); });
if cpp_like_debuginfo(tcx) { if cpp_like_debuginfo(tcx) {
write!(output, "CONST${:x}", hash_short) write!(output, "CONST${hash_short:x}")
} else { } else {
write!(output, "{{CONST#{:x}}}", hash_short) write!(output, "{{CONST#{hash_short:x}}}")
} }
} }
}, },
@ -752,7 +752,7 @@ fn push_close_angle_bracket(cpp_like_debuginfo: bool, output: &mut String) {
} }
fn pop_close_angle_bracket(output: &mut String) { fn pop_close_angle_bracket(output: &mut String) {
assert!(output.ends_with('>'), "'output' does not end with '>': {}", output); assert!(output.ends_with('>'), "'output' does not end with '>': {output}");
output.pop(); output.pop();
if output.ends_with(' ') { if output.ends_with(' ') {
output.pop(); output.pop();

View File

@ -177,31 +177,31 @@ impl IntoDiagnostic<'_> for ThorinErrorWrapper {
} }
thorin::Error::NamelessSection(_, offset) => { thorin::Error::NamelessSection(_, offset) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_section_without_name); diag = handler.struct_err(fluent::codegen_ssa_thorin_section_without_name);
diag.set_arg("offset", format!("0x{:08x}", offset)); diag.set_arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::RelocationWithInvalidSymbol(section, offset) => { thorin::Error::RelocationWithInvalidSymbol(section, offset) => {
diag = diag =
handler.struct_err(fluent::codegen_ssa_thorin_relocation_with_invalid_symbol); handler.struct_err(fluent::codegen_ssa_thorin_relocation_with_invalid_symbol);
diag.set_arg("section", section); diag.set_arg("section", section);
diag.set_arg("offset", format!("0x{:08x}", offset)); diag.set_arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::MultipleRelocations(section, offset) => { thorin::Error::MultipleRelocations(section, offset) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_multiple_relocations); diag = handler.struct_err(fluent::codegen_ssa_thorin_multiple_relocations);
diag.set_arg("section", section); diag.set_arg("section", section);
diag.set_arg("offset", format!("0x{:08x}", offset)); diag.set_arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::UnsupportedRelocation(section, offset) => { thorin::Error::UnsupportedRelocation(section, offset) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_unsupported_relocation); diag = handler.struct_err(fluent::codegen_ssa_thorin_unsupported_relocation);
diag.set_arg("section", section); diag.set_arg("section", section);
diag.set_arg("offset", format!("0x{:08x}", offset)); diag.set_arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::MissingDwoName(id) => { thorin::Error::MissingDwoName(id) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_missing_dwo_name); diag = handler.struct_err(fluent::codegen_ssa_thorin_missing_dwo_name);
diag.set_arg("id", format!("0x{:08x}", id)); diag.set_arg("id", format!("0x{id:08x}"));
diag diag
} }
thorin::Error::NoCompilationUnits => { thorin::Error::NoCompilationUnits => {
@ -251,7 +251,7 @@ impl IntoDiagnostic<'_> for ThorinErrorWrapper {
} }
thorin::Error::StrAtOffset(_, offset) => { thorin::Error::StrAtOffset(_, offset) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_str_at_offset); diag = handler.struct_err(fluent::codegen_ssa_thorin_str_at_offset);
diag.set_arg("offset", format!("0x{:08x}", offset)); diag.set_arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::ParseIndex(_, section) => { thorin::Error::ParseIndex(_, section) => {
@ -261,7 +261,7 @@ impl IntoDiagnostic<'_> for ThorinErrorWrapper {
} }
thorin::Error::UnitNotInIndex(unit) => { thorin::Error::UnitNotInIndex(unit) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_unit_not_in_index); diag = handler.struct_err(fluent::codegen_ssa_thorin_unit_not_in_index);
diag.set_arg("unit", format!("0x{:08x}", unit)); diag.set_arg("unit", format!("0x{unit:08x}"));
diag diag
} }
thorin::Error::RowNotInIndex(_, row) => { thorin::Error::RowNotInIndex(_, row) => {
@ -275,7 +275,7 @@ impl IntoDiagnostic<'_> for ThorinErrorWrapper {
} }
thorin::Error::EmptyUnit(unit) => { thorin::Error::EmptyUnit(unit) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_empty_unit); diag = handler.struct_err(fluent::codegen_ssa_thorin_empty_unit);
diag.set_arg("unit", format!("0x{:08x}", unit)); diag.set_arg("unit", format!("0x{unit:08x}"));
diag diag
} }
thorin::Error::MultipleDebugInfoSection => { thorin::Error::MultipleDebugInfoSection => {
@ -292,12 +292,12 @@ impl IntoDiagnostic<'_> for ThorinErrorWrapper {
} }
thorin::Error::DuplicateUnit(unit) => { thorin::Error::DuplicateUnit(unit) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_duplicate_unit); diag = handler.struct_err(fluent::codegen_ssa_thorin_duplicate_unit);
diag.set_arg("unit", format!("0x{:08x}", unit)); diag.set_arg("unit", format!("0x{unit:08x}"));
diag diag
} }
thorin::Error::MissingReferencedUnit(unit) => { thorin::Error::MissingReferencedUnit(unit) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_missing_referenced_unit); diag = handler.struct_err(fluent::codegen_ssa_thorin_missing_referenced_unit);
diag.set_arg("unit", format!("0x{:08x}", unit)); diag.set_arg("unit", format!("0x{unit:08x}"));
diag diag
} }
thorin::Error::NoOutputObjectCreated => { thorin::Error::NoOutputObjectCreated => {

View File

@ -703,13 +703,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
with_no_trimmed_paths!({ with_no_trimmed_paths!({
if layout.abi.is_uninhabited() { if layout.abi.is_uninhabited() {
// Use this error even for the other intrinsics as it is more precise. // Use this error even for the other intrinsics as it is more precise.
format!("attempted to instantiate uninhabited type `{}`", ty) format!("attempted to instantiate uninhabited type `{ty}`")
} else if requirement == ValidityRequirement::Zero { } else if requirement == ValidityRequirement::Zero {
format!("attempted to zero-initialize type `{}`, which is invalid", ty) format!("attempted to zero-initialize type `{ty}`, which is invalid")
} else { } else {
format!( format!(
"attempted to leave type `{}` uninitialized, which is invalid", "attempted to leave type `{ty}` uninitialized, which is invalid"
ty
) )
} }
}) })
@ -1045,10 +1044,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
assert_eq!( assert_eq!(
fn_abi.args.len(), fn_abi.args.len(),
mir_args + 1, mir_args + 1,
"#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {:?} {:?} {:?}", "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
instance,
fn_span,
fn_abi,
); );
let location = let location =
self.get_caller_location(bx, mir::SourceInfo { span: fn_span, ..source_info }); self.get_caller_location(bx, mir::SourceInfo { span: fn_span, ..source_info });
@ -1555,7 +1551,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock { fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
let llbb = self.llbb(bb); let llbb = self.llbb(bb);
if base::wants_new_eh_instructions(self.cx.sess()) { if base::wants_new_eh_instructions(self.cx.sess()) {
let cleanup_bb = Bx::append_block(self.cx, self.llfn, &format!("funclet_{:?}", bb)); let cleanup_bb = Bx::append_block(self.cx, self.llfn, &format!("funclet_{bb:?}"));
let mut cleanup_bx = Bx::build(self.cx, cleanup_bb); let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
let funclet = cleanup_bx.cleanup_pad(None, &[]); let funclet = cleanup_bx.cleanup_pad(None, &[]);
cleanup_bx.br(llbb); cleanup_bx.br(llbb);
@ -1675,7 +1671,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
match self.cached_llbbs[bb] { match self.cached_llbbs[bb] {
CachedLlbb::None => { CachedLlbb::None => {
// FIXME(eddyb) only name the block if `fewer_names` is `false`. // FIXME(eddyb) only name the block if `fewer_names` is `false`.
let llbb = Bx::append_block(self.cx, self.llfn, &format!("{:?}", bb)); let llbb = Bx::append_block(self.cx, self.llfn, &format!("{bb:?}"));
self.cached_llbbs[bb] = CachedLlbb::Some(llbb); self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
Some(llbb) Some(llbb)
} }

View File

@ -337,7 +337,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
} else { } else {
Some(match whole_local_var.or(fallback_var.clone()) { Some(match whole_local_var.or(fallback_var.clone()) {
Some(var) if var.name != kw::Empty => var.name.to_string(), Some(var) if var.name != kw::Empty => var.name.to_string(),
_ => format!("{:?}", local), _ => format!("{local:?}"),
}) })
}; };

View File

@ -397,8 +397,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
) -> OperandRef<'tcx, Bx::Value> { ) -> OperandRef<'tcx, Bx::Value> {
assert!( assert!(
self.rvalue_creates_operand(rvalue, DUMMY_SP), self.rvalue_creates_operand(rvalue, DUMMY_SP),
"cannot codegen {:?} to operand", "cannot codegen {rvalue:?} to operand",
rvalue,
); );
match *rvalue { match *rvalue {

View File

@ -140,8 +140,8 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {
MonoItem::Fn(instance) => { MonoItem::Fn(instance) => {
format!("Fn({:?}, {})", instance.def, instance.args.as_ptr().addr()) format!("Fn({:?}, {})", instance.def, instance.args.as_ptr().addr())
} }
MonoItem::Static(id) => format!("Static({:?})", id), MonoItem::Static(id) => format!("Static({id:?})"),
MonoItem::GlobalAsm(id) => format!("GlobalAsm({:?})", id), MonoItem::GlobalAsm(id) => format!("GlobalAsm({id:?})"),
} }
} }
} }

View File

@ -369,9 +369,9 @@ pub fn from_target_feature(
// We allow comma separation to enable multiple features. // We allow comma separation to enable multiple features.
target_features.extend(value.as_str().split(',').filter_map(|feature| { target_features.extend(value.as_str().split(',').filter_map(|feature| {
let Some(feature_gate) = supported_target_features.get(feature) else { let Some(feature_gate) = supported_target_features.get(feature) else {
let msg = format!("the feature named `{}` is not valid for this target", feature); let msg = format!("the feature named `{feature}` is not valid for this target");
let mut err = tcx.sess.struct_span_err(item.span(), msg); let mut err = tcx.sess.struct_span_err(item.span(), msg);
err.span_label(item.span(), format!("`{}` is not valid for this target", feature)); err.span_label(item.span(), format!("`{feature}` is not valid for this target"));
if let Some(stripped) = feature.strip_prefix('+') { if let Some(stripped) = feature.strip_prefix('+') {
let valid = supported_target_features.contains_key(stripped); let valid = supported_target_features.contains_key(stripped);
if valid { if valid {
@ -405,7 +405,7 @@ pub fn from_target_feature(
&tcx.sess.parse_sess, &tcx.sess.parse_sess,
feature_gate.unwrap(), feature_gate.unwrap(),
item.span(), item.span(),
format!("the target feature `{}` is currently unstable", feature), format!("the target feature `{feature}` is currently unstable"),
) )
.emit(); .emit();
} }

View File

@ -241,16 +241,16 @@ fn dump_graph(query: &DepGraphQuery) {
{ {
// dump a .txt file with just the edges: // dump a .txt file with just the edges:
let txt_path = format!("{}.txt", path); let txt_path = format!("{path}.txt");
let mut file = BufWriter::new(File::create(&txt_path).unwrap()); let mut file = BufWriter::new(File::create(&txt_path).unwrap());
for (source, target) in &edges { for (source, target) in &edges {
write!(file, "{:?} -> {:?}\n", source, target).unwrap(); write!(file, "{source:?} -> {target:?}\n").unwrap();
} }
} }
{ {
// dump a .dot file in graphviz format: // dump a .dot file in graphviz format:
let dot_path = format!("{}.dot", path); let dot_path = format!("{path}.dot");
let mut v = Vec::new(); let mut v = Vec::new();
dot::render(&GraphvizDepGraph(nodes, edges), &mut v).unwrap(); dot::render(&GraphvizDepGraph(nodes, edges), &mut v).unwrap();
fs::write(dot_path, v).unwrap(); fs::write(dot_path, v).unwrap();
@ -285,7 +285,7 @@ impl<'a> dot::Labeller<'a> for GraphvizDepGraph {
dot::Id::new("DependencyGraph").unwrap() dot::Id::new("DependencyGraph").unwrap()
} }
fn node_id(&self, n: &DepKind) -> dot::Id<'_> { fn node_id(&self, n: &DepKind) -> dot::Id<'_> {
let s: String = format!("{:?}", n) let s: String = format!("{n:?}")
.chars() .chars()
.map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' }) .map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' })
.collect(); .collect();
@ -293,7 +293,7 @@ impl<'a> dot::Labeller<'a> for GraphvizDepGraph {
dot::Id::new(s).unwrap() dot::Id::new(s).unwrap()
} }
fn node_label(&self, n: &DepKind) -> dot::LabelText<'_> { fn node_label(&self, n: &DepKind) -> dot::LabelText<'_> {
dot::LabelText::label(format!("{:?}", n)) dot::LabelText::label(format!("{n:?}"))
} }
} }

View File

@ -300,7 +300,7 @@ impl<'tcx> DirtyCleanVisitor<'tcx> {
}, },
_ => self.tcx.sess.emit_fatal(errors::UndefinedCleanDirty { _ => self.tcx.sess.emit_fatal(errors::UndefinedCleanDirty {
span: attr.span, span: attr.span,
kind: format!("{:?}", node), kind: format!("{node:?}"),
}), }),
}; };
let labels = let labels =

View File

@ -427,13 +427,11 @@ fn copy_files(sess: &Session, target_dir: &Path, source_dir: &Path) -> Result<bo
if sess.opts.unstable_opts.incremental_info { if sess.opts.unstable_opts.incremental_info {
eprintln!( eprintln!(
"[incremental] session directory: \ "[incremental] session directory: \
{} files hard-linked", {files_linked} files hard-linked"
files_linked
); );
eprintln!( eprintln!(
"[incremental] session directory: \ "[incremental] session directory: \
{} files copied", {files_copied} files copied"
files_copied
); );
} }
@ -604,7 +602,7 @@ fn crate_path(sess: &Session, crate_name: Symbol, stable_crate_id: StableCrateId
let stable_crate_id = base_n::encode(stable_crate_id.as_u64() as u128, INT_ENCODE_BASE); let stable_crate_id = base_n::encode(stable_crate_id.as_u64() as u128, INT_ENCODE_BASE);
let crate_name = format!("{}-{}", crate_name, stable_crate_id); let crate_name = format!("{crate_name}-{stable_crate_id}");
incr_dir.join(crate_name) incr_dir.join(crate_name)
} }

View File

@ -210,10 +210,8 @@ impl<'a> SourceKindMultiSuggestion<'a> {
_ => ("", ""), _ => ("", ""),
}; };
let (start_span, start_span_code, end_span) = match should_wrap_expr { let (start_span, start_span_code, end_span) = match should_wrap_expr {
Some(end_span) => { Some(end_span) => (data.span(), format!("{arrow}{ty_info}{post}{{ "), Some(end_span)),
(data.span(), format!("{}{}{}{{ ", arrow, ty_info, post), Some(end_span)) None => (data.span(), format!("{arrow}{ty_info}{post}"), None),
}
None => (data.span(), format!("{}{}{}", arrow, ty_info, post), None),
}; };
Self::ClosureReturn { start_span, start_span_code, end_span } Self::ClosureReturn { start_span, start_span_code, end_span }
} }
@ -404,9 +402,9 @@ impl AddToDiagnostic for AddLifetimeParamsSuggestion<'_> {
debug!(?lifetime_sub.ident.span); debug!(?lifetime_sub.ident.span);
let make_suggestion = |ident: Ident| { let make_suggestion = |ident: Ident| {
let sugg = if ident.name == kw::Empty { let sugg = if ident.name == kw::Empty {
format!("{}, ", suggestion_param_name) format!("{suggestion_param_name}, ")
} else if ident.name == kw::UnderscoreLifetime && ident.span.is_empty() { } else if ident.name == kw::UnderscoreLifetime && ident.span.is_empty() {
format!("{} ", suggestion_param_name) format!("{suggestion_param_name} ")
} else { } else {
suggestion_param_name.clone() suggestion_param_name.clone()
}; };
@ -419,9 +417,9 @@ impl AddToDiagnostic for AddLifetimeParamsSuggestion<'_> {
let new_param_suggestion = if let Some(first) = let new_param_suggestion = if let Some(first) =
generics.params.iter().find(|p| !p.name.ident().span.is_empty()) generics.params.iter().find(|p| !p.name.ident().span.is_empty())
{ {
(first.span.shrink_to_lo(), format!("{}, ", suggestion_param_name)) (first.span.shrink_to_lo(), format!("{suggestion_param_name}, "))
} else { } else {
(generics.span, format!("<{}>", suggestion_param_name)) (generics.span, format!("<{suggestion_param_name}>"))
}; };
suggestions.push(new_param_suggestion); suggestions.push(new_param_suggestion);
@ -1320,7 +1318,7 @@ impl AddToDiagnostic for SuggestTuplePatternMany {
message, message,
self.compatible_variants.into_iter().map(|variant| { self.compatible_variants.into_iter().map(|variant| {
vec![ vec![
(self.cause_span.shrink_to_lo(), format!("{}(", variant)), (self.cause_span.shrink_to_lo(), format!("{variant}(")),
(self.cause_span.shrink_to_hi(), ")".to_string()), (self.cause_span.shrink_to_hi(), ")".to_string()),
] ]
}), }),

View File

@ -80,7 +80,7 @@ impl<'a> DescriptionCtx<'a> {
// We shouldn't really be having unification failures with ReVar // We shouldn't really be having unification failures with ReVar
// and ReLateBound though. // and ReLateBound though.
ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => { ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
(alt_span, "revar", format!("{:?}", region)) (alt_span, "revar", format!("{region:?}"))
} }
}; };
Some(DescriptionCtx { span, kind, arg }) Some(DescriptionCtx { span, kind, arg })

View File

@ -205,7 +205,7 @@ impl CanonicalizeMode for CanonicalizeQueryResponse {
// `delay_span_bug` to allow type error over an ICE. // `delay_span_bug` to allow type error over an ICE.
canonicalizer.tcx.sess.delay_span_bug( canonicalizer.tcx.sess.delay_span_bug(
rustc_span::DUMMY_SP, rustc_span::DUMMY_SP,
format!("unexpected region in query response: `{:?}`", r), format!("unexpected region in query response: `{r:?}`"),
); );
r r
} }

View File

@ -177,7 +177,7 @@ impl<'tcx> InferCtxt<'tcx> {
self.tcx.check_tys_might_be_eq(canonical).map_err(|_| { self.tcx.check_tys_might_be_eq(canonical).map_err(|_| {
self.tcx.sess.delay_span_bug( self.tcx.sess.delay_span_bug(
DUMMY_SP, DUMMY_SP,
format!("cannot relate consts of different types (a={:?}, b={:?})", a, b,), format!("cannot relate consts of different types (a={a:?}, b={b:?})",),
) )
}) })
}); });

View File

@ -238,7 +238,7 @@ fn msg_span_from_named_region<'tcx>(
let text = if name == kw::UnderscoreLifetime { let text = if name == kw::UnderscoreLifetime {
"the anonymous lifetime as defined here".to_string() "the anonymous lifetime as defined here".to_string()
} else { } else {
format!("the lifetime `{}` as defined here", name) format!("the lifetime `{name}` as defined here")
}; };
(text, Some(span)) (text, Some(span))
} }
@ -250,7 +250,7 @@ fn msg_span_from_named_region<'tcx>(
}) })
), ),
_ => ( _ => (
format!("the lifetime `{}` as defined here", region), format!("the lifetime `{region}` as defined here"),
Some(tcx.def_span(scope)), Some(tcx.def_span(scope)),
), ),
} }
@ -280,7 +280,7 @@ fn emit_msg_span(
span: Option<Span>, span: Option<Span>,
suffix: &str, suffix: &str,
) { ) {
let message = format!("{}{}{}", prefix, description, suffix); let message = format!("{prefix}{description}{suffix}");
if let Some(span) = span { if let Some(span) = span {
err.span_note(span, message); err.span_note(span, message);
@ -296,7 +296,7 @@ fn label_msg_span(
span: Option<Span>, span: Option<Span>,
suffix: &str, suffix: &str,
) { ) {
let message = format!("{}{}{}", prefix, description, suffix); let message = format!("{prefix}{description}{suffix}");
if let Some(span) = span { if let Some(span) = span {
err.span_label(span, message); err.span_label(span, message);
@ -333,7 +333,7 @@ pub fn unexpected_hidden_region_diagnostic<'tcx>(
explain_free_region( explain_free_region(
tcx, tcx,
&mut err, &mut err,
&format!("hidden type `{}` captures ", hidden_ty), &format!("hidden type `{hidden_ty}` captures "),
hidden_region, hidden_region,
"", "",
); );
@ -345,7 +345,7 @@ pub fn unexpected_hidden_region_diagnostic<'tcx>(
fn_returns, fn_returns,
hidden_region.to_string(), hidden_region.to_string(),
None, None,
format!("captures `{}`", hidden_region), format!("captures `{hidden_region}`"),
None, None,
Some(reg_info.def_id), Some(reg_info.def_id),
) )
@ -373,7 +373,7 @@ pub fn unexpected_hidden_region_diagnostic<'tcx>(
note_and_explain_region( note_and_explain_region(
tcx, tcx,
&mut err, &mut err,
&format!("hidden type `{}` captures ", hidden_ty), &format!("hidden type `{hidden_ty}` captures "),
hidden_region, hidden_region,
"", "",
None, None,
@ -716,7 +716,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
{ {
err.span_label(span, format!("this is an iterator with items of type `{}`", args.type_at(0))); err.span_label(span, format!("this is an iterator with items of type `{}`", args.type_at(0)));
} else { } else {
err.span_label(span, format!("this expression has type `{}`", ty)); err.span_label(span, format!("this expression has type `{ty}`"));
} }
} }
if let Some(ty::error::ExpectedFound { found, .. }) = exp_found if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
@ -726,7 +726,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
err.span_suggestion( err.span_suggestion(
span, span,
"consider dereferencing the boxed value", "consider dereferencing the boxed value",
format!("*{}", snippet), format!("*{snippet}"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} }
@ -785,13 +785,13 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
if prior_arms.len() <= 4 { if prior_arms.len() <= 4 {
for sp in prior_arms { for sp in prior_arms {
any_multiline_arm |= source_map.is_multiline(*sp); any_multiline_arm |= source_map.is_multiline(*sp);
err.span_label(*sp, format!("this is found to be of type `{}`", t)); err.span_label(*sp, format!("this is found to be of type `{t}`"));
} }
} else if let Some(sp) = prior_arms.last() { } else if let Some(sp) = prior_arms.last() {
any_multiline_arm |= source_map.is_multiline(*sp); any_multiline_arm |= source_map.is_multiline(*sp);
err.span_label( err.span_label(
*sp, *sp,
format!("this and all prior arms are found to be of type `{}`", t), format!("this and all prior arms are found to be of type `{t}`"),
); );
} }
let outer = if any_multiline_arm || !source_map.is_multiline(cause.span) { let outer = if any_multiline_arm || !source_map.is_multiline(cause.span) {
@ -1661,7 +1661,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
.. ..
})) = values })) = values
{ {
Cow::from(format!("expected this to be `{}`", expected)) Cow::from(format!("expected this to be `{expected}`"))
} else { } else {
terr.to_string(self.tcx) terr.to_string(self.tcx)
}; };
@ -2368,13 +2368,13 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
} }
let labeled_user_string = match bound_kind { let labeled_user_string = match bound_kind {
GenericKind::Param(ref p) => format!("the parameter type `{}`", p), GenericKind::Param(ref p) => format!("the parameter type `{p}`"),
GenericKind::Alias(ref p) => match p.kind(self.tcx) { GenericKind::Alias(ref p) => match p.kind(self.tcx) {
ty::AliasKind::Projection | ty::AliasKind::Inherent => { ty::AliasKind::Projection | ty::AliasKind::Inherent => {
format!("the associated type `{}`", p) format!("the associated type `{p}`")
} }
ty::AliasKind::Weak => format!("the type alias `{}`", p), ty::AliasKind::Weak => format!("the type alias `{p}`"),
ty::AliasKind::Opaque => format!("the opaque type `{}`", p), ty::AliasKind::Opaque => format!("the opaque type `{p}`"),
}, },
}; };
@ -2388,7 +2388,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
span, span,
impl_item_def_id, impl_item_def_id,
trait_item_def_id, trait_item_def_id,
&format!("`{}: {}`", bound_kind, sub), &format!("`{bound_kind}: {sub}`"),
); );
} }
@ -2402,7 +2402,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
let msg = "consider adding an explicit lifetime bound"; let msg = "consider adding an explicit lifetime bound";
if let Some((sp, has_lifetimes)) = type_param_span { if let Some((sp, has_lifetimes)) = type_param_span {
let suggestion = let suggestion =
if has_lifetimes { format!(" + {}", sub) } else { format!(": {}", sub) }; if has_lifetimes { format!(" + {sub}") } else { format!(": {sub}") };
let mut suggestions = vec![(sp, suggestion)]; let mut suggestions = vec![(sp, suggestion)];
for add_lt_sugg in add_lt_suggs.into_iter().flatten() { for add_lt_sugg in add_lt_suggs.into_iter().flatten() {
suggestions.push(add_lt_sugg); suggestions.push(add_lt_sugg);
@ -2413,7 +2413,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
Applicability::MaybeIncorrect, // Issue #41966 Applicability::MaybeIncorrect, // Issue #41966
); );
} else { } else {
let consider = format!("{} `{}: {}`...", msg, bound_kind, sub); let consider = format!("{msg} `{bound_kind}: {sub}`...");
err.help(consider); err.help(consider);
} }
} }
@ -2422,13 +2422,10 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
|err: &mut Diagnostic, type_param_span: Option<(Span, bool)>| { |err: &mut Diagnostic, type_param_span: Option<(Span, bool)>| {
let msg = "consider introducing an explicit lifetime bound"; let msg = "consider introducing an explicit lifetime bound";
if let Some((sp, has_lifetimes)) = type_param_span { if let Some((sp, has_lifetimes)) = type_param_span {
let suggestion = if has_lifetimes { let suggestion =
format!(" + {}", new_lt) if has_lifetimes { format!(" + {new_lt}") } else { format!(": {new_lt}") };
} else {
format!(": {}", new_lt)
};
let mut sugg = let mut sugg =
vec![(sp, suggestion), (span.shrink_to_hi(), format!(" + {}", new_lt))]; vec![(sp, suggestion), (span.shrink_to_hi(), format!(" + {new_lt}"))];
for lt in add_lt_suggs.clone().into_iter().flatten() { for lt in add_lt_suggs.clone().into_iter().flatten() {
sugg.push(lt); sugg.push(lt);
sugg.rotate_right(1); sugg.rotate_right(1);
@ -2508,7 +2505,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
"{} may not live long enough", "{} may not live long enough",
labeled_user_string labeled_user_string
); );
let pred = format!("{}: {}", bound_kind, sub); let pred = format!("{bound_kind}: {sub}");
let suggestion = format!("{} {}", generics.add_where_or_trailing_comma(), pred,); let suggestion = format!("{} {}", generics.add_where_or_trailing_comma(), pred,);
err.span_suggestion( err.span_suggestion(
generics.tail_span_for_predicate_suggestion(), generics.tail_span_for_predicate_suggestion(),
@ -2564,7 +2561,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
note_and_explain_region( note_and_explain_region(
self.tcx, self.tcx,
&mut err, &mut err,
&format!("{} must be valid for ", labeled_user_string), &format!("{labeled_user_string} must be valid for "),
sub, sub,
"...", "...",
None, None,
@ -2814,10 +2811,10 @@ impl<'tcx> InferCtxt<'tcx> {
br_string(br), br_string(br),
self.tcx.associated_item(def_id).name self.tcx.associated_item(def_id).name
), ),
infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name), infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{name}`"),
infer::UpvarRegion(ref upvar_id, _) => { infer::UpvarRegion(ref upvar_id, _) => {
let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id); let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
format!(" for capture of `{}` by closure", var_name) format!(" for capture of `{var_name}` by closure")
} }
infer::Nll(..) => bug!("NLL variable found in lexical phase"), infer::Nll(..) => bug!("NLL variable found in lexical phase"),
}; };

View File

@ -246,7 +246,7 @@ fn closure_as_fn_str<'tcx>(infcx: &InferCtxt<'tcx>, ty: Ty<'tcx>) -> String {
} else { } else {
format!(" -> {}", ty_to_string(infcx, fn_sig.output().skip_binder(), None)) format!(" -> {}", ty_to_string(infcx, fn_sig.output().skip_binder(), None))
}; };
format!("fn({}){}", args, ret) format!("fn({args}){ret}")
} }
impl<'tcx> InferCtxt<'tcx> { impl<'tcx> InferCtxt<'tcx> {

View File

@ -235,10 +235,10 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
} }
let arg = match param.param.pat.simple_ident() { let arg = match param.param.pat.simple_ident() {
Some(simple_ident) => format!("argument `{}`", simple_ident), Some(simple_ident) => format!("argument `{simple_ident}`"),
None => "the argument".to_string(), None => "the argument".to_string(),
}; };
let captures = format!("captures data from {}", arg); let captures = format!("captures data from {arg}");
suggest_new_region_bound( suggest_new_region_bound(
tcx, tcx,
&mut err, &mut err,
@ -269,11 +269,11 @@ pub fn suggest_new_region_bound(
// FIXME: account for the need of parens in `&(dyn Trait + '_)` // FIXME: account for the need of parens in `&(dyn Trait + '_)`
let consider = "consider changing"; let consider = "consider changing";
let declare = "to declare that"; let declare = "to declare that";
let explicit = format!("you can add an explicit `{}` lifetime bound", lifetime_name); let explicit = format!("you can add an explicit `{lifetime_name}` lifetime bound");
let explicit_static = let explicit_static =
arg.map(|arg| format!("explicit `'static` bound to the lifetime of {}", arg)); arg.map(|arg| format!("explicit `'static` bound to the lifetime of {arg}"));
let add_static_bound = "alternatively, add an explicit `'static` bound to this reference"; let add_static_bound = "alternatively, add an explicit `'static` bound to this reference";
let plus_lt = format!(" + {}", lifetime_name); let plus_lt = format!(" + {lifetime_name}");
for fn_return in fn_returns { for fn_return in fn_returns {
if fn_return.span.desugaring_kind().is_some() { if fn_return.span.desugaring_kind().is_some() {
// Skip `async` desugaring `impl Future`. // Skip `async` desugaring `impl Future`.
@ -383,12 +383,7 @@ pub fn suggest_new_region_bound(
if let LifetimeName::ImplicitObjectLifetimeDefault = lt.res { if let LifetimeName::ImplicitObjectLifetimeDefault = lt.res {
err.span_suggestion_verbose( err.span_suggestion_verbose(
fn_return.span.shrink_to_hi(), fn_return.span.shrink_to_hi(),
format!( format!("{declare} the trait object {captures}, {explicit}",),
"{declare} the trait object {captures}, {explicit}",
declare = declare,
captures = captures,
explicit = explicit,
),
&plus_lt, &plus_lt,
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
@ -400,7 +395,7 @@ pub fn suggest_new_region_bound(
if let Some(explicit_static) = &explicit_static { if let Some(explicit_static) = &explicit_static {
err.span_suggestion_verbose( err.span_suggestion_verbose(
lt.ident.span, lt.ident.span,
format!("{} the trait object's {}", consider, explicit_static), format!("{consider} the trait object's {explicit_static}"),
&lifetime_name, &lifetime_name,
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );

View File

@ -227,7 +227,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
span, span,
impl_item_def_id, impl_item_def_id,
trait_item_def_id, trait_item_def_id,
&format!("`{}: {}`", sup, sub), &format!("`{sup}: {sub}`"),
); );
// We should only suggest rewriting the `where` clause if the predicate is within that `where` clause // We should only suggest rewriting the `where` clause if the predicate is within that `where` clause
if let Some(generics) = self.tcx.hir().get_generics(impl_item_def_id) if let Some(generics) = self.tcx.hir().get_generics(impl_item_def_id)
@ -251,7 +251,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
let item_name = self.tcx.item_name(impl_item_def_id.to_def_id()); let item_name = self.tcx.item_name(impl_item_def_id.to_def_id());
err.span_label( err.span_label(
trait_item_span, trait_item_span,
format!("definition of `{}` from trait", item_name), format!("definition of `{item_name}` from trait"),
); );
} }

View File

@ -47,7 +47,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
diag.span_suggestion( diag.span_suggestion(
sp, sp,
"use a float literal", "use a float literal",
format!("{}.0", snippet), format!("{snippet}.0"),
MachineApplicable, MachineApplicable,
); );
} }
@ -134,7 +134,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
if matched_end_of_args { if matched_end_of_args {
// Append suggestion to the end of our args // Append suggestion to the end of our args
let path = format!(", {}{} = {}",item_name, item_args, p); let path = format!(", {item_name}{item_args} = {p}");
note = !suggest_constraining_type_param( note = !suggest_constraining_type_param(
tcx, tcx,
generics, generics,
@ -148,7 +148,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
// Suggest adding a bound to an existing trait // Suggest adding a bound to an existing trait
// or if the trait doesn't exist, add the trait // or if the trait doesn't exist, add the trait
// and the suggested bounds. // and the suggested bounds.
let path = format!("<{}{} = {}>", item_name, item_args, p); let path = format!("<{item_name}{item_args} = {p}>");
note = !suggest_constraining_type_param( note = !suggest_constraining_type_param(
tcx, tcx,
generics, generics,
@ -213,8 +213,7 @@ impl<T> Trait<T> for X {
} }
diag.help(format!( diag.help(format!(
"every closure has a distinct type and so could not always match the \ "every closure has a distinct type and so could not always match the \
caller-chosen type of parameter `{}`", caller-chosen type of parameter `{p}`"
p
)); ));
} }
(ty::Param(p), _) | (_, ty::Param(p)) => { (ty::Param(p), _) | (_, ty::Param(p)) => {

View File

@ -575,12 +575,12 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
if param_hir.pat.span == param_hir.ty_span { if param_hir.pat.span == param_hir.ty_span {
// for `|x|`, `|_|`, `|x: impl Foo|` // for `|x|`, `|_|`, `|x: impl Foo|`
let Ok(pat) = self.tcx.sess.source_map().span_to_snippet(param_hir.pat.span) else { return; }; let Ok(pat) = self.tcx.sess.source_map().span_to_snippet(param_hir.pat.span) else { return; };
suggestion += &format!("{}: &_", pat); suggestion += &format!("{pat}: &_");
} else { } else {
// for `|x: ty|`, `|_: ty|` // for `|x: ty|`, `|_: ty|`
let Ok(pat) = self.tcx.sess.source_map().span_to_snippet(param_hir.pat.span) else { return; }; let Ok(pat) = self.tcx.sess.source_map().span_to_snippet(param_hir.pat.span) else { return; };
let Ok(ty) = self.tcx.sess.source_map().span_to_snippet(param_hir.ty_span) else { return; }; let Ok(ty) = self.tcx.sess.source_map().span_to_snippet(param_hir.ty_span) else { return; };
suggestion += &format!("{}: &{}", pat, ty); suggestion += &format!("{pat}: &{ty}");
} }
has_suggestion = true; has_suggestion = true;
} else { } else {

View File

@ -837,9 +837,8 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> {
self.var_infos[node_idx].origin.span(), self.var_infos[node_idx].origin.span(),
format!( format!(
"collect_error_for_expanding_node() could not find \ "collect_error_for_expanding_node() could not find \
error for var {:?} in universe {:?}, lower_bounds={:#?}, \ error for var {node_idx:?} in universe {node_universe:?}, lower_bounds={lower_bounds:#?}, \
upper_bounds={:#?}", upper_bounds={upper_bounds:#?}"
node_idx, node_universe, lower_bounds, upper_bounds
), ),
); );
} }

View File

@ -557,7 +557,7 @@ where
// Forbid inference variables in the RHS. // Forbid inference variables in the RHS.
self.infcx.tcx.sess.delay_span_bug( self.infcx.tcx.sess.delay_span_bug(
self.delegate.span(), self.delegate.span(),
format!("unexpected inference var {:?}", b,), format!("unexpected inference var {b:?}",),
); );
Ok(a) Ok(a)
} }

View File

@ -253,7 +253,7 @@ where
// this point it never will be // this point it never will be
self.tcx.sess.delay_span_bug( self.tcx.sess.delay_span_bug(
origin.span(), origin.span(),
format!("unresolved inference variable in outlives: {:?}", v), format!("unresolved inference variable in outlives: {v:?}"),
); );
} }
} }

View File

@ -179,7 +179,7 @@ impl<'cx, 'tcx> VerifyBoundCx<'cx, 'tcx> {
// this point it never will be // this point it never will be
self.tcx.sess.delay_span_bug( self.tcx.sess.delay_span_bug(
rustc_span::DUMMY_SP, rustc_span::DUMMY_SP,
format!("unresolved inference variable in outlives: {:?}", v), format!("unresolved inference variable in outlives: {v:?}"),
); );
// add a bound that never holds // add a bound that never holds
VerifyBound::AnyBound(vec![]) VerifyBound::AnyBound(vec![])

View File

@ -704,8 +704,8 @@ impl fmt::Debug for RegionSnapshot {
impl<'tcx> fmt::Debug for GenericKind<'tcx> { impl<'tcx> fmt::Debug for GenericKind<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
GenericKind::Param(ref p) => write!(f, "{:?}", p), GenericKind::Param(ref p) => write!(f, "{p:?}"),
GenericKind::Alias(ref p) => write!(f, "{:?}", p), GenericKind::Alias(ref p) => write!(f, "{p:?}"),
} }
} }
} }
@ -713,8 +713,8 @@ impl<'tcx> fmt::Debug for GenericKind<'tcx> {
impl<'tcx> fmt::Display for GenericKind<'tcx> { impl<'tcx> fmt::Display for GenericKind<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
GenericKind::Param(ref p) => write!(f, "{}", p), GenericKind::Param(ref p) => write!(f, "{p}"),
GenericKind::Alias(ref p) => write!(f, "{}", p), GenericKind::Alias(ref p) => write!(f, "{p}"),
} }
} }
} }

View File

@ -28,11 +28,11 @@ impl<'tcx> InferCtxt<'tcx> {
if !self.tcx.is_impl_trait_in_trait(trait_item_def_id) { if !self.tcx.is_impl_trait_in_trait(trait_item_def_id) {
if let Some(span) = self.tcx.hir().span_if_local(trait_item_def_id) { if let Some(span) = self.tcx.hir().span_if_local(trait_item_def_id) {
let item_name = self.tcx.item_name(impl_item_def_id.to_def_id()); let item_name = self.tcx.item_name(impl_item_def_id.to_def_id());
err.span_label(span, format!("definition of `{}` from trait", item_name)); err.span_label(span, format!("definition of `{item_name}` from trait"));
} }
} }
err.span_label(error_span, format!("impl has extra requirement {}", requirement)); err.span_label(error_span, format!("impl has extra requirement {requirement}"));
err err
} }
@ -56,7 +56,7 @@ pub fn report_object_safety_error<'tcx>(
"the trait `{}` cannot be made into an object", "the trait `{}` cannot be made into an object",
trait_str trait_str
); );
err.span_label(span, format!("`{}` cannot be made into an object", trait_str)); err.span_label(span, format!("`{trait_str}` cannot be made into an object"));
let mut reported_violations = FxIndexSet::default(); let mut reported_violations = FxIndexSet::default();
let mut multi_span = vec![]; let mut multi_span = vec![];

View File

@ -190,7 +190,7 @@ impl<'tcx> ProjectionCache<'_, 'tcx> {
} }
let fresh_key = let fresh_key =
map.insert(key, ProjectionCacheEntry::NormalizedTy { ty: value, complete: None }); map.insert(key, ProjectionCacheEntry::NormalizedTy { ty: value, complete: None });
assert!(!fresh_key, "never started projecting `{:?}`", key); assert!(!fresh_key, "never started projecting `{key:?}`");
} }
/// Mark the relevant projection cache key as having its derived obligations /// Mark the relevant projection cache key as having its derived obligations
@ -229,7 +229,7 @@ impl<'tcx> ProjectionCache<'_, 'tcx> {
/// be different). /// be different).
pub fn ambiguous(&mut self, key: ProjectionCacheKey<'tcx>) { pub fn ambiguous(&mut self, key: ProjectionCacheKey<'tcx>) {
let fresh = self.map().insert(key, ProjectionCacheEntry::Ambiguous); let fresh = self.map().insert(key, ProjectionCacheEntry::Ambiguous);
assert!(!fresh, "never started projecting `{:?}`", key); assert!(!fresh, "never started projecting `{key:?}`");
} }
/// Indicates that while trying to normalize `key`, `key` was required to /// Indicates that while trying to normalize `key`, `key` was required to
@ -237,14 +237,14 @@ impl<'tcx> ProjectionCache<'_, 'tcx> {
/// an error here. /// an error here.
pub fn recur(&mut self, key: ProjectionCacheKey<'tcx>) { pub fn recur(&mut self, key: ProjectionCacheKey<'tcx>) {
let fresh = self.map().insert(key, ProjectionCacheEntry::Recur); let fresh = self.map().insert(key, ProjectionCacheEntry::Recur);
assert!(!fresh, "never started projecting `{:?}`", key); assert!(!fresh, "never started projecting `{key:?}`");
} }
/// Indicates that trying to normalize `key` resulted in /// Indicates that trying to normalize `key` resulted in
/// error. /// error.
pub fn error(&mut self, key: ProjectionCacheKey<'tcx>) { pub fn error(&mut self, key: ProjectionCacheKey<'tcx>) {
let fresh = self.map().insert(key, ProjectionCacheEntry::Error); let fresh = self.map().insert(key, ProjectionCacheEntry::Error);
assert!(!fresh, "never started projecting `{:?}`", key); assert!(!fresh, "never started projecting `{key:?}`");
} }
} }

View File

@ -38,17 +38,17 @@ impl<'tcx> fmt::Debug for traits::FulfillmentError<'tcx> {
impl<'tcx> fmt::Debug for traits::FulfillmentErrorCode<'tcx> { impl<'tcx> fmt::Debug for traits::FulfillmentErrorCode<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
super::CodeSelectionError(ref e) => write!(f, "{:?}", e), super::CodeSelectionError(ref e) => write!(f, "{e:?}"),
super::CodeProjectionError(ref e) => write!(f, "{:?}", e), super::CodeProjectionError(ref e) => write!(f, "{e:?}"),
super::CodeSubtypeError(ref a, ref b) => { super::CodeSubtypeError(ref a, ref b) => {
write!(f, "CodeSubtypeError({:?}, {:?})", a, b) write!(f, "CodeSubtypeError({a:?}, {b:?})")
} }
super::CodeConstEquateError(ref a, ref b) => { super::CodeConstEquateError(ref a, ref b) => {
write!(f, "CodeConstEquateError({:?}, {:?})", a, b) write!(f, "CodeConstEquateError({a:?}, {b:?})")
} }
super::CodeAmbiguity { overflow: false } => write!(f, "Ambiguity"), super::CodeAmbiguity { overflow: false } => write!(f, "Ambiguity"),
super::CodeAmbiguity { overflow: true } => write!(f, "Overflow"), super::CodeAmbiguity { overflow: true } => write!(f, "Overflow"),
super::CodeCycle(ref cycle) => write!(f, "Cycle({:?})", cycle), super::CodeCycle(ref cycle) => write!(f, "Cycle({cycle:?})"),
} }
} }
} }

View File

@ -908,7 +908,7 @@ pub fn list_file_metadata(
let flavor = get_flavor_from_path(path); let flavor = get_flavor_from_path(path);
match get_metadata_section(target, flavor, path, metadata_loader) { match get_metadata_section(target, flavor, path, metadata_loader) {
Ok(metadata) => metadata.list_crate_metadata(out), Ok(metadata) => metadata.list_crate_metadata(out),
Err(msg) => write!(out, "{}\n", msg), Err(msg) => write!(out, "{msg}\n"),
} }
} }

View File

@ -51,7 +51,7 @@ mod encoder;
mod table; mod table;
pub(crate) fn rustc_version(cfg_version: &'static str) -> String { pub(crate) fn rustc_version(cfg_version: &'static str) -> String {
format!("rustc {}", cfg_version) format!("rustc {cfg_version}")
} }
/// Metadata encoding version. /// Metadata encoding version.

View File

@ -1099,10 +1099,10 @@ fn debug_with_context_rec<V: Debug + Eq>(
let info_elem = map.places[child].proj_elem.unwrap(); let info_elem = map.places[child].proj_elem.unwrap();
let child_place_str = match info_elem { let child_place_str = match info_elem {
TrackElem::Discriminant => { TrackElem::Discriminant => {
format!("discriminant({})", place_str) format!("discriminant({place_str})")
} }
TrackElem::Variant(idx) => { TrackElem::Variant(idx) => {
format!("({} as {:?})", place_str, idx) format!("({place_str} as {idx:?})")
} }
TrackElem::Field(field) => { TrackElem::Field(field) => {
if place_str.starts_with('*') { if place_str.starts_with('*') {

View File

@ -1001,7 +1001,7 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> {
allow_shadowing: bool, allow_shadowing: bool,
) { ) {
if self.r.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing { if self.r.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
let msg = format!("`{}` is already in scope", name); let msg = format!("`{name}` is already in scope");
let note = let note =
"macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)"; "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
self.r.tcx.sess.struct_span_err(span, msg).note(note).emit(); self.r.tcx.sess.struct_span_err(span, msg).note(note).emit();

View File

@ -362,7 +362,7 @@ impl Resolver<'_, '_> {
let mut span_snippets = spans let mut span_snippets = spans
.iter() .iter()
.filter_map(|s| match tcx.sess.source_map().span_to_snippet(*s) { .filter_map(|s| match tcx.sess.source_map().span_to_snippet(*s) {
Ok(s) => Some(format!("`{}`", s)), Ok(s) => Some(format!("`{s}`")),
_ => None, _ => None,
}) })
.collect::<Vec<String>>(); .collect::<Vec<String>>();

View File

@ -243,7 +243,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
(TypeNS, _) => "type", (TypeNS, _) => "type",
}; };
let msg = format!("the name `{}` is defined multiple times", name); let msg = format!("the name `{name}` is defined multiple times");
let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) { let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
(true, true) => struct_span_err!(self.tcx.sess, span, E0259, "{}", msg), (true, true) => struct_span_err!(self.tcx.sess, span, E0259, "{}", msg),
@ -265,11 +265,11 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
container container
)); ));
err.span_label(span, format!("`{}` re{} here", name, new_participle)); err.span_label(span, format!("`{name}` re{new_participle} here"));
if !old_binding.span.is_dummy() && old_binding.span != span { if !old_binding.span.is_dummy() && old_binding.span != span {
err.span_label( err.span_label(
self.tcx.sess.source_map().guess_head_span(old_binding.span), self.tcx.sess.source_map().guess_head_span(old_binding.span),
format!("previous {} of the {} `{}` here", old_noun, old_kind, name), format!("previous {old_noun} of the {old_kind} `{name}` here"),
); );
} }
@ -358,15 +358,15 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
binding_span: Span, binding_span: Span,
) { ) {
let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() { let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
format!("Other{}", name) format!("Other{name}")
} else { } else {
format!("other_{}", name) format!("other_{name}")
}; };
let mut suggestion = None; let mut suggestion = None;
match import.kind { match import.kind {
ImportKind::Single { type_ns_only: true, .. } => { ImportKind::Single { type_ns_only: true, .. } => {
suggestion = Some(format!("self as {}", suggested_name)) suggestion = Some(format!("self as {suggested_name}"))
} }
ImportKind::Single { source, .. } => { ImportKind::Single { source, .. } => {
if let Some(pos) = if let Some(pos) =
@ -602,11 +602,11 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
let sugg_msg = "try using a local generic parameter instead"; let sugg_msg = "try using a local generic parameter instead";
let name = self.tcx.item_name(def_id); let name = self.tcx.item_name(def_id);
let (span, snippet) = if span.is_empty() { let (span, snippet) = if span.is_empty() {
let snippet = format!("<{}>", name); let snippet = format!("<{name}>");
(span, snippet) (span, snippet)
} else { } else {
let span = sm.span_through_char(span, '<').shrink_to_hi(); let span = sm.span_through_char(span, '<').shrink_to_hi();
let snippet = format!("{}, ", name); let snippet = format!("{name}, ");
(span, snippet) (span, snippet)
}; };
// Suggest the modification to the user // Suggest the modification to the user
@ -667,7 +667,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
name, name,
); );
for sp in target_sp { for sp in target_sp {
err.span_label(sp, format!("pattern doesn't bind `{}`", name)); err.span_label(sp, format!("pattern doesn't bind `{name}`"));
} }
for sp in origin_sp { for sp in origin_sp {
err.span_label(sp, "variable not in all patterns"); err.span_label(sp, "variable not in all patterns");
@ -694,8 +694,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
if import_suggestions.is_empty() { if import_suggestions.is_empty() {
let help_msg = format!( let help_msg = format!(
"if you meant to match on a variant or a `const` item, consider \ "if you meant to match on a variant or a `const` item, consider \
making the path in the pattern qualified: `path::to::ModOrType::{}`", making the path in the pattern qualified: `path::to::ModOrType::{name}`",
name,
); );
err.span_help(span, help_msg); err.span_help(span, help_msg);
} }
@ -953,8 +952,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
let mut err = self.tcx.sess.struct_span_err_with_code( let mut err = self.tcx.sess.struct_span_err_with_code(
span, span,
format!( format!(
"item `{}` is an associated {}, which doesn't match its trait `{}`", "item `{name}` is an associated {kind}, which doesn't match its trait `{trait_path}`",
name, kind, trait_path,
), ),
code, code,
); );
@ -1427,10 +1425,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
"a function-like macro".to_string() "a function-like macro".to_string()
} }
Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => { Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
format!("an attribute: `#[{}]`", ident) format!("an attribute: `#[{ident}]`")
} }
Res::Def(DefKind::Macro(MacroKind::Derive), _) => { Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
format!("a derive macro: `#[derive({})]`", ident) format!("a derive macro: `#[derive({ident})]`")
} }
Res::ToolMod => { Res::ToolMod => {
// Don't confuse the user with tool modules. // Don't confuse the user with tool modules.
@ -1451,7 +1449,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
if !import.span.is_dummy() { if !import.span.is_dummy() {
err.span_note( err.span_note(
import.span, import.span,
format!("`{}` is imported here, but it is {}", ident, desc), format!("`{ident}` is imported here, but it is {desc}"),
); );
// Silence the 'unused import' warning we might get, // Silence the 'unused import' warning we might get,
// since this diagnostic already covers that import. // since this diagnostic already covers that import.
@ -1459,7 +1457,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
return; return;
} }
} }
err.note(format!("`{}` is in scope, but it is {}", ident, desc)); err.note(format!("`{ident}` is in scope, but it is {desc}"));
return; return;
} }
} }
@ -1597,7 +1595,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
.enumerate() .enumerate()
.map(|(i, help_msg)| { .map(|(i, help_msg)| {
let or = if i == 0 { "" } else { "or " }; let or = if i == 0 { "" } else { "or " };
format!("{}{}", or, help_msg) format!("{or}{help_msg}")
}) })
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
) )
@ -1655,7 +1653,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
let descr = get_descr(binding); let descr = get_descr(binding);
let mut err = let mut err =
struct_span_err!(self.tcx.sess, ident.span, E0603, "{} `{}` is private", descr, ident); struct_span_err!(self.tcx.sess, ident.span, E0603, "{} `{}` is private", descr, ident);
err.span_label(ident.span, format!("private {}", descr)); err.span_label(ident.span, format!("private {descr}"));
if let Some((this_res, outer_ident)) = outermost_res { if let Some((this_res, outer_ident)) = outermost_res {
let import_suggestions = self.lookup_import_candidates( let import_suggestions = self.lookup_import_candidates(
@ -1840,7 +1838,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
_ => format!("`{parent}`"), _ => format!("`{parent}`"),
}; };
let mut msg = format!("could not find `{}` in {}", ident, parent); let mut msg = format!("could not find `{ident}` in {parent}");
if ns == TypeNS || ns == ValueNS { if ns == TypeNS || ns == ValueNS {
let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS }; let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
let binding = if let Some(module) = module { let binding = if let Some(module) = module {
@ -1955,12 +1953,12 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
let suggestion = match_span.map(|span| { let suggestion = match_span.map(|span| {
( (
vec![(span, String::from(""))], vec![(span, String::from(""))],
format!("`{}` is defined here, but is not a type", ident), format!("`{ident}` is defined here, but is not a type"),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
) )
}); });
(format!("use of undeclared type `{}`", ident), suggestion) (format!("use of undeclared type `{ident}`"), suggestion)
} else { } else {
let mut suggestion = None; let mut suggestion = None;
if ident.name == sym::alloc { if ident.name == sym::alloc {
@ -1982,7 +1980,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
}, },
) )
}); });
(format!("use of undeclared crate or module `{}`", ident), suggestion) (format!("use of undeclared crate or module `{ident}`"), suggestion)
} }
} }
@ -2166,16 +2164,16 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
let module_name = crate_module.kind.name().unwrap(); let module_name = crate_module.kind.name().unwrap();
let import_snippet = match import.kind { let import_snippet = match import.kind {
ImportKind::Single { source, target, .. } if source != target => { ImportKind::Single { source, target, .. } if source != target => {
format!("{} as {}", source, target) format!("{source} as {target}")
} }
_ => format!("{}", ident), _ => format!("{ident}"),
}; };
let mut corrections: Vec<(Span, String)> = Vec::new(); let mut corrections: Vec<(Span, String)> = Vec::new();
if !import.is_nested() { if !import.is_nested() {
// Assume this is the easy case of `use issue_59764::foo::makro;` and just remove // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
// intermediate segments. // intermediate segments.
corrections.push((import.span, format!("{}::{}", module_name, import_snippet))); corrections.push((import.span, format!("{module_name}::{import_snippet}")));
} else { } else {
// Find the binding span (and any trailing commas and spaces). // Find the binding span (and any trailing commas and spaces).
// ie. `use a::b::{c, d, e};` // ie. `use a::b::{c, d, e};`
@ -2242,11 +2240,11 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
start_point, start_point,
if has_nested { if has_nested {
// In this case, `start_snippet` must equal '{'. // In this case, `start_snippet` must equal '{'.
format!("{}{}, ", start_snippet, import_snippet) format!("{start_snippet}{import_snippet}, ")
} else { } else {
// In this case, add a `{`, then the moved import, then whatever // In this case, add a `{`, then the moved import, then whatever
// was there before. // was there before.
format!("{{{}, {}", import_snippet, start_snippet) format!("{{{import_snippet}, {start_snippet}")
}, },
)); ));
@ -2663,9 +2661,9 @@ fn show_candidates(
"item" "item"
}; };
let plural_descr = let plural_descr =
if descr.ends_with('s') { format!("{}es", descr) } else { format!("{}s", descr) }; if descr.ends_with('s') { format!("{descr}es") } else { format!("{descr}s") };
let mut msg = format!("{}these {} exist but are inaccessible", prefix, plural_descr); let mut msg = format!("{prefix}these {plural_descr} exist but are inaccessible");
let mut has_colon = false; let mut has_colon = false;
let mut spans = Vec::new(); let mut spans = Vec::new();
@ -2686,7 +2684,7 @@ fn show_candidates(
let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect()); let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
for (name, span) in spans { for (name, span) in spans {
multi_span.push_span_label(span, format!("`{}`: not accessible", name)); multi_span.push_span_label(span, format!("`{name}`: not accessible"));
} }
for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) { for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {

View File

@ -1445,12 +1445,12 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
let name_str = if name == kw::PathRoot { let name_str = if name == kw::PathRoot {
"crate root".to_string() "crate root".to_string()
} else { } else {
format!("`{}`", name) format!("`{name}`")
}; };
let label = if segment_idx == 1 && path[0].ident.name == kw::PathRoot { let label = if segment_idx == 1 && path[0].ident.name == kw::PathRoot {
format!("global paths cannot start with {}", name_str) format!("global paths cannot start with {name_str}")
} else { } else {
format!("{} in paths can only be used in start position", name_str) format!("{name_str} in paths can only be used in start position")
}; };
(label, None) (label, None)
}); });

View File

@ -1153,18 +1153,18 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
ModuleOrUniformRoot::Module(module) => { ModuleOrUniformRoot::Module(module) => {
let module_str = module_to_string(module); let module_str = module_to_string(module);
if let Some(module_str) = module_str { if let Some(module_str) = module_str {
format!("no `{}` in `{}`", ident, module_str) format!("no `{ident}` in `{module_str}`")
} else { } else {
format!("no `{}` in the root", ident) format!("no `{ident}` in the root")
} }
} }
_ => { _ => {
if !ident.is_path_segment_keyword() { if !ident.is_path_segment_keyword() {
format!("no external crate `{}`", ident) format!("no external crate `{ident}`")
} else { } else {
// HACK(eddyb) this shows up for `self` & `super`, which // HACK(eddyb) this shows up for `self` & `super`, which
// should work instead - for now keep the same error message. // should work instead - for now keep the same error message.
format!("no `{}` in the root", ident) format!("no `{ident}` in the root")
} }
} }
}; };
@ -1212,10 +1212,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
let (ns, binding) = reexport_error.unwrap(); let (ns, binding) = reexport_error.unwrap();
if pub_use_of_private_extern_crate_hack(import, binding) { if pub_use_of_private_extern_crate_hack(import, binding) {
let msg = format!( let msg = format!(
"extern crate `{}` is private, and cannot be \ "extern crate `{ident}` is private, and cannot be \
re-exported (error E0365), consider declaring with \ re-exported (error E0365), consider declaring with \
`pub`", `pub`"
ident
); );
self.lint_buffer.buffer_lint( self.lint_buffer.buffer_lint(
PUB_USE_OF_PRIVATE_EXTERN_CRATE, PUB_USE_OF_PRIVATE_EXTERN_CRATE,
@ -1355,7 +1354,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
UNUSED_IMPORTS, UNUSED_IMPORTS,
id, id,
import.span, import.span,
format!("the item `{}` is imported redundantly", ident), format!("the item `{ident}` is imported redundantly"),
BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident), BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
); );
} }

View File

@ -1917,10 +1917,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
candidate: LifetimeElisionCandidate, candidate: LifetimeElisionCandidate,
) { ) {
if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) { if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
panic!( panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
"lifetime {:?} resolved multiple times ({:?} before, {:?} now)",
id, prev_res, res
)
} }
match res { match res {
LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static => { LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static => {
@ -1936,8 +1933,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) { fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) { if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
panic!( panic!(
"lifetime parameter {:?} resolved multiple times ({:?} before, {:?} now)", "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
id, prev_res, res
) )
} }
} }

View File

@ -585,13 +585,13 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
let others = match enum_candidates.len() { let others = match enum_candidates.len() {
1 => String::new(), 1 => String::new(),
2 => " and 1 other".to_owned(), 2 => " and 1 other".to_owned(),
n => format!(" and {} others", n), n => format!(" and {n} others"),
}; };
format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others) format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
} else { } else {
String::new() String::new()
}; };
let msg = format!("{}try using the variant's enum", preamble); let msg = format!("{preamble}try using the variant's enum");
err.span_suggestions( err.span_suggestions(
span, span,
@ -696,7 +696,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
ident.name == path[0].ident.name { ident.name == path[0].ident.name {
err.span_help( err.span_help(
ident.span, ident.span,
format!("the binding `{}` is available in a different scope in the same function", path_str), format!("the binding `{path_str}` is available in a different scope in the same function"),
); );
return (true, candidates); return (true, candidates);
} }
@ -858,7 +858,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
for label_rib in &self.label_ribs { for label_rib in &self.label_ribs {
for (label_ident, node_id) in &label_rib.bindings { for (label_ident, node_id) in &label_rib.bindings {
let ident = path.last().unwrap().ident; let ident = path.last().unwrap().ident;
if format!("'{}", ident) == label_ident.to_string() { if format!("'{ident}") == label_ident.to_string() {
err.span_label(label_ident.span, "a label with a similar name exists"); err.span_label(label_ident.span, "a label with a similar name exists");
if let PathSource::Expr(Some(Expr { if let PathSource::Expr(Some(Expr {
kind: ExprKind::Break(None, Some(_)), kind: ExprKind::Break(None, Some(_)),
@ -983,7 +983,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
if let Some(ident) = fn_kind.ident() { if let Some(ident) = fn_kind.ident() {
err.span_label( err.span_label(
ident.span, ident.span,
format!("this function {} have a `self` parameter", doesnt), format!("this function {doesnt} have a `self` parameter"),
); );
} }
} }
@ -1164,7 +1164,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
}; };
err.span_suggestion_verbose( err.span_suggestion_verbose(
*where_span, *where_span,
format!("constrain the associated type to `{}`", ident), format!("constrain the associated type to `{ident}`"),
where_bound_predicate_to_string(&new_where_bound_predicate), where_bound_predicate_to_string(&new_where_bound_predicate),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
@ -1338,8 +1338,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
span, // Note the parentheses surrounding the suggestion below span, // Note the parentheses surrounding the suggestion below
format!( format!(
"you might want to surround a struct literal with parentheses: \ "you might want to surround a struct literal with parentheses: \
`({} {{ /* fields */ }})`?", `({path_str} {{ /* fields */ }})`?"
path_str
), ),
); );
} }
@ -1373,7 +1372,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
.map(|(idx, new)| (new, old_fields.get(idx))) .map(|(idx, new)| (new, old_fields.get(idx)))
.map(|(new, old)| { .map(|(new, old)| {
let new = new.to_ident_string(); let new = new.to_ident_string();
if let Some(Some(old)) = old && new != *old { format!("{}: {}", new, old) } else { new } if let Some(Some(old)) = old && new != *old { format!("{new}: {old}") } else { new }
}) })
.collect::<Vec<String>>() .collect::<Vec<String>>()
} else { } else {
@ -1390,7 +1389,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
}; };
err.span_suggestion( err.span_suggestion(
span, span,
format!("use struct {} syntax instead", descr), format!("use struct {descr} syntax instead"),
format!("{path_str} {{{pad}{fields}{pad}}}"), format!("{path_str} {{{pad}{fields}{pad}}}"),
applicability, applicability,
); );
@ -1584,7 +1583,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
err.span_suggestion( err.span_suggestion(
span, span,
"use the tuple variant pattern syntax instead", "use the tuple variant pattern syntax instead",
format!("{}({})", path_str, fields), format!("{path_str}({fields})"),
Applicability::HasPlaceholders, Applicability::HasPlaceholders,
); );
} }
@ -1994,9 +1993,9 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
if !suggestable_variants.is_empty() { if !suggestable_variants.is_empty() {
let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 { let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
format!("try {} the enum's variant", source_msg) format!("try {source_msg} the enum's variant")
} else { } else {
format!("try {} one of the enum's variants", source_msg) format!("try {source_msg} one of the enum's variants")
}; };
err.span_suggestions( err.span_suggestions(
@ -2009,19 +2008,15 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
// If the enum has no tuple variants.. // If the enum has no tuple variants..
if non_suggestable_variant_count == variants.len() { if non_suggestable_variant_count == variants.len() {
err.help(format!("the enum has no tuple variants {}", source_msg)); err.help(format!("the enum has no tuple variants {source_msg}"));
} }
// If there are also non-tuple variants.. // If there are also non-tuple variants..
if non_suggestable_variant_count == 1 { if non_suggestable_variant_count == 1 {
err.help(format!( err.help(format!("you might have meant {source_msg} the enum's non-tuple variant"));
"you might have meant {} the enum's non-tuple variant",
source_msg
));
} else if non_suggestable_variant_count >= 1 { } else if non_suggestable_variant_count >= 1 {
err.help(format!( err.help(format!(
"you might have meant {} one of the enum's non-tuple variants", "you might have meant {source_msg} one of the enum's non-tuple variants"
source_msg
)); ));
} }
} else { } else {
@ -2041,7 +2036,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
.map(|(variant, _, kind)| (path_names_to_string(variant), kind)) .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
.map(|(variant, kind)| match kind { .map(|(variant, kind)| match kind {
CtorKind::Const => variant, CtorKind::Const => variant,
CtorKind::Fn => format!("({}())", variant), CtorKind::Fn => format!("({variant}())"),
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let no_suggestable_variant = suggestable_variants.is_empty(); let no_suggestable_variant = suggestable_variants.is_empty();
@ -2066,7 +2061,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
.filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind)) .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
.map(|(variant, _, kind)| (path_names_to_string(variant), kind)) .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
.filter_map(|(variant, kind)| match kind { .filter_map(|(variant, kind)| match kind {
CtorKind::Fn => Some(format!("({}(/* fields */))", variant)), CtorKind::Fn => Some(format!("({variant}(/* fields */))")),
_ => None, _ => None,
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -2361,8 +2356,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
err.span_label( err.span_label(
span, span,
format!( format!(
"lifetime `{}` is missing in item created through this procedural macro", "lifetime `{name}` is missing in item created through this procedural macro",
name,
), ),
); );
continue; continue;
@ -2406,7 +2400,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
); );
} else if let Some(name) = name { } else if let Some(name) = name {
let message = let message =
Cow::from(format!("consider introducing lifetime `{}` here", name)); Cow::from(format!("consider introducing lifetime `{name}` here"));
should_continue = suggest(err, false, span, message, sugg); should_continue = suggest(err, false, span, message, sugg);
} else { } else {
let message = Cow::from("consider introducing a named lifetime parameter"); let message = Cow::from("consider introducing a named lifetime parameter");
@ -2550,7 +2544,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
} }
let help_name = if let Some(ident) = ident { let help_name = if let Some(ident) = ident {
format!("`{}`", ident) format!("`{ident}`")
} else { } else {
format!("argument {}", index + 1) format!("argument {}", index + 1)
}; };
@ -2558,7 +2552,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
if lifetime_count == 1 { if lifetime_count == 1 {
m.push_str(&help_name[..]) m.push_str(&help_name[..])
} else { } else {
m.push_str(&format!("one of {}'s {} lifetimes", help_name, lifetime_count)[..]) m.push_str(&format!("one of {help_name}'s {lifetime_count} lifetimes")[..])
} }
} }
@ -2588,14 +2582,12 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
} else if num_params == 1 { } else if num_params == 1 {
err.help(format!( err.help(format!(
"this function's return type contains a borrowed value, \ "this function's return type contains a borrowed value, \
but the signature does not say which {} it is borrowed from", but the signature does not say which {m} it is borrowed from"
m
)); ));
} else { } else {
err.help(format!( err.help(format!(
"this function's return type contains a borrowed value, \ "this function's return type contains a borrowed value, \
but the signature does not say whether it is borrowed from {}", but the signature does not say whether it is borrowed from {m}"
m
)); ));
} }
} }
@ -2614,7 +2606,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
} }
MissingLifetimeKind::Ampersand => { MissingLifetimeKind::Ampersand => {
debug_assert_eq!(lt.count, 1); debug_assert_eq!(lt.count, 1);
(lt.span.shrink_to_hi(), format!("{} ", existing_name)) (lt.span.shrink_to_hi(), format!("{existing_name} "))
} }
MissingLifetimeKind::Comma => { MissingLifetimeKind::Comma => {
let sugg: String = std::iter::repeat([existing_name.as_str(), ", "]) let sugg: String = std::iter::repeat([existing_name.as_str(), ", "])
@ -2661,7 +2653,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
} }
1 => { 1 => {
err.multipart_suggestion_verbose( err.multipart_suggestion_verbose(
format!("consider using the `{}` lifetime", existing_name), format!("consider using the `{existing_name}` lifetime"),
spans_suggs, spans_suggs,
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
@ -2778,9 +2770,9 @@ pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident
let shadower = shadower.span; let shadower = shadower.span;
let mut err = sess.struct_span_warn( let mut err = sess.struct_span_warn(
shadower, shadower,
format!("label name `{}` shadows a label name that is already in scope", name), format!("label name `{name}` shadows a label name that is already in scope"),
); );
err.span_label(orig, "first declared here"); err.span_label(orig, "first declared here");
err.span_label(shadower, format!("label `{}` already in scope", name)); err.span_label(shadower, format!("label `{name}` already in scope"));
err.emit(); err.emit();
} }

View File

@ -1168,7 +1168,7 @@ impl<'tcx> Resolver<'_, 'tcx> {
} }
fn local_def_id(&self, node: NodeId) -> LocalDefId { fn local_def_id(&self, node: NodeId) -> LocalDefId {
self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node)) self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
} }
/// Adds a definition with a parent definition. /// Adds a definition with a parent definition.
@ -1834,7 +1834,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) { fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
debug!("(recording res) recording {:?} for {}", resolution, node_id); debug!("(recording res) recording {:?} for {}", resolution, node_id);
if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) { if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution); panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
} }
} }

View File

@ -207,7 +207,7 @@ impl<'a, 'tcx> ResolverExpand for Resolver<'a, 'tcx> {
self.tcx self.tcx
.sess .sess
.diagnostic() .diagnostic()
.bug(format!("built-in macro `{}` was already registered", name)); .bug(format!("built-in macro `{name}` was already registered"));
} }
} }
@ -570,7 +570,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
} }
let mut err = self.tcx.sess.create_err(err); let mut err = self.tcx.sess.create_err(err);
err.span_label(path.span, format!("not {} {}", article, expected)); err.span_label(path.span, format!("not {article} {expected}"));
err.emit(); err.emit();
@ -906,7 +906,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) { if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
self.tcx.sess.span_err( self.tcx.sess.span_err(
ident.span, ident.span,
format!("name `{}` is reserved in attribute namespace", ident), format!("name `{ident}` is reserved in attribute namespace"),
); );
} }
} }

View File

@ -512,7 +512,7 @@ impl<'tcx> Stable<'tcx> for mir::InlineAsmOperand<'tcx> {
| InlineAsmOperand::SymStatic { .. } => (None, None), | InlineAsmOperand::SymStatic { .. } => (None, None),
}; };
stable_mir::mir::InlineAsmOperand { in_value, out_place, raw_rpr: format!("{:?}", self) } stable_mir::mir::InlineAsmOperand { in_value, out_place, raw_rpr: format!("{self:?}") }
} }
} }
@ -561,10 +561,10 @@ impl<'tcx> Stable<'tcx> for mir::Terminator<'tcx> {
}, },
InlineAsm { template, operands, options, line_spans, destination, unwind } => { InlineAsm { template, operands, options, line_spans, destination, unwind } => {
Terminator::InlineAsm { Terminator::InlineAsm {
template: format!("{:?}", template), template: format!("{template:?}"),
operands: operands.iter().map(|operand| operand.stable(tables)).collect(), operands: operands.iter().map(|operand| operand.stable(tables)).collect(),
options: format!("{:?}", options), options: format!("{options:?}"),
line_spans: format!("{:?}", line_spans), line_spans: format!("{line_spans:?}"),
destination: destination.map(|d| d.as_usize()), destination: destination.map(|d| d.as_usize()),
unwind: unwind.stable(tables), unwind: unwind.stable(tables),
} }

View File

@ -161,7 +161,7 @@ impl<'tcx> AutoTraitFinder<'tcx> {
let (full_env, full_user_env) = self let (full_env, full_user_env) = self
.evaluate_predicates(&infcx, trait_did, ty, new_env, user_env, &mut fresh_preds) .evaluate_predicates(&infcx, trait_did, ty, new_env, user_env, &mut fresh_preds)
.unwrap_or_else(|| { .unwrap_or_else(|| {
panic!("Failed to fully process: {:?} {:?} {:?}", ty, trait_did, orig_env) panic!("Failed to fully process: {ty:?} {trait_did:?} {orig_env:?}")
}); });
debug!( debug!(
@ -178,7 +178,7 @@ impl<'tcx> AutoTraitFinder<'tcx> {
ocx.register_bound(ObligationCause::dummy(), full_env, ty, trait_did); ocx.register_bound(ObligationCause::dummy(), full_env, ty, trait_did);
let errors = ocx.select_all_or_error(); let errors = ocx.select_all_or_error();
if !errors.is_empty() { if !errors.is_empty() {
panic!("Unable to fulfill trait {:?} for '{:?}': {:?}", trait_did, ty, errors); panic!("Unable to fulfill trait {trait_did:?} for '{ty:?}': {errors:?}");
} }
let outlives_env = OutlivesEnvironment::new(full_env); let outlives_env = OutlivesEnvironment::new(full_env);
@ -339,7 +339,7 @@ impl<'tcx> AutoTraitFinder<'tcx> {
return None; return None;
} }
} }
_ => panic!("Unexpected error for '{:?}': {:?}", ty, result), _ => panic!("Unexpected error for '{ty:?}': {result:?}"),
}; };
let normalized_preds = let normalized_preds =
@ -747,7 +747,7 @@ impl<'tcx> AutoTraitFinder<'tcx> {
// subobligations or getting an error) when we started off with // subobligations or getting an error) when we started off with
// inference variables // inference variables
if p.term().skip_binder().has_infer_types() { if p.term().skip_binder().has_infer_types() {
panic!("Unexpected result when selecting {:?} {:?}", ty, obligation) panic!("Unexpected result when selecting {ty:?} {obligation:?}")
} }
} }
} }

View File

@ -357,7 +357,7 @@ fn impl_intersection_has_negative_obligation(
Err(err) => { Err(err) => {
tcx.sess.delay_span_bug( tcx.sess.delay_span_bug(
tcx.def_span(impl1_def_id), tcx.def_span(impl1_def_id),
format!("failed to fully normalize {:?}: {:?}", impl1_def_id, err), format!("failed to fully normalize {impl1_def_id:?}: {err:?}"),
); );
return false; return false;
} }

View File

@ -226,7 +226,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> {
let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| hir.span(id)); let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| hir.span(id));
(span, None, vec![ArgKind::empty(); variant_data.fields().len()]) (span, None, vec![ArgKind::empty(); variant_data.fields().len()])
} }
_ => panic!("non-FnLike node found: {:?}", node), _ => panic!("non-FnLike node found: {node:?}"),
}) })
} }
@ -273,10 +273,10 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> {
found_str, found_str,
); );
err.span_label(span, format!("expected {} that takes {}", kind, expected_str)); err.span_label(span, format!("expected {kind} that takes {expected_str}"));
if let Some(found_span) = found_span { if let Some(found_span) = found_span {
err.span_label(found_span, format!("takes {}", found_str)); err.span_label(found_span, format!("takes {found_str}"));
// Suggest to take and ignore the arguments with expected_args_length `_`s if // Suggest to take and ignore the arguments with expected_args_length `_`s if
// found arguments is empty (assume the user just wants to ignore args in this case). // found arguments is empty (assume the user just wants to ignore args in this case).
@ -289,7 +289,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> {
"consider changing the closure to take and ignore the expected argument{}", "consider changing the closure to take and ignore the expected argument{}",
pluralize!(expected_args.len()) pluralize!(expected_args.len())
), ),
format!("|{}|", underscores), format!("|{underscores}|"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} }
@ -304,7 +304,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> {
err.span_suggestion_verbose( err.span_suggestion_verbose(
found_span, found_span,
"change the closure to take multiple arguments instead of a single tuple", "change the closure to take multiple arguments instead of a single tuple",
format!("|{}|", sugg), format!("|{sugg}|"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} }
@ -703,9 +703,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
.get_parent_trait_ref(obligation.cause.code()) .get_parent_trait_ref(obligation.cause.code())
.map(|(t, s)| { .map(|(t, s)| {
( (
format!(" in `{}`", t), format!(" in `{t}`"),
format!("within `{}`, ", t), format!("within `{t}`, "),
s.map(|s| (format!("within this `{}`", t), s)), s.map(|s| (format!("within this `{t}`"), s)),
) )
}) })
.unwrap_or_default(); .unwrap_or_default();
@ -1070,7 +1070,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
// which bounds actually failed to hold. // which bounds actually failed to hold.
self.tcx.sess.struct_span_err( self.tcx.sess.struct_span_err(
span, span,
format!("the type `{}` is not well-formed", ty), format!("the type `{ty}` is not well-formed"),
) )
} }
} }
@ -1108,7 +1108,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => { ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
let mut diag = self.tcx.sess.struct_span_err( let mut diag = self.tcx.sess.struct_span_err(
span, span,
format!("the constant `{}` is not of type `{}`", ct, ty), format!("the constant `{ct}` is not of type `{ty}`"),
); );
self.note_type_err( self.note_type_err(
&mut diag, &mut diag,
@ -1980,7 +1980,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
if all_traits_equal { if all_traits_equal {
format!("\n {}", c.self_ty()) format!("\n {}", c.self_ty())
} else { } else {
format!("\n {}", c) format!("\n {c}")
} }
}) })
.collect(); .collect();
@ -2178,10 +2178,8 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
format!("trait impl{} with same name found", pluralize!(trait_impls.len())), format!("trait impl{} with same name found", pluralize!(trait_impls.len())),
); );
let trait_crate = self.tcx.crate_name(trait_with_same_path.krate); let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
let crate_msg = format!( let crate_msg =
"perhaps two different versions of crate `{}` are being used?", format!("perhaps two different versions of crate `{trait_crate}` are being used?");
trait_crate
);
err.note(crate_msg); err.note(crate_msg);
suggested = true; suggested = true;
} }
@ -2309,7 +2307,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
err.cancel(); err.cancel();
return; return;
} }
err.note(format!("cannot satisfy `{}`", predicate)); err.note(format!("cannot satisfy `{predicate}`"));
let impl_candidates = self let impl_candidates = self
.find_similar_impl_candidates(predicate.to_opt_poly_trait_pred().unwrap()); .find_similar_impl_candidates(predicate.to_opt_poly_trait_pred().unwrap());
if impl_candidates.len() < 10 { if impl_candidates.len() < 10 {
@ -2373,7 +2371,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
if let Some(local_def_id) = data.trait_ref.def_id.as_local() if let Some(local_def_id) = data.trait_ref.def_id.as_local()
&& let Some(hir::Node::Item(hir::Item { ident: trait_name, kind: hir::ItemKind::Trait(_, _, _, _, trait_item_refs), .. })) = self.tcx.hir().find_by_def_id(local_def_id) && let Some(hir::Node::Item(hir::Item { ident: trait_name, kind: hir::ItemKind::Trait(_, _, _, _, trait_item_refs), .. })) = self.tcx.hir().find_by_def_id(local_def_id)
&& let Some(method_ref) = trait_item_refs.iter().find(|item_ref| item_ref.ident == *assoc_item_name) { && let Some(method_ref) = trait_item_refs.iter().find(|item_ref| item_ref.ident == *assoc_item_name) {
err.span_label(method_ref.span, format!("`{}::{}` defined here", trait_name, assoc_item_name)); err.span_label(method_ref.span, format!("`{trait_name}::{assoc_item_name}` defined here"));
} }
err.span_label(span, format!("cannot {verb} associated {noun} of trait")); err.span_label(span, format!("cannot {verb} associated {noun} of trait"));
@ -2474,7 +2472,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
ErrorCode::E0284, ErrorCode::E0284,
true, true,
); );
err.note(format!("cannot satisfy `{}`", predicate)); err.note(format!("cannot satisfy `{predicate}`"));
err err
} else { } else {
// If we can't find a substitution, just print a generic error // If we can't find a substitution, just print a generic error
@ -2485,7 +2483,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
"type annotations needed: cannot satisfy `{}`", "type annotations needed: cannot satisfy `{}`",
predicate, predicate,
); );
err.span_label(span, format!("cannot satisfy `{}`", predicate)); err.span_label(span, format!("cannot satisfy `{predicate}`"));
err err
} }
} }
@ -2513,7 +2511,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
"type annotations needed: cannot satisfy `{}`", "type annotations needed: cannot satisfy `{}`",
predicate, predicate,
); );
err.span_label(span, format!("cannot satisfy `{}`", predicate)); err.span_label(span, format!("cannot satisfy `{predicate}`"));
err err
} }
} }
@ -2528,7 +2526,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
"type annotations needed: cannot satisfy `{}`", "type annotations needed: cannot satisfy `{}`",
predicate, predicate,
); );
err.span_label(span, format!("cannot satisfy `{}`", predicate)); err.span_label(span, format!("cannot satisfy `{predicate}`"));
err err
} }
}; };
@ -2565,7 +2563,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
} }
} }
} }
let mut crate_names: Vec<_> = crates.iter().map(|n| format!("`{}`", n)).collect(); let mut crate_names: Vec<_> = crates.iter().map(|n| format!("`{n}`")).collect();
crate_names.sort(); crate_names.sort();
crate_names.dedup(); crate_names.dedup();
post.sort(); post.sort();
@ -2592,7 +2590,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
predicate predicate
); );
let post = if post.len() > 1 || (post.len() == 1 && post[0].contains('\n')) { let post = if post.len() > 1 || (post.len() == 1 && post[0].contains('\n')) {
format!(":\n{}", post.iter().map(|p| format!("- {}", p)).collect::<Vec<_>>().join("\n"),) format!(":\n{}", post.iter().map(|p| format!("- {p}")).collect::<Vec<_>>().join("\n"),)
} else if post.len() == 1 { } else if post.len() == 1 {
format!(": `{}`", post[0]) format!(": `{}`", post[0])
} else { } else {
@ -2601,7 +2599,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
match (spans.len(), crates.len(), crate_names.len()) { match (spans.len(), crates.len(), crate_names.len()) {
(0, 0, 0) => { (0, 0, 0) => {
err.note(format!("cannot satisfy `{}`", predicate)); err.note(format!("cannot satisfy `{predicate}`"));
} }
(0, _, 1) => { (0, _, 1) => {
err.note(format!("{} in the `{}` crate{}", msg, crates[0], post,)); err.note(format!("{} in the `{}` crate{}", msg, crates[0], post,));
@ -2772,7 +2770,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
err.span_suggestion_verbose( err.span_suggestion_verbose(
span, span,
"consider relaxing the implicit `Sized` restriction", "consider relaxing the implicit `Sized` restriction",
format!("{} ?Sized", separator), format!("{separator} ?Sized"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} }
@ -2863,7 +2861,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
} }
}) })
.unwrap_or_else(|| { .unwrap_or_else(|| {
format!("the trait bound `{}` is not satisfied{}", trait_predicate, post_message) format!("the trait bound `{trait_predicate}` is not satisfied{post_message}")
}) })
} }
@ -3151,11 +3149,11 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
err.span_label( err.span_label(
closure_span, closure_span,
format!("this closure implements `{}`, not `{}`", found_kind, kind), format!("this closure implements `{found_kind}`, not `{kind}`"),
); );
err.span_label( err.span_label(
obligation.cause.span, obligation.cause.span,
format!("the requirement to implement `{}` derives from here", kind), format!("the requirement to implement `{kind}` derives from here"),
); );
// Additional context information explaining why the closure only implements // Additional context information explaining why the closure only implements
@ -3382,8 +3380,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
let const_span = self.tcx.def_span(uv.def); let const_span = self.tcx.def_span(uv.def);
match self.tcx.sess.source_map().span_to_snippet(const_span) { match self.tcx.sess.source_map().span_to_snippet(const_span) {
Ok(snippet) => err.help(format!( Ok(snippet) => err.help(format!(
"try adding a `where` bound using this expression: `where [(); {}]:`", "try adding a `where` bound using this expression: `where [(); {snippet}]:`"
snippet
)), )),
_ => err.help("consider adding a `where` bound using this expression"), _ => err.help("consider adding a `where` bound using this expression"),
}; };

View File

@ -170,7 +170,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
if let Some(k) = obligation.cause.span.desugaring_kind() { if let Some(k) = obligation.cause.span.desugaring_kind() {
flags.push((sym::from_desugaring, None)); flags.push((sym::from_desugaring, None));
flags.push((sym::from_desugaring, Some(format!("{:?}", k)))); flags.push((sym::from_desugaring, Some(format!("{k:?}"))));
} }
if let ObligationCauseCode::MainFunctionType = obligation.cause.code() { if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
@ -258,9 +258,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
if let ty::Array(aty, len) = self_ty.kind() { if let ty::Array(aty, len) = self_ty.kind() {
flags.push((sym::_Self, Some("[]".to_string()))); flags.push((sym::_Self, Some("[]".to_string())));
let len = len.try_to_value().and_then(|v| v.try_to_target_usize(self.tcx)); let len = len.try_to_value().and_then(|v| v.try_to_target_usize(self.tcx));
flags.push((sym::_Self, Some(format!("[{}; _]", aty)))); flags.push((sym::_Self, Some(format!("[{aty}; _]"))));
if let Some(n) = len { if let Some(n) = len {
flags.push((sym::_Self, Some(format!("[{}; {}]", aty, n)))); flags.push((sym::_Self, Some(format!("[{aty}; {n}]"))));
} }
if let Some(def) = aty.ty_adt_def() { if let Some(def) = aty.ty_adt_def() {
// We also want to be able to select the array's type's original // We also want to be able to select the array's type's original
@ -579,7 +579,7 @@ impl<'tcx> OnUnimplementedFormatString {
"there is no parameter `{}` on {}", "there is no parameter `{}` on {}",
s, s,
if trait_def_id == item_def_id { if trait_def_id == item_def_id {
format!("trait `{}`", trait_name) format!("trait `{trait_name}`")
} else { } else {
"impl".to_string() "impl".to_string()
} }

View File

@ -479,13 +479,13 @@ fn suggest_restriction<'tcx>(
.visit_ty(input); .visit_ty(input);
} }
// The type param `T: Trait` we will suggest to introduce. // The type param `T: Trait` we will suggest to introduce.
let type_param = format!("{}: {}", type_param_name, bound_str); let type_param = format!("{type_param_name}: {bound_str}");
let mut sugg = vec![ let mut sugg = vec![
if let Some(span) = hir_generics.span_for_param_suggestion() { if let Some(span) = hir_generics.span_for_param_suggestion() {
(span, format!(", {}", type_param)) (span, format!(", {type_param}"))
} else { } else {
(hir_generics.span, format!("<{}>", type_param)) (hir_generics.span, format!("<{type_param}>"))
}, },
// `fn foo(t: impl Trait)` // `fn foo(t: impl Trait)`
// ^ suggest `where <T as Trait>::A: Bound` // ^ suggest `where <T as Trait>::A: Bound`
@ -530,7 +530,7 @@ fn suggest_restriction<'tcx>(
err.span_suggestion_verbose( err.span_suggestion_verbose(
sp, sp,
format!("consider further restricting {}", msg), format!("consider further restricting {msg}"),
suggestion, suggestion,
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
@ -694,7 +694,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
term term
); );
} else { } else {
constraint.push_str(&format!("<{} = {}>", name, term)); constraint.push_str(&format!("<{name} = {term}>"));
} }
} }
@ -1016,7 +1016,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
let name = self.tcx.def_path_str(def_id); let name = self.tcx.def_path_str(def_id);
err.span_label( err.span_label(
self.tcx.def_span(def_id), self.tcx.def_span(def_id),
format!("consider calling the constructor for `{}`", name), format!("consider calling the constructor for `{name}`"),
); );
name name
} }
@ -1395,7 +1395,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
// Because of this, we modify the error to refer to the original obligation and // Because of this, we modify the error to refer to the original obligation and
// return early in the caller. // return early in the caller.
let msg = format!("the trait bound `{}` is not satisfied", old_pred); let msg = format!("the trait bound `{old_pred}` is not satisfied");
if has_custom_message { if has_custom_message {
err.note(msg); err.note(msg);
} else { } else {
@ -1435,7 +1435,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
err.multipart_suggestion_verbose( err.multipart_suggestion_verbose(
sugg_msg, sugg_msg,
vec![ vec![
(span.shrink_to_lo(), format!("({}", sugg_prefix)), (span.shrink_to_lo(), format!("({sugg_prefix}")),
(span.shrink_to_hi(), ")".to_string()), (span.shrink_to_hi(), ")".to_string()),
], ],
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
@ -1471,7 +1471,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
vec![(span.shrink_to_lo(), sugg_prefix)] vec![(span.shrink_to_lo(), sugg_prefix)]
} else { } else {
vec![ vec![
(span.shrink_to_lo(), format!("{}(", sugg_prefix)), (span.shrink_to_lo(), format!("{sugg_prefix}(")),
(span.shrink_to_hi(), ")".to_string()), (span.shrink_to_hi(), ")".to_string()),
] ]
}; };
@ -1702,8 +1702,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
hir.get_if_local(*def_id) hir.get_if_local(*def_id)
{ {
let msg = format!( let msg = format!(
"alternatively, consider making `fn {}` asynchronous", "alternatively, consider making `fn {ident}` asynchronous"
ident
); );
if vis_span.is_empty() { if vis_span.is_empty() {
err.span_suggestion_verbose( err.span_suggestion_verbose(
@ -1954,10 +1953,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
// don't print out the [type error] here // don't print out the [type error] here
err.delay_as_bug(); err.delay_as_bug();
} else { } else {
err.span_label( err.span_label(expr.span, format!("this returned value is of type `{ty}`"));
expr.span,
format!("this returned value is of type `{}`", ty),
);
} }
} }
} }
@ -2458,8 +2454,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
err.clear_code(); err.clear_code();
err.set_primary_message(format!( err.set_primary_message(format!(
"{} cannot be {} between threads safely", "{future_or_generator} cannot be {trait_verb} between threads safely"
future_or_generator, trait_verb
)); ));
let original_span = err.span.primary_span().unwrap(); let original_span = err.span.primary_span().unwrap();
@ -2468,7 +2463,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
let message = outer_generator let message = outer_generator
.and_then(|generator_did| { .and_then(|generator_did| {
Some(match self.tcx.generator_kind(generator_did).unwrap() { Some(match self.tcx.generator_kind(generator_did).unwrap() {
GeneratorKind::Gen => format!("generator is not {}", trait_name), GeneratorKind::Gen => format!("generator is not {trait_name}"),
GeneratorKind::Async(AsyncGeneratorKind::Fn) => self GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
.tcx .tcx
.parent(generator_did) .parent(generator_did)
@ -2476,73 +2471,73 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
.map(|parent_did| hir.local_def_id_to_hir_id(parent_did)) .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
.and_then(|parent_hir_id| hir.opt_name(parent_hir_id)) .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
.map(|name| { .map(|name| {
format!("future returned by `{}` is not {}", name, trait_name) format!("future returned by `{name}` is not {trait_name}")
})?, })?,
GeneratorKind::Async(AsyncGeneratorKind::Block) => { GeneratorKind::Async(AsyncGeneratorKind::Block) => {
format!("future created by async block is not {}", trait_name) format!("future created by async block is not {trait_name}")
} }
GeneratorKind::Async(AsyncGeneratorKind::Closure) => { GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
format!("future created by async closure is not {}", trait_name) format!("future created by async closure is not {trait_name}")
} }
}) })
}) })
.unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name)); .unwrap_or_else(|| format!("{future_or_generator} is not {trait_name}"));
span.push_span_label(original_span, message); span.push_span_label(original_span, message);
err.set_span(span); err.set_span(span);
format!("is not {}", trait_name) format!("is not {trait_name}")
} else { } else {
format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path()) format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
}; };
let mut explain_yield = let mut explain_yield = |interior_span: Span,
|interior_span: Span, yield_span: Span, scope_span: Option<Span>| { yield_span: Span,
let mut span = MultiSpan::from_span(yield_span); scope_span: Option<Span>| {
let snippet = match source_map.span_to_snippet(interior_span) { let mut span = MultiSpan::from_span(yield_span);
// #70935: If snippet contains newlines, display "the value" instead let snippet = match source_map.span_to_snippet(interior_span) {
// so that we do not emit complex diagnostics. // #70935: If snippet contains newlines, display "the value" instead
Ok(snippet) if !snippet.contains('\n') => format!("`{}`", snippet), // so that we do not emit complex diagnostics.
_ => "the value".to_string(), Ok(snippet) if !snippet.contains('\n') => format!("`{snippet}`"),
}; _ => "the value".to_string(),
// note: future is not `Send` as this value is used across an await };
// --> $DIR/issue-70935-complex-spans.rs:13:9 // note: future is not `Send` as this value is used across an await
// | // --> $DIR/issue-70935-complex-spans.rs:13:9
// LL | baz(|| async { // |
// | ______________- // LL | baz(|| async {
// | | // | ______________-
// | | // | |
// LL | | foo(tx.clone()); // | |
// LL | | }).await; // LL | | foo(tx.clone());
// | | - ^^^^^^ await occurs here, with value maybe used later // LL | | }).await;
// | |__________| // | | - ^^^^^^ await occurs here, with value maybe used later
// | has type `closure` which is not `Send` // | |__________|
// note: value is later dropped here // | has type `closure` which is not `Send`
// LL | | }).await; // note: value is later dropped here
// | | ^ // LL | | }).await;
// // | | ^
span.push_span_label( //
yield_span, span.push_span_label(
format!("{} occurs here, with {} maybe used later", await_or_yield, snippet), yield_span,
); format!("{await_or_yield} occurs here, with {snippet} maybe used later"),
span.push_span_label( );
interior_span, span.push_span_label(
format!("has type `{}` which {}", target_ty, trait_explanation), interior_span,
); format!("has type `{target_ty}` which {trait_explanation}"),
if let Some(scope_span) = scope_span { );
let scope_span = source_map.end_point(scope_span); if let Some(scope_span) = scope_span {
let scope_span = source_map.end_point(scope_span);
let msg = format!("{} is later dropped here", snippet); let msg = format!("{snippet} is later dropped here");
span.push_span_label(scope_span, msg); span.push_span_label(scope_span, msg);
} }
err.span_note( err.span_note(
span, span,
format!( format!(
"{} {} as this value is used across {}", "{future_or_generator} {trait_explanation} as this value is used across {an_await_or_yield}"
future_or_generator, trait_explanation, an_await_or_yield
), ),
); );
}; };
match interior_or_upvar_span { match interior_or_upvar_span {
GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => { GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info { if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
@ -2552,15 +2547,13 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
span.push_span_label( span.push_span_label(
await_span, await_span,
format!( format!(
"await occurs here on type `{}`, which {}", "await occurs here on type `{target_ty}`, which {trait_explanation}"
target_ty, trait_explanation
), ),
); );
err.span_note( err.span_note(
span, span,
format!( format!(
"future {not_trait} as it awaits another future which {not_trait}", "future {trait_explanation} as it awaits another future which {trait_explanation}"
not_trait = trait_explanation
), ),
); );
} else { } else {
@ -2643,18 +2636,16 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
let ref_kind = if is_mut { "&mut" } else { "&" }; let ref_kind = if is_mut { "&mut" } else { "&" };
( (
format!( format!(
"has type `{}` which {}, because `{}` is not `{}`", "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`"
target_ty, trait_explanation, ref_ty, ref_ty_trait
), ),
format!( format!(
"captured value {} because `{}` references cannot be sent unless their referent is `{}`", "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`"
trait_explanation, ref_kind, ref_ty_trait
), ),
) )
} }
None => ( None => (
format!("has type `{}` which {}", target_ty, trait_explanation), format!("has type `{target_ty}` which {trait_explanation}"),
format!("captured value {}", trait_explanation), format!("captured value {trait_explanation}"),
), ),
}; };
@ -2743,8 +2734,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
} }
ObligationCauseCode::ObjectTypeBound(object_ty, region) => { ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
err.note(format!( err.note(format!(
"required so that the lifetime bound of `{}` for `{}` is satisfied", "required so that the lifetime bound of `{region}` for `{object_ty}` is satisfied",
region, object_ty,
)); ));
} }
ObligationCauseCode::ItemObligation(_) ObligationCauseCode::ItemObligation(_)
@ -3064,7 +3054,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
let mut msg = let mut msg =
"required because it captures the following types: ".to_owned(); "required because it captures the following types: ".to_owned();
for ty in bound_tys.skip_binder() { for ty in bound_tys.skip_binder() {
with_forced_trimmed_paths!(write!(msg, "`{}`, ", ty).unwrap()); with_forced_trimmed_paths!(write!(msg, "`{ty}`, ").unwrap());
} }
err.note(msg.trim_end_matches(", ").to_string()) err.note(msg.trim_end_matches(", ").to_string())
} }
@ -3078,7 +3068,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
"required because it captures the following types: ".to_owned(); "required because it captures the following types: ".to_owned();
for bty in tcx.generator_hidden_types(*def_id) { for bty in tcx.generator_hidden_types(*def_id) {
let ty = bty.instantiate(tcx, args); let ty = bty.instantiate(tcx, args);
write!(msg, "`{}`, ", ty).unwrap(); write!(msg, "`{ty}`, ").unwrap();
} }
err.note(msg.trim_end_matches(", ").to_string()) err.note(msg.trim_end_matches(", ").to_string())
} }
@ -3513,7 +3503,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
trait_pred.skip_binder().self_ty(), trait_pred.skip_binder().self_ty(),
diagnostic_name, diagnostic_name,
), ),
format!("#[derive({})]\n", diagnostic_name), format!("#[derive({diagnostic_name})]\n"),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} }
@ -3999,7 +3989,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
.map(|trait_ref| trait_ref.trait_ref.self_ty()) .map(|trait_ref| trait_ref.trait_ref.self_ty())
.find(|t| is_slice(*t)) .find(|t| is_slice(*t))
{ {
let msg = format!("convert the array to a `{}` slice instead", slice_ty); let msg = format!("convert the array to a `{slice_ty}` slice instead");
if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
let mut suggestions = vec![]; let mut suggestions = vec![];

View File

@ -517,8 +517,7 @@ fn virtual_call_violation_for_method<'tcx>(
tcx.sess.delay_span_bug( tcx.sess.delay_span_bug(
tcx.def_span(method.def_id), tcx.def_span(method.def_id),
format!( format!(
"receiver when `Self = ()` should have a Scalar ABI; found {:?}", "receiver when `Self = ()` should have a Scalar ABI; found {abi:?}"
abi
), ),
); );
} }
@ -536,8 +535,7 @@ fn virtual_call_violation_for_method<'tcx>(
tcx.sess.delay_span_bug( tcx.sess.delay_span_bug(
tcx.def_span(method.def_id), tcx.def_span(method.def_id),
format!( format!(
"receiver when `Self = {}` should have a ScalarPair ABI; found {:?}", "receiver when `Self = {trait_object_ty}` should have a ScalarPair ABI; found {abi:?}"
trait_object_ty, abi
), ),
); );
} }

View File

@ -483,8 +483,7 @@ impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
assert!( assert!(
!value.has_escaping_bound_vars(), !value.has_escaping_bound_vars(),
"Normalizing {:?} without wrapping in a `Binder`", "Normalizing {value:?} without wrapping in a `Binder`"
value
); );
if !needs_normalization(&value, self.param_env.reveal()) { if !needs_normalization(&value, self.param_env.reveal()) {
@ -1932,7 +1931,7 @@ fn assemble_candidates_from_impls<'cx, 'tcx>(
// These traits have no associated types. // These traits have no associated types.
selcx.tcx().sess.delay_span_bug( selcx.tcx().sess.delay_span_bug(
obligation.cause.span, obligation.cause.span,
format!("Cannot project an associated type from `{:?}`", impl_source), format!("Cannot project an associated type from `{impl_source:?}`"),
); );
return Err(()); return Err(());
} }
@ -2303,8 +2302,7 @@ fn confirm_param_env_candidate<'cx, 'tcx>(
} }
Err(e) => { Err(e) => {
let msg = format!( let msg = format!(
"Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}", "Failed to unify obligation `{obligation:?}` with poly_projection `{poly_cache_entry:?}`: {e:?}",
obligation, poly_cache_entry, e,
); );
debug!("confirm_param_env_candidate: {}", msg); debug!("confirm_param_env_candidate: {}", msg);
let err = Ty::new_error_with_message(infcx.tcx, obligation.cause.span, msg); let err = Ty::new_error_with_message(infcx.tcx, obligation.cause.span, msg);

View File

@ -299,7 +299,7 @@ impl<'cx, 'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for QueryNormalizer<'cx, 'tcx>
if !tcx.sess.opts.actually_rustdoc { if !tcx.sess.opts.actually_rustdoc {
tcx.sess.delay_span_bug( tcx.sess.delay_span_bug(
DUMMY_SP, DUMMY_SP,
format!("unexpected ambiguity: {:?} {:?}", c_data, result), format!("unexpected ambiguity: {c_data:?} {result:?}"),
); );
} }
return Err(NoSolution); return Err(NoSolution);

View File

@ -77,8 +77,7 @@ where
let pre_obligations = infcx.take_registered_region_obligations(); let pre_obligations = infcx.take_registered_region_obligations();
assert!( assert!(
pre_obligations.is_empty(), pre_obligations.is_empty(),
"scrape_region_constraints: incoming region obligations = {:#?}", "scrape_region_constraints: incoming region obligations = {pre_obligations:#?}",
pre_obligations,
); );
let value = infcx.commit_if_ok(|_| { let value = infcx.commit_if_ok(|_| {
@ -92,7 +91,7 @@ where
} else { } else {
Err(infcx.tcx.sess.delay_span_bug( Err(infcx.tcx.sess.delay_span_bug(
DUMMY_SP, DUMMY_SP,
format!("errors selecting obligation during MIR typeck: {:?}", errors), format!("errors selecting obligation during MIR typeck: {errors:?}"),
)) ))
} }
})?; })?;

View File

@ -74,22 +74,21 @@ impl IntercrateAmbiguityCause {
match self { match self {
IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } => { IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } => {
let self_desc = if let Some(ty) = self_desc { let self_desc = if let Some(ty) = self_desc {
format!(" for type `{}`", ty) format!(" for type `{ty}`")
} else { } else {
String::new() String::new()
}; };
format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc) format!("downstream crates may implement trait `{trait_desc}`{self_desc}")
} }
IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc } => { IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc } => {
let self_desc = if let Some(ty) = self_desc { let self_desc = if let Some(ty) = self_desc {
format!(" for type `{}`", ty) format!(" for type `{ty}`")
} else { } else {
String::new() String::new()
}; };
format!( format!(
"upstream crates may add a new impl of trait `{}`{} \ "upstream crates may add a new impl of trait `{trait_desc}`{self_desc} \
in future versions", in future versions"
trait_desc, self_desc
) )
} }
IntercrateAmbiguityCause::ReservationImpl { message } => message.clone(), IntercrateAmbiguityCause::ReservationImpl { message } => message.clone(),
@ -2410,8 +2409,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> {
let guar = self.infcx.tcx.sess.delay_span_bug( let guar = self.infcx.tcx.sess.delay_span_bug(
obligation.cause.span, obligation.cause.span,
format!( format!(
"Impl {:?} was matchable against {:?} but now is not", "Impl {impl_def_id:?} was matchable against {obligation:?} but now is not"
impl_def_id, obligation
), ),
); );
let value = self.infcx.fresh_args_for_item(obligation.cause.span, impl_def_id); let value = self.infcx.fresh_args_for_item(obligation.cause.span, impl_def_id);

View File

@ -388,16 +388,16 @@ fn report_conflicting_impls<'tcx>(
impl_span, impl_span,
format!( format!(
"conflicting implementation{}", "conflicting implementation{}",
overlap.self_ty.map_or_else(String::new, |ty| format!(" for `{}`", ty)) overlap.self_ty.map_or_else(String::new, |ty| format!(" for `{ty}`"))
), ),
); );
} }
Err(cname) => { Err(cname) => {
let msg = match to_pretty_impl_header(tcx, overlap.with_impl) { let msg = match to_pretty_impl_header(tcx, overlap.with_impl) {
Some(s) => { Some(s) => {
format!("conflicting implementation in crate `{}`:\n- {}", cname, s) format!("conflicting implementation in crate `{cname}`:\n- {s}")
} }
None => format!("conflicting implementation in crate `{}`", cname), None => format!("conflicting implementation in crate `{cname}`"),
}; };
err.note(msg); err.note(msg);
} }
@ -514,8 +514,7 @@ pub(crate) fn to_pretty_impl_header(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Opti
pretty_predicates.push(p.to_string()); pretty_predicates.push(p.to_string());
} }
pretty_predicates pretty_predicates.extend(types_without_default_bounds.iter().map(|ty| format!("{ty}: ?Sized")));
.extend(types_without_default_bounds.iter().map(|ty| format!("{}: ?Sized", ty)));
if !pretty_predicates.is_empty() { if !pretty_predicates.is_empty() {
write!(w, "\n where {}", pretty_predicates.join(", ")).unwrap(); write!(w, "\n where {}", pretty_predicates.join(", ")).unwrap();

View File

@ -50,7 +50,7 @@ impl<'tcx> TraitAliasExpansionInfo<'tcx> {
diag.span_label(self.top().1, top_label); diag.span_label(self.top().1, top_label);
if self.path.len() > 1 { if self.path.len() > 1 {
for (_, sp) in self.path.iter().rev().skip(1).take(self.path.len() - 2) { for (_, sp) in self.path.iter().rev().skip(1).take(self.path.len() - 2) {
diag.span_label(*sp, format!("referenced here ({})", use_desc)); diag.span_label(*sp, format!("referenced here ({use_desc})"));
} }
} }
if self.top().1 != self.bottom().1 { if self.top().1 != self.bottom().1 {
@ -58,7 +58,7 @@ impl<'tcx> TraitAliasExpansionInfo<'tcx> {
// redundant labels. // redundant labels.
diag.span_label( diag.span_label(
self.bottom().1, self.bottom().1,
format!("trait alias used in trait object type ({})", use_desc), format!("trait alias used in trait object type ({use_desc})"),
); );
} }
} }

View File

@ -195,11 +195,7 @@ fn dump_vtable_entries<'tcx>(
trait_ref: ty::PolyTraitRef<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>,
entries: &[VtblEntry<'tcx>], entries: &[VtblEntry<'tcx>],
) { ) {
tcx.sess.emit_err(DumpVTableEntries { tcx.sess.emit_err(DumpVTableEntries { span: sp, trait_ref, entries: format!("{entries:#?}") });
span: sp,
trait_ref,
entries: format!("{:#?}", entries),
});
} }
fn has_own_existential_vtable_entries(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool { fn has_own_existential_vtable_entries(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {