From 543fecad31ce0ce11d93cc3255819b16b5acec4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Mon, 24 Jul 2023 16:10:35 +0200 Subject: [PATCH] inline format!() args See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Opening.20.60E-easy.60.20meta.20issue.28s.29.20for.20small.20tweaks.3F --- compiler/rustc/build.rs | 2 +- compiler/rustc_abi/src/layout.rs | 8 +- compiler/rustc_abi/src/lib.rs | 17 +- compiler/rustc_apfloat/src/ieee.rs | 4 +- .../rustc_ast_passes/src/ast_validation.rs | 9 +- .../rustc_borrowck/src/borrowck_errors.rs | 46 +++--- compiler/rustc_borrowck/src/dataflow.rs | 2 +- .../src/diagnostics/conflict_errors.rs | 76 ++++----- compiler/rustc_borrowck/src/facts.rs | 2 +- compiler/rustc_borrowck/src/lib.rs | 6 +- compiler/rustc_borrowck/src/nll.rs | 6 +- .../src/region_infer/dump_mir.rs | 11 +- .../src/region_infer/graphviz.rs | 4 +- .../rustc_borrowck/src/region_infer/mod.rs | 2 +- .../src/region_infer/opaque_types.rs | 2 +- .../rustc_borrowck/src/region_infer/values.rs | 6 +- compiler/rustc_builtin_macros/src/asm.rs | 20 ++- .../src/deriving/clone.rs | 8 +- .../src/deriving/decodable.rs | 2 +- .../src/deriving/encodable.rs | 2 +- .../src/deriving/generic/mod.rs | 9 +- compiler/rustc_builtin_macros/src/format.rs | 8 +- .../src/format_foreign.rs | 21 ++- .../src/global_allocator.rs | 2 +- .../src/proc_macro_harness.rs | 3 +- .../rustc_builtin_macros/src/source_util.rs | 2 +- compiler/rustc_codegen_llvm/src/asm.rs | 8 +- compiler/rustc_codegen_llvm/src/attributes.rs | 2 +- .../rustc_codegen_llvm/src/back/archive.rs | 10 +- compiler/rustc_codegen_llvm/src/back/lto.rs | 6 +- compiler/rustc_codegen_llvm/src/back/write.rs | 6 +- compiler/rustc_codegen_llvm/src/builder.rs | 11 +- compiler/rustc_codegen_llvm/src/common.rs | 4 +- compiler/rustc_codegen_llvm/src/consts.rs | 3 +- .../rustc_codegen_llvm/src/debuginfo/gdb.rs | 2 +- .../src/debuginfo/metadata.rs | 16 +- .../rustc_codegen_llvm/src/debuginfo/utils.rs | 3 +- compiler/rustc_codegen_llvm/src/intrinsic.rs | 18 +-- compiler/rustc_codegen_llvm/src/lib.rs | 6 +- compiler/rustc_codegen_llvm/src/llvm_util.rs | 8 +- compiler/rustc_codegen_ssa/src/back/link.rs | 29 ++-- compiler/rustc_codegen_ssa/src/back/linker.rs | 34 ++-- .../rustc_codegen_ssa/src/back/metadata.rs | 7 +- compiler/rustc_codegen_ssa/src/back/rpath.rs | 2 +- compiler/rustc_codegen_ssa/src/back/write.rs | 4 +- .../src/debuginfo/type_names.rs | 18 +-- compiler/rustc_codegen_ssa/src/errors.rs | 20 +-- compiler/rustc_codegen_ssa/src/mir/block.rs | 16 +- .../rustc_codegen_ssa/src/mir/debuginfo.rs | 2 +- compiler/rustc_codegen_ssa/src/mir/rvalue.rs | 3 +- compiler/rustc_codegen_ssa/src/mono_item.rs | 4 +- .../rustc_codegen_ssa/src/target_features.rs | 6 +- .../src/const_eval/eval_queries.rs | 2 +- .../src/const_eval/valtrees.rs | 2 +- .../src/interpret/eval_context.rs | 10 +- .../src/interpret/intrinsics.rs | 17 +- .../rustc_const_eval/src/interpret/memory.rs | 4 +- .../src/interpret/operator.rs | 5 +- .../rustc_const_eval/src/interpret/step.rs | 2 +- .../src/interpret/validity.rs | 10 +- .../src/transform/check_consts/ops.rs | 8 +- .../src/transform/validate.rs | 61 ++++--- compiler/rustc_error_messages/src/lib.rs | 10 +- compiler/rustc_errors/src/diagnostic.rs | 10 +- compiler/rustc_errors/src/diagnostic_impls.rs | 2 +- compiler/rustc_errors/src/emitter.rs | 14 +- compiler/rustc_errors/src/json.rs | 8 +- compiler/rustc_errors/src/lib.rs | 8 +- compiler/rustc_expand/src/config.rs | 6 +- compiler/rustc_expand/src/expand.rs | 4 +- compiler/rustc_expand/src/mbe/diagnostics.rs | 2 +- compiler/rustc_expand/src/mbe/macro_check.rs | 4 +- compiler/rustc_expand/src/mbe/macro_parser.rs | 8 +- compiler/rustc_expand/src/mbe/macro_rules.rs | 13 +- compiler/rustc_expand/src/mbe/quoted.rs | 2 +- compiler/rustc_expand/src/proc_macro.rs | 4 +- .../rustc_expand/src/proc_macro_server.rs | 2 +- .../rustc_hir_analysis/src/astconv/errors.rs | 6 +- .../src/astconv/generics.rs | 8 +- .../rustc_hir_analysis/src/astconv/lint.rs | 4 +- .../rustc_hir_analysis/src/astconv/mod.rs | 10 +- .../rustc_hir_analysis/src/check/check.rs | 6 +- .../src/check/compare_impl_item.rs | 2 +- .../rustc_hir_analysis/src/check/intrinsic.rs | 4 +- .../src/check/intrinsicck.rs | 2 +- compiler/rustc_hir_analysis/src/check/mod.rs | 2 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 8 +- .../rustc_hir_analysis/src/check_unused.rs | 2 +- .../src/coherence/builtin.rs | 3 +- .../src/coherence/inherent_impls.rs | 3 +- .../src/coherence/inherent_impls_overlap.rs | 8 +- .../src/coherence/orphan.rs | 15 +- compiler/rustc_hir_analysis/src/collect.rs | 16 +- .../src/collect/resolve_bound_vars.rs | 3 +- .../rustc_hir_analysis/src/collect/type_of.rs | 8 +- compiler/rustc_hir_analysis/src/errors.rs | 2 +- .../rustc_hir_analysis/src/impl_wf_check.rs | 5 +- .../src/impl_wf_check/min_specialization.rs | 4 +- .../wrong_number_of_generic_args.rs | 12 +- .../rustc_hir_analysis/src/variance/terms.rs | 4 +- compiler/rustc_hir_typeck/src/callee.rs | 2 +- compiler/rustc_hir_typeck/src/cast.rs | 6 +- compiler/rustc_hir_typeck/src/coercion.rs | 3 +- compiler/rustc_hir_typeck/src/expr.rs | 14 +- .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 8 +- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 42 +++-- .../src/fn_ctxt/suggestions.rs | 10 +- .../src/generator_interior/drop_ranges/mod.rs | 4 +- .../src/generator_interior/mod.rs | 2 +- compiler/rustc_hir_typeck/src/intrinsicck.rs | 2 +- .../rustc_hir_typeck/src/method/confirm.rs | 5 +- .../src/method/prelude2021.rs | 20 +-- .../rustc_hir_typeck/src/method/suggest.rs | 68 ++++---- compiler/rustc_hir_typeck/src/pat.rs | 27 ++-- compiler/rustc_hir_typeck/src/upvar.rs | 15 +- compiler/rustc_hir_typeck/src/writeback.rs | 10 +- .../rustc_incremental/src/assert_dep_graph.rs | 10 +- .../src/persist/dirty_clean.rs | 2 +- compiler/rustc_incremental/src/persist/fs.rs | 8 +- compiler/rustc_infer/src/errors/mod.rs | 16 +- .../src/errors/note_and_explain.rs | 2 +- .../src/infer/canonical/canonicalizer.rs | 2 +- compiler/rustc_infer/src/infer/combine.rs | 2 +- .../src/infer/error_reporting/mod.rs | 55 +++---- .../infer/error_reporting/need_type_info.rs | 2 +- .../nice_region_error/static_impl_trait.rs | 19 +-- .../src/infer/error_reporting/note.rs | 7 +- .../infer/error_reporting/note_and_explain.rs | 9 +- .../src/infer/error_reporting/suggest.rs | 4 +- .../src/infer/lexical_region_resolve/mod.rs | 5 +- .../rustc_infer/src/infer/nll_relate/mod.rs | 2 +- .../src/infer/outlives/obligations.rs | 2 +- .../rustc_infer/src/infer/outlives/verify.rs | 2 +- .../src/infer/region_constraints/mod.rs | 8 +- .../src/traits/error_reporting/mod.rs | 6 +- compiler/rustc_infer/src/traits/project.rs | 8 +- .../src/traits/structural_impls.rs | 10 +- compiler/rustc_lint/src/builtin.rs | 2 +- compiler/rustc_lint/src/context.rs | 34 ++-- compiler/rustc_lint/src/levels.rs | 2 +- compiler/rustc_lint/src/lints.rs | 6 +- compiler/rustc_lint/src/unused.rs | 10 +- compiler/rustc_log/src/lib.rs | 2 +- compiler/rustc_macros/src/serialize.rs | 2 +- compiler/rustc_metadata/src/locator.rs | 2 +- compiler/rustc_metadata/src/rmeta/mod.rs | 2 +- .../rustc_middle/src/dep_graph/dep_node.rs | 2 +- compiler/rustc_middle/src/dep_graph/mod.rs | 2 +- compiler/rustc_middle/src/hir/map/mod.rs | 2 +- compiler/rustc_middle/src/lint.rs | 14 +- compiler/rustc_middle/src/middle/stability.rs | 14 +- .../rustc_middle/src/mir/generic_graph.rs | 4 +- .../rustc_middle/src/mir/generic_graphviz.rs | 10 +- compiler/rustc_middle/src/mir/graphviz.rs | 2 +- .../src/mir/interpret/allocation/init_mask.rs | 6 +- .../rustc_middle/src/mir/interpret/error.rs | 2 +- .../rustc_middle/src/mir/interpret/mod.rs | 2 +- .../rustc_middle/src/mir/interpret/value.rs | 12 +- compiler/rustc_middle/src/mir/mod.rs | 128 +++++++-------- compiler/rustc_middle/src/mir/mono.rs | 8 +- compiler/rustc_middle/src/mir/pretty.rs | 89 +++++----- compiler/rustc_middle/src/mir/query.rs | 2 +- compiler/rustc_middle/src/mir/spanview.rs | 17 +- compiler/rustc_middle/src/mir/terminator.rs | 26 +-- compiler/rustc_middle/src/query/mod.rs | 2 +- compiler/rustc_middle/src/thir.rs | 22 +-- compiler/rustc_middle/src/traits/mod.rs | 39 +++-- .../src/traits/solve/inspect/format.rs | 4 +- .../src/traits/specialization_graph.rs | 2 +- .../src/traits/structural_impls.rs | 10 +- compiler/rustc_middle/src/ty/closure.rs | 2 +- compiler/rustc_middle/src/ty/consts.rs | 4 +- compiler/rustc_middle/src/ty/consts/int.rs | 2 +- compiler/rustc_middle/src/ty/consts/kind.rs | 2 +- compiler/rustc_middle/src/ty/diagnostics.rs | 18 +-- compiler/rustc_middle/src/ty/error.rs | 8 +- compiler/rustc_middle/src/ty/instance.rs | 16 +- compiler/rustc_middle/src/ty/layout.rs | 4 +- compiler/rustc_middle/src/ty/mod.rs | 4 +- .../src/ty/normalize_erasing_regions.rs | 4 +- compiler/rustc_middle/src/ty/opaque_types.rs | 16 +- compiler/rustc_middle/src/ty/print/pretty.rs | 10 +- .../rustc_middle/src/ty/structural_impls.rs | 12 +- compiler/rustc_middle/src/ty/util.rs | 2 +- compiler/rustc_middle/src/ty/vtable.rs | 4 +- compiler/rustc_middle/src/util/bug.rs | 2 +- compiler/rustc_middle/src/util/common.rs | 2 +- .../rustc_mir_build/src/build/custom/parse.rs | 2 +- .../src/build/expr/as_rvalue.rs | 3 +- .../rustc_mir_build/src/build/matches/mod.rs | 4 +- .../rustc_mir_build/src/build/matches/test.rs | 6 +- compiler/rustc_mir_build/src/build/mod.rs | 15 +- compiler/rustc_mir_build/src/errors.rs | 8 +- compiler/rustc_mir_build/src/thir/cx/expr.rs | 4 +- .../src/thir/pattern/check_match.rs | 25 ++- .../src/thir/pattern/deconstruct_pat.rs | 18 +-- .../src/thir/pattern/usefulness.rs | 4 +- .../rustc_mir_dataflow/src/value_analysis.rs | 4 +- .../src/coverage/counters.rs | 8 +- .../rustc_mir_transform/src/coverage/debug.rs | 4 +- .../rustc_mir_transform/src/coverage/graph.rs | 15 +- .../src/coverage/test_macros/src/lib.rs | 2 +- .../src/elaborate_drops.rs | 5 +- .../src/function_item_references.rs | 6 +- compiler/rustc_mir_transform/src/generator.rs | 2 +- .../rustc_mir_transform/src/instsimplify.rs | 2 +- compiler/rustc_mir_transform/src/lib.rs | 2 +- .../rustc_mir_transform/src/match_branches.rs | 2 +- .../src/multiple_return_terminators.rs | 2 +- compiler/rustc_mir_transform/src/nrvo.rs | 2 +- .../rustc_mir_transform/src/pass_manager.rs | 4 +- .../src/remove_unneeded_drops.rs | 2 +- .../rustc_mir_transform/src/remove_zsts.rs | 2 +- compiler/rustc_parse/src/lexer/diagnostics.rs | 2 +- compiler/rustc_parse/src/lexer/tokentrees.rs | 2 +- .../src/lexer/unescape_error_reporting.rs | 15 +- .../rustc_parse/src/lexer/unicode_chars.rs | 2 +- compiler/rustc_parse/src/lib.rs | 2 +- .../rustc_parse/src/parser/attr_wrapper.rs | 17 +- .../rustc_parse/src/parser/diagnostics.rs | 4 +- compiler/rustc_parse/src/parser/expr.rs | 4 +- compiler/rustc_parse/src/parser/mod.rs | 6 +- compiler/rustc_parse/src/parser/pat.rs | 6 +- compiler/rustc_parse/src/parser/path.rs | 2 +- compiler/rustc_parse/src/parser/stmt.rs | 9 +- compiler/rustc_parse/src/validate_attr.rs | 8 +- compiler/rustc_passes/src/check_const.rs | 6 +- compiler/rustc_passes/src/hir_id_validator.rs | 5 +- compiler/rustc_passes/src/hir_stats.rs | 8 +- compiler/rustc_passes/src/liveness.rs | 2 +- .../rustc_query_system/src/dep_graph/graph.rs | 4 +- .../rustc_resolve/src/build_reduced_graph.rs | 2 +- compiler/rustc_resolve/src/check_unused.rs | 2 +- compiler/rustc_resolve/src/diagnostics.rs | 60 ++++--- compiler/rustc_resolve/src/ident.rs | 6 +- compiler/rustc_resolve/src/imports.rs | 15 +- compiler/rustc_resolve/src/late.rs | 8 +- .../rustc_resolve/src/late/diagnostics.rs | 62 ++++--- compiler/rustc_resolve/src/lib.rs | 4 +- compiler/rustc_resolve/src/macros.rs | 6 +- compiler/rustc_session/src/config.rs | 8 +- compiler/rustc_session/src/options.rs | 3 +- compiler/rustc_smir/src/rustc_smir/mod.rs | 8 +- .../src/traits/auto_trait.rs | 8 +- .../src/traits/coherence.rs | 2 +- .../src/traits/error_reporting/mod.rs | 57 ++++--- .../error_reporting/on_unimplemented.rs | 8 +- .../src/traits/error_reporting/suggestions.rs | 152 ++++++++---------- .../src/traits/object_safety.rs | 6 +- .../src/traits/project.rs | 8 +- .../src/traits/query/normalize.rs | 2 +- .../src/traits/query/type_op/custom.rs | 5 +- .../src/traits/select/mod.rs | 14 +- .../src/traits/specialize/mod.rs | 9 +- .../rustc_trait_selection/src/traits/util.rs | 4 +- .../src/traits/vtable.rs | 6 +- compiler/rustc_ty_utils/src/needs_drop.rs | 2 +- compiler/rustc_type_ir/src/lib.rs | 2 +- library/core/src/net/ip_addr.rs | 8 +- library/core/src/num/mod.rs | 3 +- library/core/src/panic/panic_info.rs | 4 +- library/core/src/str/lossy.rs | 2 +- library/core/src/str/mod.rs | 9 +- library/core/src/time.rs | 10 +- library/proc_macro/src/bridge/symbol.rs | 4 +- library/proc_macro/src/lib.rs | 6 +- library/std/src/backtrace.rs | 6 +- library/std/src/env.rs | 2 +- library/std/src/io/error/repr_bitpacked.rs | 5 +- .../src/sys/unix/process/process_common.rs | 2 +- .../std/src/sys/unix/process/process_unix.rs | 3 +- library/std/src/sys_common/wtf8.rs | 2 +- library/test/src/formatters/junit.rs | 2 +- 273 files changed, 1218 insertions(+), 1473 deletions(-) diff --git a/compiler/rustc/build.rs b/compiler/rustc/build.rs index 39cf3e094c823..8b7d28d2b8aa6 100644 --- a/compiler/rustc/build.rs +++ b/compiler/rustc/build.rs @@ -18,7 +18,7 @@ fn set_windows_exe_options() { let mut manifest = env::current_dir().unwrap(); manifest.push(WINDOWS_MANIFEST_FILE); - println!("cargo:rerun-if-changed={}", WINDOWS_MANIFEST_FILE); + println!("cargo:rerun-if-changed={WINDOWS_MANIFEST_FILE}"); // Embed the Windows application manifest file. println!("cargo:rustc-link-arg-bin=rustc-main=/MANIFEST:EMBED"); println!("cargo:rustc-link-arg-bin=rustc-main=/MANIFESTINPUT:{}", manifest.to_str().unwrap()); diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index aea88641f82b1..d249ad78d7ac7 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -260,8 +260,7 @@ pub trait LayoutCalculator { } _ => assert!( start == Bound::Unbounded && end == Bound::Unbounded, - "nonscalar layout for layout_scalar_valid_range type: {:#?}", - st, + "nonscalar layout for layout_scalar_valid_range type: {st:#?}", ), } @@ -463,7 +462,7 @@ pub trait LayoutCalculator { min = 0; max = 0; } - assert!(min <= max, "discriminant range is {}...{}", min, max); + assert!(min <= max, "discriminant range is {min}...{max}"); let (min_ity, signed) = discr_range_of_repr(min, max); //Integer::repr_discr(tcx, ty, &repr, min, max); let mut align = dl.aggregate_align; @@ -537,8 +536,7 @@ pub trait LayoutCalculator { // space necessary to represent would have to be discarded (or layout is wrong // on thinking it needs 16 bits) panic!( - "layout decided on a larger discriminant type ({:?}) than typeck ({:?})", - min_ity, typeck_ity + "layout decided on a larger discriminant type ({min_ity:?}) than typeck ({typeck_ity:?})" ); // However, it is fine to make discr type however large (as an optimisation) // after this point – we’ll just truncate the value we load in codegen. diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index ef0c763ac2038..24404c2758660 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -332,7 +332,7 @@ impl TargetDataLayout { 16 => 1 << 15, 32 => 1 << 31, 64 => 1 << 47, - bits => panic!("obj_size_bound: unknown pointer bit size {}", bits), + bits => panic!("obj_size_bound: unknown pointer bit size {bits}"), } } @@ -342,7 +342,7 @@ impl TargetDataLayout { 16 => I16, 32 => I32, 64 => I64, - bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits), + bits => panic!("ptr_sized_integer: unknown pointer bit size {bits}"), } } @@ -399,7 +399,7 @@ impl FromStr for Endian { match s { "little" => Ok(Self::Little), "big" => Ok(Self::Big), - _ => Err(format!(r#"unknown endian: "{}""#, s)), + _ => Err(format!(r#"unknown endian: "{s}""#)), } } } @@ -456,7 +456,7 @@ impl Size { pub fn bits(self) -> u64 { #[cold] fn overflow(bytes: u64) -> ! { - panic!("Size::bits: {} bytes in bits doesn't fit in u64", bytes) + panic!("Size::bits: {bytes} bytes in bits doesn't fit in u64") } self.bytes().checked_mul(8).unwrap_or_else(|| overflow(self.bytes())) @@ -1179,12 +1179,7 @@ impl FieldsShape { unreachable!("FieldsShape::offset: `Primitive`s have no fields") } FieldsShape::Union(count) => { - assert!( - i < count.get(), - "tried to access field {} of union with {} fields", - i, - count - ); + assert!(i < count.get(), "tried to access field {i} of union with {count} fields"); Size::ZERO } FieldsShape::Array { stride, count } => { @@ -1294,7 +1289,7 @@ impl Abi { Primitive::Int(_, signed) => signed, _ => false, }, - _ => panic!("`is_signed` on non-scalar ABI {:?}", self), + _ => panic!("`is_signed` on non-scalar ABI {self:?}"), } } diff --git a/compiler/rustc_apfloat/src/ieee.rs b/compiler/rustc_apfloat/src/ieee.rs index 2286712f02565..b1b55260d51a6 100644 --- a/compiler/rustc_apfloat/src/ieee.rs +++ b/compiler/rustc_apfloat/src/ieee.rs @@ -570,9 +570,9 @@ impl fmt::Display for IeeeFloat { // Exponent always at least two digits if we do not truncate zeros. if truncate_zero { - write!(f, "{:+}", exp)?; + write!(f, "{exp:+}")?; } else { - write!(f, "{:+03}", exp)?; + write!(f, "{exp:+03}")?; } return Ok(()); diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 418e1df5857a4..af594a00705f5 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -659,7 +659,7 @@ fn validate_generic_param_order( GenericParamKind::Type { .. } => (ParamKindOrd::TypeOrConst, ident.to_string()), GenericParamKind::Const { ty, .. } => { let ty = pprust::ty_to_string(ty); - (ParamKindOrd::TypeOrConst, format!("const {}: {}", ident, ty)) + (ParamKindOrd::TypeOrConst, format!("const {ident}: {ty}")) } }; param_idents.push((kind, ord_kind, bounds, idx, ident)); @@ -1463,15 +1463,12 @@ fn deny_equality_constraints( let Some(arg) = args.args.last() else { continue; }; - ( - format!(", {} = {}", assoc, ty), - arg.span().shrink_to_hi(), - ) + (format!(", {assoc} = {ty}"), arg.span().shrink_to_hi()) } _ => continue, }, None => ( - format!("<{} = {}>", assoc, ty), + format!("<{assoc} = {ty}>"), trait_segment.span().shrink_to_hi(), ), }; diff --git a/compiler/rustc_borrowck/src/borrowck_errors.rs b/compiler/rustc_borrowck/src/borrowck_errors.rs index a4e0e773a81ae..a2c7e767b4cc2 100644 --- a/compiler/rustc_borrowck/src/borrowck_errors.rs +++ b/compiler/rustc_borrowck/src/borrowck_errors.rs @@ -37,8 +37,8 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { desc, ); - err.span_label(borrow_span, format!("{} is borrowed here", borrow_desc)); - err.span_label(span, format!("use of borrowed {}", borrow_desc)); + err.span_label(borrow_span, format!("{borrow_desc} is borrowed here")); + err.span_label(span, format!("use of borrowed {borrow_desc}")); err } @@ -51,8 +51,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { old_opt_via: &str, old_load_end_span: Option, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - let via = - |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {})", msg) }; + let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") }; let mut err = struct_span_err!( self, new_loan_span, @@ -143,9 +142,9 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { ); err.span_label( new_loan_span, - format!("{} construction occurs here{}", container_name, opt_via), + format!("{container_name} construction occurs here{opt_via}"), ); - err.span_label(old_loan_span, format!("borrow occurs here{}", old_opt_via)); + err.span_label(old_loan_span, format!("borrow occurs here{old_opt_via}")); if let Some(previous_end_span) = previous_end_span { err.span_label(previous_end_span, "borrow ends here"); } @@ -173,13 +172,10 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { opt_via, kind_new, ); - err.span_label( - new_loan_span, - format!("{}borrow occurs here{}", second_borrow_desc, opt_via), - ); + err.span_label(new_loan_span, format!("{second_borrow_desc}borrow occurs here{opt_via}")); err.span_label( old_loan_span, - format!("{} construction occurs here{}", container_name, old_opt_via), + format!("{container_name} construction occurs here{old_opt_via}"), ); if let Some(previous_end_span) = previous_end_span { err.span_label(previous_end_span, "borrow from closure ends here"); @@ -199,8 +195,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { msg_old: &str, old_load_end_span: Option, ) -> DiagnosticBuilder<'cx, ErrorGuaranteed> { - let via = - |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {})", msg) }; + let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") }; let mut err = struct_span_err!( self, span, @@ -216,22 +211,21 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { if msg_new == "" { // If `msg_new` is empty, then this isn't a borrow of a union field. - err.span_label(span, format!("{} borrow occurs here", kind_new)); - err.span_label(old_span, format!("{} borrow occurs here", kind_old)); + err.span_label(span, format!("{kind_new} borrow occurs here")); + err.span_label(old_span, format!("{kind_old} borrow occurs here")); } else { // If `msg_new` isn't empty, then this a borrow of a union field. err.span_label( span, format!( - "{} borrow of {} -- which overlaps with {} -- occurs here", - kind_new, msg_new, msg_old, + "{kind_new} borrow of {msg_new} -- which overlaps with {msg_old} -- occurs here", ), ); err.span_label(old_span, format!("{} borrow occurs here{}", kind_old, via(msg_old))); } if let Some(old_load_end_span) = old_load_end_span { - err.span_label(old_load_end_span, format!("{} borrow ends here", kind_old)); + err.span_label(old_load_end_span, format!("{kind_old} borrow ends here")); } err } @@ -250,8 +244,8 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { desc, ); - err.span_label(borrow_span, format!("{} is borrowed here", desc)); - err.span_label(span, format!("{} is assigned to here but it was already borrowed", desc)); + err.span_label(borrow_span, format!("{desc} is borrowed here")); + err.span_label(span, format!("{desc} is assigned to here but it was already borrowed")); err } @@ -330,7 +324,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { optional_adverb_for_moved: &str, moved_path: Option, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - let moved_path = moved_path.map(|mp| format!(": `{}`", mp)).unwrap_or_default(); + let moved_path = moved_path.map(|mp| format!(": `{mp}`")).unwrap_or_default(); struct_span_err!( self, @@ -369,8 +363,8 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { immutable_place, immutable_section, ); - err.span_label(mutate_span, format!("cannot {}", action)); - err.span_label(immutable_span, format!("value is immutable in {}", immutable_section)); + err.span_label(mutate_span, format!("cannot {action}")); + err.span_label(immutable_span, format!("value is immutable in {immutable_section}")); err } @@ -428,7 +422,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { err.span_label( span, - format!("{}s a {} data owned by the current function", return_kind, reference_desc), + format!("{return_kind}s a {reference_desc} data owned by the current function"), ); err @@ -449,8 +443,8 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { "{closure_kind} may outlive the current {scope}, but it borrows {borrowed_path}, \ which is owned by the current {scope}", ); - err.span_label(capture_span, format!("{} is borrowed here", borrowed_path)) - .span_label(closure_span, format!("may outlive borrowed value {}", borrowed_path)); + err.span_label(capture_span, format!("{borrowed_path} is borrowed here")) + .span_label(closure_span, format!("may outlive borrowed value {borrowed_path}")); err } diff --git a/compiler/rustc_borrowck/src/dataflow.rs b/compiler/rustc_borrowck/src/dataflow.rs index 1064b44d2cd76..1e89a9f51445b 100644 --- a/compiler/rustc_borrowck/src/dataflow.rs +++ b/compiler/rustc_borrowck/src/dataflow.rs @@ -360,7 +360,7 @@ impl<'tcx> rustc_mir_dataflow::GenKillAnalysis<'tcx> for Borrows<'_, 'tcx> { return; } let index = self.borrow_set.get_index_of(&location).unwrap_or_else(|| { - panic!("could not find BorrowIndex for location {:?}", location); + panic!("could not find BorrowIndex for location {location:?}"); }); trans.gen(index); diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 97c3e0b879a6a..03b90f4ab184e 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -653,7 +653,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { err.span_suggestion_verbose( sugg_span.shrink_to_hi(), "consider assigning a value", - format!(" = {}", assign_value), + format!(" = {assign_value}"), Applicability::MaybeIncorrect, ); } @@ -738,7 +738,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // Try to find predicates on *generic params* that would allow copying `ty` let suggestion = if let Some(symbol) = tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { - format!(": {}.clone()", symbol) + format!(": {symbol}.clone()") } else { ".clone()".to_owned() }; @@ -1162,8 +1162,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { if union_type_name != "" { err.note(format!( - "{} is a field of the union `{}`, so it overlaps the field {}", - msg_place, union_type_name, msg_borrow, + "{msg_place} is a field of the union `{union_type_name}`, so it overlaps the field {msg_borrow}", )); } @@ -1353,8 +1352,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let Some(trait_did) = tcx.trait_of_item(def_id) && tcx.is_diagnostic_item(sym::Iterator, trait_did) { err.note(format!( - "a for loop advances the iterator for you, the result is stored in `{}`.", - loop_bind + "a for loop advances the iterator for you, the result is stored in `{loop_bind}`." )); err.help("if you want to call `next` on a iterator within the loop, consider using `while let`."); } @@ -1825,7 +1823,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { }, ConstraintCategory::CallArgument(None), var_or_use_span, - &format!("`{}`", name), + &format!("`{name}`"), "block", ), ( @@ -1847,7 +1845,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { region_name, category, span, - &format!("`{}`", name), + &format!("`{name}`"), "function", ), ( @@ -1921,14 +1919,14 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } } - let mut err = self.path_does_not_live_long_enough(borrow_span, &format!("`{}`", name)); + let mut err = self.path_does_not_live_long_enough(borrow_span, &format!("`{name}`")); if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) { let region_name = annotation.emit(self, &mut err); err.span_label( borrow_span, - format!("`{}` would have to be valid for `{}`...", name, region_name), + format!("`{name}` would have to be valid for `{region_name}`..."), ); err.span_label( @@ -1939,7 +1937,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { self.infcx .tcx .opt_item_name(self.mir_def_id().to_def_id()) - .map(|name| format!("function `{}`", name)) + .map(|name| format!("function `{name}`")) .unwrap_or_else(|| { match &self.infcx.tcx.def_kind(self.mir_def_id()) { DefKind::Closure => "enclosing closure", @@ -1974,7 +1972,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } } else { err.span_label(borrow_span, "borrowed value does not live long enough"); - err.span_label(drop_span, format!("`{}` dropped here while still borrowed", name)); + err.span_label(drop_span, format!("`{name}` dropped here while still borrowed")); borrow_spans.args_subdiag(&mut err, |args_span| { crate::session_diagnostics::CaptureArgLabel::Capture { @@ -2018,22 +2016,17 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let mut err = self.cannot_borrow_across_destructor(borrow_span); let what_was_dropped = match self.describe_place(place.as_ref()) { - Some(name) => format!("`{}`", name), + Some(name) => format!("`{name}`"), None => String::from("temporary value"), }; let label = match self.describe_place(borrow.borrowed_place.as_ref()) { Some(borrowed) => format!( - "here, drop of {D} needs exclusive access to `{B}`, \ - because the type `{T}` implements the `Drop` trait", - D = what_was_dropped, - T = dropped_ty, - B = borrowed + "here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \ + because the type `{dropped_ty}` implements the `Drop` trait" ), None => format!( - "here is drop of {D}; whose type `{T}` implements the `Drop` trait", - D = what_was_dropped, - T = dropped_ty + "here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait" ), }; err.span_label(drop_span, label); @@ -2245,10 +2238,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } else { "local data " }; - ( - format!("{}`{}`", local_kind, place_desc), - format!("`{}` is borrowed here", place_desc), - ) + (format!("{local_kind}`{place_desc}`"), format!("`{place_desc}` is borrowed here")) } else { let root_place = self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All).last().unwrap(); @@ -2350,9 +2340,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { err.span_suggestion_verbose( sugg_span, format!( - "to force the {} to take ownership of {} (and any \ - other referenced variables), use the `move` keyword", - kind, captured_var + "to force the {kind} to take ownership of {captured_var} (and any \ + other referenced variables), use the `move` keyword" ), suggestion, Applicability::MachineApplicable, @@ -2360,7 +2349,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { match category { ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => { - let msg = format!("{} is returned here", kind); + let msg = format!("{kind} is returned here"); err.span_note(constraint_span, msg); } ConstraintCategory::CallArgument(_) => { @@ -2402,21 +2391,18 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { err.span_label( upvar_span, - format!("`{}` declared here, outside of the {} body", upvar_name, escapes_from), + format!("`{upvar_name}` declared here, outside of the {escapes_from} body"), ); - err.span_label(borrow_span, format!("borrow is only valid in the {} body", escapes_from)); + err.span_label(borrow_span, format!("borrow is only valid in the {escapes_from} body")); if let Some(name) = name { err.span_label( escape_span, - format!("reference to `{}` escapes the {} body here", name, escapes_from), + format!("reference to `{name}` escapes the {escapes_from} body here"), ); } else { - err.span_label( - escape_span, - format!("reference escapes the {} body here", escapes_from), - ); + err.span_label(escape_span, format!("reference escapes the {escapes_from} body here")); } err @@ -2697,10 +2683,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { }); if let Some(Ok(instance)) = deref_target { let deref_target_ty = instance.ty(tcx, self.param_env); - err.note(format!( - "borrow occurs due to deref coercion to `{}`", - deref_target_ty - )); + err.note(format!("borrow occurs due to deref coercion to `{deref_target_ty}`")); err.span_note(tcx.def_span(instance.def_id()), "deref defined here"); } } @@ -2756,7 +2739,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { "cannot assign twice to immutable variable" }; if span != assigned_span && !from_arg { - err.span_label(assigned_span, format!("first assignment to {}", place_description)); + err.span_label(assigned_span, format!("first assignment to {place_description}")); } if let Some(decl) = local_decl && let Some(name) = local_name @@ -2765,7 +2748,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { err.span_suggestion( decl.source_info.span, "consider making this binding mutable", - format!("mut {}", name), + format!("mut {name}"), Applicability::MachineApplicable, ); } @@ -3226,7 +3209,7 @@ impl<'tcx> AnnotatedBorrowFnSignature<'tcx> { return_span, } => { let argument_ty_name = cx.get_name_for_ty(argument_ty, 0); - diag.span_label(argument_span, format!("has type `{}`", argument_ty_name)); + diag.span_label(argument_span, format!("has type `{argument_ty_name}`")); let return_ty_name = cx.get_name_for_ty(return_ty, 0); let types_equal = return_ty_name == argument_ty_name; @@ -3253,15 +3236,14 @@ impl<'tcx> AnnotatedBorrowFnSignature<'tcx> { // Region of return type and arguments checked to be the same earlier. let region_name = cx.get_region_name_for_ty(*return_ty, 0); for (_, argument_span) in arguments { - diag.span_label(*argument_span, format!("has lifetime `{}`", region_name)); + diag.span_label(*argument_span, format!("has lifetime `{region_name}`")); } - diag.span_label(*return_span, format!("also has lifetime `{}`", region_name,)); + diag.span_label(*return_span, format!("also has lifetime `{region_name}`",)); diag.help(format!( - "use data from the highlighted arguments which match the `{}` lifetime of \ + "use data from the highlighted arguments which match the `{region_name}` lifetime of \ the return type", - region_name, )); region_name diff --git a/compiler/rustc_borrowck/src/facts.rs b/compiler/rustc_borrowck/src/facts.rs index 87fad9a355d3d..9916ebca32fa9 100644 --- a/compiler/rustc_borrowck/src/facts.rs +++ b/compiler/rustc_borrowck/src/facts.rs @@ -202,7 +202,7 @@ trait FactCell { impl FactCell for A { default fn to_string(&self, _location_table: &LocationTable) -> String { - format!("{:?}", self) + format!("{self:?}") } } diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index ea32506fc8980..32368f35fc99d 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -1817,8 +1817,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } ProjectionElem::Subslice { .. } => { - panic!("we don't allow assignments to subslices, location: {:?}", - location); + panic!("we don't allow assignments to subslices, location: {location:?}"); } ProjectionElem::Field(..) => { @@ -2017,8 +2016,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { self.infcx.tcx.sess.delay_span_bug( span, format!( - "Accessing `{:?}` with the kind `{:?}` shouldn't be possible", - place, kind, + "Accessing `{place:?}` with the kind `{kind:?}` shouldn't be possible", ), ); } diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs index b5014a3f479c7..679a19710a7f4 100644 --- a/compiler/rustc_borrowck/src/nll.rs +++ b/compiler/rustc_borrowck/src/nll.rs @@ -347,7 +347,7 @@ pub(super) fn dump_mir_results<'tcx>( for_each_region_constraint( infcx.tcx, closure_region_requirements, - &mut |msg| writeln!(out, "| {}", msg), + &mut |msg| writeln!(out, "| {msg}"), )?; writeln!(out, "|")?; } @@ -426,7 +426,7 @@ pub(super) fn dump_annotation<'tcx>( }; if !opaque_type_values.is_empty() { - err.note(format!("Inferred opaque type values:\n{:#?}", opaque_type_values)); + err.note(format!("Inferred opaque type values:\n{opaque_type_values:#?}")); } errors.buffer_non_error_diag(err); @@ -439,7 +439,7 @@ fn for_each_region_constraint<'tcx>( ) -> io::Result<()> { for req in &closure_region_requirements.outlives_requirements { let subject = match req.subject { - ClosureOutlivesSubject::Region(subject) => format!("{:?}", subject), + ClosureOutlivesSubject::Region(subject) => format!("{subject:?}"), ClosureOutlivesSubject::Ty(ty) => { format!("{:?}", ty.instantiate(tcx, |vid| ty::Region::new_var(tcx, vid))) } diff --git a/compiler/rustc_borrowck/src/region_infer/dump_mir.rs b/compiler/rustc_borrowck/src/region_infer/dump_mir.rs index 6524b594e44dc..4d620ac9de615 100644 --- a/compiler/rustc_borrowck/src/region_infer/dump_mir.rs +++ b/compiler/rustc_borrowck/src/region_infer/dump_mir.rs @@ -52,7 +52,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { writeln!(out, "|")?; writeln!(out, "| Inference Constraints")?; - self.for_each_constraint(tcx, &mut |msg| writeln!(out, "| {}", msg))?; + self.for_each_constraint(tcx, &mut |msg| writeln!(out, "| {msg}"))?; Ok(()) } @@ -69,7 +69,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { for region in self.definitions.indices() { let value = self.liveness_constraints.region_value_str(region); if value != "{}" { - with_msg(&format!("{:?} live at {}", region, value))?; + with_msg(&format!("{region:?} live at {value}"))?; } } @@ -81,12 +81,9 @@ impl<'tcx> RegionInferenceContext<'tcx> { Locations::All(span) => { ("All", tcx.sess.source_map().span_to_embeddable_string(*span)) } - Locations::Single(loc) => ("Single", format!("{:?}", loc)), + Locations::Single(loc) => ("Single", format!("{loc:?}")), }; - with_msg(&format!( - "{:?}: {:?} due to {:?} at {}({}) ({:?}", - sup, sub, category, name, arg, span - ))?; + with_msg(&format!("{sup:?}: {sub:?} due to {category:?} at {name}({arg}) ({span:?}"))?; } Ok(()) diff --git a/compiler/rustc_borrowck/src/region_infer/graphviz.rs b/compiler/rustc_borrowck/src/region_infer/graphviz.rs index 2e15586e03b3b..a0cf22e935a94 100644 --- a/compiler/rustc_borrowck/src/region_infer/graphviz.rs +++ b/compiler/rustc_borrowck/src/region_infer/graphviz.rs @@ -49,7 +49,7 @@ impl<'a, 'this, 'tcx> dot::Labeller<'this> for RawConstraints<'a, 'tcx> { Some(dot::LabelText::LabelStr(Cow::Borrowed("box"))) } fn node_label(&'this self, n: &RegionVid) -> dot::LabelText<'this> { - dot::LabelText::LabelStr(format!("{:?}", n).into()) + dot::LabelText::LabelStr(format!("{n:?}").into()) } fn edge_label(&'this self, e: &OutlivesConstraint<'tcx>) -> dot::LabelText<'this> { dot::LabelText::LabelStr(format!("{:?}", e.locations).into()) @@ -100,7 +100,7 @@ impl<'a, 'this, 'tcx> dot::Labeller<'this> for SccConstraints<'a, 'tcx> { } fn node_label(&'this self, n: &ConstraintSccIndex) -> dot::LabelText<'this> { let nodes = &self.nodes_per_scc[*n]; - dot::LabelText::LabelStr(format!("{:?} = {:?}", n, nodes).into()) + dot::LabelText::LabelStr(format!("{n:?} = {nodes:?}").into()) } } diff --git a/compiler/rustc_borrowck/src/region_infer/mod.rs b/compiler/rustc_borrowck/src/region_infer/mod.rs index fbbccc58ad666..30dfb2d919a3c 100644 --- a/compiler/rustc_borrowck/src/region_infer/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/mod.rs @@ -259,7 +259,7 @@ fn sccs_info<'cx, 'tcx>( let mut reg_vars_to_origins_str = "region variables to origins:\n".to_string(); for (reg_var, origin) in var_to_origin_sorted.into_iter() { - reg_vars_to_origins_str.push_str(&format!("{:?}: {:?}\n", reg_var, origin)); + reg_vars_to_origins_str.push_str(&format!("{reg_var:?}: {origin:?}\n")); } debug!("{}", reg_vars_to_origins_str); diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs index d8e81827a3be1..f5da848d1c0de 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs @@ -419,7 +419,7 @@ fn check_opaque_type_parameter_valid( return Err(tcx .sess .struct_span_err(span, "non-defining opaque type use in defining scope") - .span_note(spans, format!("{} used multiple times", descr)) + .span_note(spans, format!("{descr} used multiple times")) .emit()); } } diff --git a/compiler/rustc_borrowck/src/region_infer/values.rs b/compiler/rustc_borrowck/src/region_infer/values.rs index 9290e7479144a..d205862cd3fe0 100644 --- a/compiler/rustc_borrowck/src/region_infer/values.rs +++ b/compiler/rustc_borrowck/src/region_infer/values.rs @@ -470,7 +470,7 @@ fn region_value_str(elements: impl IntoIterator) -> String } push_sep(&mut result); - result.push_str(&format!("{:?}", fr)); + result.push_str(&format!("{fr:?}")); } RegionElement::PlaceholderRegion(placeholder) => { @@ -481,7 +481,7 @@ fn region_value_str(elements: impl IntoIterator) -> String } push_sep(&mut result); - result.push_str(&format!("{:?}", placeholder)); + result.push_str(&format!("{placeholder:?}")); } } } @@ -497,7 +497,7 @@ fn region_value_str(elements: impl IntoIterator) -> String fn push_location_range(str: &mut String, location1: Location, location2: Location) { if location1 == location2 { - str.push_str(&format!("{:?}", location1)); + str.push_str(&format!("{location1:?}")); } else { assert_eq!(location1.block, location2.block); str.push_str(&format!( diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs index 21f4593521840..df38fe6d50507 100644 --- a/compiler/rustc_builtin_macros/src/asm.rs +++ b/compiler/rustc_builtin_macros/src/asm.rs @@ -575,7 +575,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option, args: AsmArgs) -> Option format!("no {}arguments were given", positional), - 1 => format!("there is 1 {}argument", positional), - x => format!("there are {} {}arguments", x, positional), + 0 => format!("no {positional}arguments were given"), + 1 => format!("there is 1 {positional}argument"), + x => format!("there are {x} {positional}arguments"), }; err.note(msg); @@ -624,7 +624,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option Some(idx), None => { - let msg = format!("there is no argument named `{}`", name); + let msg = format!("there is no argument named `{name}`"); let span = arg.position_span; ecx.struct_span_err( template_span @@ -680,10 +680,10 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option, args: AsmArgs) -> Option, args: AsmArgs) -> Option cx.span_bug( trait_span, - format!("unexpected substructure in simple `derive({})`", name), + format!("unexpected substructure in simple `derive({name})`"), ), } } @@ -178,10 +178,10 @@ fn cs_clone( vdata = &variant.data; } EnumTag(..) | AllFieldlessEnum(..) => { - cx.span_bug(trait_span, format!("enum tags in `derive({})`", name,)) + cx.span_bug(trait_span, format!("enum tags in `derive({name})`",)) } StaticEnum(..) | StaticStruct(..) => { - cx.span_bug(trait_span, format!("associated function in `derive({})`", name)) + cx.span_bug(trait_span, format!("associated function in `derive({name})`")) } } @@ -193,7 +193,7 @@ fn cs_clone( let Some(ident) = field.name else { cx.span_bug( trait_span, - format!("unnamed field in normal struct in `derive({})`", name,), + format!("unnamed field in normal struct in `derive({name})`",), ); }; let call = subcall(cx, field); diff --git a/compiler/rustc_builtin_macros/src/deriving/decodable.rs b/compiler/rustc_builtin_macros/src/deriving/decodable.rs index 3921533c84a19..bcf11cb4ce9d4 100644 --- a/compiler/rustc_builtin_macros/src/deriving/decodable.rs +++ b/compiler/rustc_builtin_macros/src/deriving/decodable.rs @@ -204,7 +204,7 @@ where let fields = fields .iter() .enumerate() - .map(|(i, &span)| getarg(cx, span, Symbol::intern(&format!("_field{}", i)), i)) + .map(|(i, &span)| getarg(cx, span, Symbol::intern(&format!("_field{i}")), i)) .collect(); cx.expr_call(trait_span, path_expr, fields) diff --git a/compiler/rustc_builtin_macros/src/deriving/encodable.rs b/compiler/rustc_builtin_macros/src/deriving/encodable.rs index a3b11309d0ce1..2dc20c324972b 100644 --- a/compiler/rustc_builtin_macros/src/deriving/encodable.rs +++ b/compiler/rustc_builtin_macros/src/deriving/encodable.rs @@ -173,7 +173,7 @@ fn encodable_substructure( for (i, &FieldInfo { name, ref self_expr, span, .. }) in fields.iter().enumerate() { let name = match name { Some(id) => id.name, - None => Symbol::intern(&format!("_field{}", i)), + None => Symbol::intern(&format!("_field{i}")), }; let self_ref = cx.expr_addr_of(span, self_expr.clone()); let enc = diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index 9865b6a72ee69..6597ee3cf1b6c 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -1166,7 +1166,7 @@ impl<'a> MethodDef<'a> { .iter() .enumerate() .skip(1) - .map(|(arg_count, _selflike_arg)| format!("__arg{}", arg_count)), + .map(|(arg_count, _selflike_arg)| format!("__arg{arg_count}")), ) .collect::>(); @@ -1181,7 +1181,7 @@ impl<'a> MethodDef<'a> { let get_tag_pieces = |cx: &ExtCtxt<'_>| { let tag_idents: Vec<_> = prefixes .iter() - .map(|name| Ident::from_str_and_span(&format!("{}_tag", name), span)) + .map(|name| Ident::from_str_and_span(&format!("{name}_tag"), span)) .collect(); let mut tag_exprs: Vec<_> = tag_idents @@ -1521,7 +1521,7 @@ impl<'a> TraitDef<'a> { } fn mk_pattern_ident(&self, prefix: &str, i: usize) -> Ident { - Ident::from_str_and_span(&format!("{}_{}", prefix, i), self.span) + Ident::from_str_and_span(&format!("{prefix}_{i}"), self.span) } fn create_struct_pattern_fields( @@ -1602,8 +1602,7 @@ impl<'a> TraitDef<'a> { sp, ast::CRATE_NODE_ID, format!( - "{} slice in a packed struct that derives a built-in trait", - ty + "{ty} slice in a packed struct that derives a built-in trait" ), rustc_lint_defs::BuiltinLintDiagnostics::ByteSliceInPackedStructWithDerive ); diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index 4c878785b7b45..590db12a4cd0a 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -179,7 +179,7 @@ fn make_format_args( err.span_suggestion( unexpanded_fmt_span.shrink_to_lo(), "you might be missing a string literal to format with", - format!("\"{}\", ", sugg_fmt), + format!("\"{sugg_fmt}\", "), Applicability::MaybeIncorrect, ); } @@ -668,7 +668,7 @@ fn report_invalid_references( let num_args_desc = match args.explicit_args().len() { 0 => "no arguments were given".to_string(), 1 => "there is 1 argument".to_string(), - n => format!("there are {} arguments", n), + n => format!("there are {n} arguments"), }; let mut e; @@ -780,7 +780,7 @@ fn report_invalid_references( if num_placeholders == 1 { "is 1 argument".to_string() } else { - format!("are {} arguments", num_placeholders) + format!("are {num_placeholders} arguments") }, ), ); @@ -811,7 +811,7 @@ fn report_invalid_references( }; e = ecx.struct_span_err( span, - format!("invalid reference to positional {} ({})", arg_list, num_args_desc), + format!("invalid reference to positional {arg_list} ({num_args_desc})"), ); e.note("positional arguments are zero-based"); } diff --git a/compiler/rustc_builtin_macros/src/format_foreign.rs b/compiler/rustc_builtin_macros/src/format_foreign.rs index bd5356575ca87..e4369cb8fce9d 100644 --- a/compiler/rustc_builtin_macros/src/format_foreign.rs +++ b/compiler/rustc_builtin_macros/src/format_foreign.rs @@ -86,10 +86,7 @@ pub(crate) mod printf { '-' => c_left = true, '+' => c_plus = true, _ => { - return Err(Some(format!( - "the flag `{}` is unknown or unsupported", - c - ))); + return Err(Some(format!("the flag `{c}` is unknown or unsupported"))); } } } @@ -268,21 +265,21 @@ pub(crate) mod printf { impl Num { fn from_str(s: &str, arg: Option<&str>) -> Self { if let Some(arg) = arg { - Num::Arg(arg.parse().unwrap_or_else(|_| panic!("invalid format arg `{:?}`", arg))) + Num::Arg(arg.parse().unwrap_or_else(|_| panic!("invalid format arg `{arg:?}`"))) } else if s == "*" { Num::Next } else { - Num::Num(s.parse().unwrap_or_else(|_| panic!("invalid format num `{:?}`", s))) + Num::Num(s.parse().unwrap_or_else(|_| panic!("invalid format num `{s:?}`"))) } } fn translate(&self, s: &mut String) -> std::fmt::Result { use std::fmt::Write; match *self { - Num::Num(n) => write!(s, "{}", n), + Num::Num(n) => write!(s, "{n}"), Num::Arg(n) => { let n = n.checked_sub(1).ok_or(std::fmt::Error)?; - write!(s, "{}$", n) + write!(s, "{n}$") } Num::Next => write!(s, "*"), } @@ -626,8 +623,8 @@ pub mod shell { impl Substitution<'_> { pub fn as_str(&self) -> String { match self { - Substitution::Ordinal(n, _) => format!("${}", n), - Substitution::Name(n, _) => format!("${}", n), + Substitution::Ordinal(n, _) => format!("${n}"), + Substitution::Name(n, _) => format!("${n}"), Substitution::Escape(_) => "$$".into(), } } @@ -644,8 +641,8 @@ pub mod shell { pub fn translate(&self) -> Result> { match self { - Substitution::Ordinal(n, _) => Ok(format!("{{{}}}", n)), - Substitution::Name(n, _) => Ok(format!("{{{}}}", n)), + Substitution::Ordinal(n, _) => Ok(format!("{{{n}}}")), + Substitution::Name(n, _) => Ok(format!("{{{n}}}")), Substitution::Escape(_) => Err(None), } } diff --git a/compiler/rustc_builtin_macros/src/global_allocator.rs b/compiler/rustc_builtin_macros/src/global_allocator.rs index 5772471931f9d..053f5730f6ec2 100644 --- a/compiler/rustc_builtin_macros/src/global_allocator.rs +++ b/compiler/rustc_builtin_macros/src/global_allocator.rs @@ -72,7 +72,7 @@ impl AllocFnFactory<'_, '_> { let mut abi_args = ThinVec::new(); let mut i = 0; let mut mk = || { - let name = Ident::from_str_and_span(&format!("arg{}", i), self.span); + let name = Ident::from_str_and_span(&format!("arg{i}"), self.span); i += 1; name }; diff --git a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs index a7908373b6d88..7c0b36ced964a 100644 --- a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs +++ b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs @@ -179,8 +179,7 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> { == prev_item.path.segments[0].ident.name { format!( - "only one `#[{}]` attribute is allowed on any given function", - path_str, + "only one `#[{path_str}]` attribute is allowed on any given function", ) } else { format!( diff --git a/compiler/rustc_builtin_macros/src/source_util.rs b/compiler/rustc_builtin_macros/src/source_util.rs index e613b904d2eaf..433da74231f7a 100644 --- a/compiler/rustc_builtin_macros/src/source_util.rs +++ b/compiler/rustc_builtin_macros/src/source_util.rs @@ -149,7 +149,7 @@ pub fn expand_include<'cx>( Ok(None) => { if self.p.token != token::Eof { let token = pprust::token_to_string(&self.p.token); - let msg = format!("expected item, found `{}`", token); + let msg = format!("expected item, found `{token}`"); self.p.struct_span_err(self.p.token.span, msg).emit(); } diff --git a/compiler/rustc_codegen_llvm/src/asm.rs b/compiler/rustc_codegen_llvm/src/asm.rs index 2a6ad1be76309..c096d78025de1 100644 --- a/compiler/rustc_codegen_llvm/src/asm.rs +++ b/compiler/rustc_codegen_llvm/src/asm.rs @@ -76,7 +76,7 @@ impl<'ll, 'tcx> AsmBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { clobbered_x87 = true; clobbers.push("~{st}".to_string()); for i in 1..=7 { - clobbers.push(format!("~{{st({})}}", i)); + clobbers.push(format!("~{{st({i})}}")); } } continue; @@ -589,7 +589,7 @@ fn reg_to_llvm(reg: InlineAsmRegOrRegClass, layout: Option<&TyAndLayout<'_>>) -> // We use f32 as the type for discarded outputs 'x' }; - format!("{{{}mm{}}}", class, idx) + format!("{{{class}mm{idx}}}") } else if let Some(idx) = a64_reg_index(reg) { let class = if let Some(layout) = layout { match layout.size.bytes() { @@ -604,7 +604,7 @@ fn reg_to_llvm(reg: InlineAsmRegOrRegClass, layout: Option<&TyAndLayout<'_>>) -> // LLVM doesn't recognize x30. use lr instead. "{lr}".to_string() } else { - format!("{{{}{}}}", class, idx) + format!("{{{class}{idx}}}") } } else if let Some(idx) = a64_vreg_index(reg) { let class = if let Some(layout) = layout { @@ -620,7 +620,7 @@ fn reg_to_llvm(reg: InlineAsmRegOrRegClass, layout: Option<&TyAndLayout<'_>>) -> // We use i64x2 as the type for discarded outputs 'q' }; - format!("{{{}{}}}", class, idx) + format!("{{{class}{idx}}}") } else if reg == InlineAsmReg::Arm(ArmInlineAsmReg::r14) { // LLVM doesn't recognize r14 "{lr}".to_string() diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index 4c69b9503a2cf..1266ba1928568 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -450,7 +450,7 @@ pub fn from_fn_attrs<'ll, 'tcx>( let mut function_features = function_features .iter() .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 { InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(), diff --git a/compiler/rustc_codegen_llvm/src/back/archive.rs b/compiler/rustc_codegen_llvm/src/back/archive.rs index 10bf954d242cb..a82d2c5771a35 100644 --- a/compiler/rustc_codegen_llvm/src/back/archive.rs +++ b/compiler/rustc_codegen_llvm/src/back/archive.rs @@ -56,7 +56,7 @@ fn llvm_machine_type(cpu: &str) -> LLVMMachineType { "x86" => LLVMMachineType::I386, "aarch64" => LLVMMachineType::ARM64, "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 output_path = { 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") }; @@ -156,7 +156,7 @@ impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder { // functions. Therefore, use binutils to create the import library instead, // by writing a .DEF file to the temp dir and calling binutils's dlltool. 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!( "EXPORTS\n{}", @@ -164,7 +164,7 @@ impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder { .into_iter() .map(|(name, ordinal)| { match ordinal { - Some(n) => format!("{} @{} NONAME", name, n), + Some(n) => format!("{name} @{n} NONAME"), None => name, } }) @@ -435,7 +435,7 @@ impl<'a> LlvmArchiveBuilder<'a> { } 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 { diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index d7dd98d79389c..bf0ed8a4de0bc 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -332,7 +332,7 @@ fn fat_lto( let _timer = cgcx .prof .generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| { - recorder.record_arg(format!("{:?}", name)) + recorder.record_arg(format!("{name:?}")) }); info!("linking {:?}", name); let data = bc_decoded.data(); @@ -787,7 +787,7 @@ impl ThinLTOKeysMap { let file = File::create(path)?; let mut writer = io::BufWriter::new(file); for (module, key) in &self.keys { - writeln!(writer, "{} {}", module, key)?; + writeln!(writer, "{module} {key}")?; } Ok(()) } @@ -801,7 +801,7 @@ impl ThinLTOKeysMap { let mut split = line.split(' '); let module = 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()); } Ok(Self { keys }) diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index 0f5e975445fae..cbcbdea84daff 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -259,7 +259,7 @@ pub(crate) fn save_temp_bitcode( return; } unsafe { - let ext = format!("{}.bc", name); + let ext = format!("{name}.bc"); let cgu = Some(&module.name[..]); let path = cgcx.output_filenames.temp_path_ext(&ext, cgu); 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 }; - if write!(cursor, "{:#}", demangled).is_err() { + if write!(cursor, "{demangled:#}").is_err() { // Possible only if provided buffer is not big enough 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 { - 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.reserve(data.len()); for &byte in data { diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index d55992bf092f8..8c2b1831f0af0 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -1415,9 +1415,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { ) -> Cow<'b, [&'ll Value]> { assert!( self.cx.type_kind(fn_ty) == TypeKind::Function, - "builder::{} not passed a function, but {:?}", - typ, - fn_ty + "builder::{typ} not passed a function, but {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 name = if let Some(vector_length) = vector_length { - format!( - "llvm.{}.sat.v{}i{}.v{}f{}", - instr, vector_length, int_width, vector_length, float_width - ) + format!("llvm.{instr}.sat.v{vector_length}i{int_width}.v{vector_length}f{float_width}") } 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)); self.call(self.type_func(&[src_ty], dest_ty), None, None, f, &[val], None) diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index 4d879fbdcb7a7..130ff839e740c 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -420,10 +420,10 @@ pub(crate) fn i686_decorated_name( DllCallingConvention::C => {} DllCallingConvention::Stdcall(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) => { - write!(&mut decorated_name, "@@{}", arg_list_size).unwrap(); + write!(&mut decorated_name, "@@{arg_list_size}").unwrap(); } } } diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index df52f50f86f05..eb5969e56447c 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -238,8 +238,7 @@ impl<'ll> CodegenCx<'ll, '_> { assert!( !defined_in_current_codegen_unit, "consts::get_static() should always hit the cache for \ - statics defined in the same CGU, but did not for `{:?}`", - def_id + statics defined in the same CGU, but did not for `{def_id:?}`" ); let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all()); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs index 37f30917609ae..ed962bb3e3c91 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs @@ -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 // is defined inline as opposed to in a standalone file. 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(&visualizer.src); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index 905e0e541a8a4..40f0bcfdf58a4 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -184,9 +184,7 @@ fn build_pointer_or_reference_di_node<'ll, 'tcx>( debug_assert_eq!( (data_layout.pointer_size, data_layout.pointer_align.abi), cx.size_and_align_of(ptr_type), - "ptr_type={}, pointee_type={}", - ptr_type, - pointee_type, + "ptr_type={ptr_type}, pointee_type={pointee_type}", ); 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 { let mut hex_string = String::with_capacity(data.len() * 2); for byte in data.iter() { - write!(&mut hex_string, "{:02x}", byte).unwrap(); + write!(&mut hex_string, "{byte:02x}").unwrap(); } hex_string } @@ -766,7 +764,7 @@ fn build_param_type_di_node<'ll, 'tcx>( t: Ty<'tcx>, ) -> DINodeCreationResult<'ll> { debug!("build_param_type_di_node: {:?}", t); - let name = format!("{:?}", t); + let name = format!("{t:?}"); DINodeCreationResult { di_node: unsafe { llvm::LLVMRustDIBuilderCreateBasicType( @@ -814,7 +812,7 @@ pub fn build_compile_unit_di_node<'ll, 'tcx>( debug!("build_compile_unit_di_node: {:?}", name_in_debuginfo); 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. - 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 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 // because their might be multiple methods with the same name // (coming from different traits). - (format!("__method{}", index), void_pointer_type_di_node) + (format!("__method{index}"), void_pointer_type_di_node) } 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::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 .get(field_index) .map(|s| Cow::from(*s)) - .unwrap_or_else(|| Cow::from(format!("__{}", field_index))) + .unwrap_or_else(|| Cow::from(format!("__{field_index}"))) } diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs b/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs index 7be8363867606..c758010c58192 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs @@ -91,8 +91,7 @@ pub(crate) fn fat_pointer_kind<'ll, 'tcx>( // For all other pointee types we should already have returned None // at the beginning of the function. panic!( - "fat_pointer_kind() - Encountered unexpected `pointee_tail_ty`: {:?}", - pointee_tail_ty + "fat_pointer_kind() - Encountered unexpected `pointee_tail_ty`: {pointee_tail_ty:?}" ) } } diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 6df1b708ccd45..94521b2b49404 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -230,22 +230,22 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> { sym::ctlz | sym::cttz => { let y = self.const_bool(false); self.call_intrinsic( - &format!("llvm.{}.i{}", name, width), + &format!("llvm.{name}.i{width}"), &[args[0].immediate(), y], ) } sym::ctlz_nonzero => { 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]) } sym::cttz_nonzero => { 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]) } sym::ctpop => self.call_intrinsic( - &format!("llvm.ctpop.i{}", width), + &format!("llvm.ctpop.i{width}"), &[args[0].immediate()], ), 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 } else { self.call_intrinsic( - &format!("llvm.bswap.i{}", width), + &format!("llvm.bswap.i{width}"), &[args[0].immediate()], ) } } sym::bitreverse => self.call_intrinsic( - &format!("llvm.bitreverse.i{}", width), + &format!("llvm.bitreverse.i{width}"), &[args[0].immediate()], ), 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)), _ => 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 c = bx.call( 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_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( &[llvm_pointer_vec_ty, alignment_ty, mask_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_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 = 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); diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 5aab06febe44b..bb264db22d9fc 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -298,21 +298,21 @@ impl CodegenBackend for LlvmCodegenBackend { "ropi-rwpi", "default", ] { - writeln!(out, " {}", name); + writeln!(out, " {name}"); } writeln!(out); } PrintKind::CodeModels => { writeln!(out, "Available code models:"); for name in &["tiny", "small", "kernel", "medium", "large"] { - writeln!(out, " {}", name); + writeln!(out, " {name}"); } writeln!(out); } PrintKind::TlsModels => { writeln!(out, "Available TLS models:"); for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] { - writeln!(out, " {}", name); + writeln!(out, " {name}"); } writeln!(out); } diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index 4f20fbf2045a9..2dfd168805c70 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -315,7 +315,7 @@ pub fn target_features(sess: &Session, allow_unstable: bool) -> Vec { pub fn print_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) { @@ -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:"); 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:"); 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() { writeln!(out, " Target features listing is not supported by this LLVM version."); @@ -575,7 +575,7 @@ pub(crate) fn global_llvm_features(sess: &Session, diagnostics: bool) -> Vec { - Some(format!("{}{}", enable_disable, f)) + Some(format!("{enable_disable}{f}")) } _ => None, } diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index eefa4ac34dde2..cd6201648ee9b 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -748,7 +748,7 @@ fn link_natively<'a>( for print in &sess.opts.prints { if print.kind == PrintKind::LinkArgs { - let content = format!("{:?}", cmd); + let content = format!("{cmd:?}"); 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") - .map(|channel| format!("-{}", channel)) - .unwrap_or_default(); + let channel = + option_env!("CFG_RELEASE_CHANNEL").map(|channel| format!("-{channel}")).unwrap_or_default(); if sess.target.is_like_osx { // On Apple platforms, the sanitizer is always built as a dylib, and // LLVM will link to `@rpath/*.dylib`, so we need to specify an // rpath to the library as well (the rpath should be absolute, see // 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 rpath = path.to_str().expect("non-utf8 component in path"); linker.args(&["-Wl,-rpath", "-Xlinker", rpath]); linker.link_dylib(&filename, false, true); } 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); linker.link_whole_rlib(&path); } @@ -1415,12 +1414,12 @@ fn print_native_static_libs( } else if sess.target.linker_flavor.is_gnu() { Some(format!("-l{}{}", if verbatim { ":" } else { "" }, name)) } else { - Some(format!("-l{}", name)) + Some(format!("-l{name}")) } } NativeLibKind::Framework { .. } => { // 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 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 // check to see if the file is there and just omit linking to it if it's // not present. - let name = format!("{}.dll.lib", lib); + let name = format!("{lib}.dll.lib"); if path.join(&name).exists() { lib_args.push(name); } } else { - lib_args.push(format!("-l{}", lib)); + lib_args.push(format!("-l{lib}")); } } @@ -1628,8 +1627,8 @@ fn exec_linker( write!(f, "\"")?; for c in self.arg.chars() { match c { - '"' => write!(f, "\\{}", c)?, - c => write!(f, "{}", c)?, + '"' => write!(f, "\\{c}")?, + c => write!(f, "{c}")?, } } write!(f, "\"")?; @@ -1646,8 +1645,8 @@ fn exec_linker( // ensure the line is interpreted as one whole argument. for c in self.arg.chars() { match c { - '\\' | ' ' => write!(f, "\\{}", c)?, - c => write!(f, "{}", c)?, + '\\' | ' ' => write!(f, "\\{c}")?, + c => write!(f, "{c}")?, } } } @@ -2284,7 +2283,7 @@ fn add_order_independent_options( } 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 { diff --git a/compiler/rustc_codegen_ssa/src/back/linker.rs b/compiler/rustc_codegen_ssa/src/back/linker.rs index cd56f85cccdea..c5bbfecae4ff3 100644 --- a/compiler/rustc_codegen_ssa/src/back/linker.rs +++ b/compiler/rustc_codegen_ssa/src/back/linker.rs @@ -309,7 +309,7 @@ impl<'a> GccLinker<'a> { self.linker_arg(&format!("-plugin-opt=sample-profile={}", path.display())); }; self.linker_args(&[ - &format!("-plugin-opt={}", opt_level), + &format!("-plugin-opt={opt_level}"), &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) { 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) { @@ -672,7 +672,7 @@ impl<'a> Linker for GccLinker<'a> { let mut f = BufWriter::new(File::create(&path)?); for sym in symbols { debug!(" _{}", sym); - writeln!(f, "_{}", sym)?; + writeln!(f, "_{sym}")?; } }; if let Err(error) = res { @@ -687,7 +687,7 @@ impl<'a> Linker for GccLinker<'a> { writeln!(f, "EXPORTS")?; for symbol in symbols { debug!(" _{}", symbol); - writeln!(f, " {}", symbol)?; + writeln!(f, " {symbol}")?; } }; if let Err(error) = res { @@ -702,7 +702,7 @@ impl<'a> Linker for GccLinker<'a> { writeln!(f, " global:")?; for sym in symbols { debug!(" {};", sym); - writeln!(f, " {};", sym)?; + writeln!(f, " {sym};")?; } } 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 // check to see if the file is there and just omit linking to it if it's // not present. - let name = format!("{}.dll.lib", lib); + let name = format!("{lib}.dll.lib"); if path.join(&name).exists() { self.cmd.arg(name); } @@ -978,7 +978,7 @@ impl<'a> Linker for MsvcLinker<'a> { writeln!(f, "EXPORTS")?; for symbol in symbols { debug!(" _{}", symbol); - writeln!(f, " {}", symbol)?; + writeln!(f, " {symbol}")?; } }; if let Err(error) = res { @@ -992,7 +992,7 @@ impl<'a> Linker for MsvcLinker<'a> { fn subsystem(&mut self, subsystem: &str) { // Note that previous passes of the compiler validated this subsystem, // 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 // and windows subsystems. These both implicitly have different entry @@ -1350,7 +1350,7 @@ impl<'a> Linker for L4Bender<'a> { } fn link_staticlib(&mut self, lib: &str, _verbatim: bool) { self.hint_static(); - self.cmd.arg(format!("-PC{}", lib)); + self.cmd.arg(format!("-PC{lib}")); } fn link_rlib(&mut self, lib: &Path) { 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]) { 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"); } @@ -1453,7 +1453,7 @@ impl<'a> Linker for L4Bender<'a> { } 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) { @@ -1518,12 +1518,12 @@ impl<'a> AixLinker<'a> { impl<'a> Linker for AixLinker<'a> { fn link_dylib(&mut self, lib: &str, _verbatim: bool, _as_needed: bool) { self.hint_dynamic(); - self.cmd.arg(format!("-l{}", lib)); + self.cmd.arg(format!("-l{lib}")); } fn link_staticlib(&mut self, lib: &str, _verbatim: bool) { self.hint_static(); - self.cmd.arg(format!("-l{}", lib)); + self.cmd.arg(format!("-l{lib}")); } 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) { 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) { @@ -1627,11 +1627,11 @@ impl<'a> Linker for AixLinker<'a> { // FIXME: use llvm-nm to generate export list. for symbol in symbols { debug!(" _{}", symbol); - writeln!(f, " {}", symbol)?; + writeln!(f, " {symbol}")?; } }; 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())); } @@ -1908,7 +1908,7 @@ impl<'a> Linker for BpfLinker<'a> { let res: io::Result<()> = try { let mut f = BufWriter::new(File::create(&path)?); for sym in symbols { - writeln!(f, "{}", sym)?; + writeln!(f, "{sym}")?; } }; if let Err(error) = res { diff --git a/compiler/rustc_codegen_ssa/src/back/metadata.rs b/compiler/rustc_codegen_ssa/src/back/metadata.rs index c4bb51edade61..5c7df29444b80 100644 --- a/compiler/rustc_codegen_ssa/src/back/metadata.rs +++ b/compiler/rustc_codegen_ssa/src/back/metadata.rs @@ -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; 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 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; if offset + len > (info_data.len() as usize) { return Err(format!( - "Metadata at offset {} with size {} is beyond .info section", - offset, len + "Metadata at offset {offset} with size {len} is beyond .info section" )); } return Ok(&info_data[offset..(offset + len)]); } else { - return Err(format!("Unable to find symbol {}", AIX_METADATA_SYMBOL_NAME)); + return Err(format!("Unable to find symbol {AIX_METADATA_SYMBOL_NAME}")); }; } diff --git a/compiler/rustc_codegen_ssa/src/back/rpath.rs b/compiler/rustc_codegen_ssa/src/back/rpath.rs index 0b5656c9ad127..1826862234120 100644 --- a/compiler/rustc_codegen_ssa/src/back/rpath.rs +++ b/compiler/rustc_codegen_ssa/src/back/rpath.rs @@ -86,7 +86,7 @@ fn get_rpath_relative_to_output(config: &mut RPathConfig<'_>, lib: &Path) -> Str output.pop(); // strip filename let output = fs::canonicalize(&output).unwrap_or(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 format!("{}/{}", prefix, relative.to_str().expect("non-utf8 component in path")) } diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 6c781c6f0820d..a77649c5336ac 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -1471,7 +1471,7 @@ fn start_executing_work( } } Err(e) => { - let msg = &format!("failed to acquire jobserver token: {}", e); + let msg = &format!("failed to acquire jobserver token: {e}"); shared_emitter.fatal(msg); codegen_state = Aborted; } @@ -2041,7 +2041,7 @@ pub fn submit_pre_lto_module_to_llvm( } 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 { diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index 64f799bb1e68e..067c824aba03a 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -414,7 +414,7 @@ fn push_debuginfo_type_name<'tcx>( } // Type parameters from polymorphized functions. ty::Param(_) => { - write!(output, "{:?}", t).unwrap(); + write!(output, "{t:?}").unwrap(); } ty::Error(_) | ty::Infer(_) @@ -565,9 +565,9 @@ fn push_disambiguated_special_name( output: &mut String, ) { if cpp_like_debuginfo { - write!(output, "{}${}", label, disambiguator).unwrap(); + write!(output, "{label}${disambiguator}").unwrap(); } 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) => { 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; - write!(output, "{}", val) + write!(output, "{val}") } ty::Uint(_) => { let val = ct.eval_bits(tcx, ty::ParamEnv::reveal_all(), ct.ty()); - write!(output, "{}", val) + write!(output, "{val}") } ty::Bool => { 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 @@ -678,9 +678,9 @@ fn push_const_param<'tcx>(tcx: TyCtxt<'tcx>, ct: ty::Const<'tcx>, output: &mut S }); if cpp_like_debuginfo(tcx) { - write!(output, "CONST${:x}", hash_short) + write!(output, "CONST${hash_short:x}") } 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) { - assert!(output.ends_with('>'), "'output' does not end with '>': {}", output); + assert!(output.ends_with('>'), "'output' does not end with '>': {output}"); output.pop(); if output.ends_with(' ') { output.pop(); diff --git a/compiler/rustc_codegen_ssa/src/errors.rs b/compiler/rustc_codegen_ssa/src/errors.rs index dbe1d6e8ba89a..b7d8b9b45bf16 100644 --- a/compiler/rustc_codegen_ssa/src/errors.rs +++ b/compiler/rustc_codegen_ssa/src/errors.rs @@ -177,31 +177,31 @@ impl IntoDiagnostic<'_> for ThorinErrorWrapper { } thorin::Error::NamelessSection(_, offset) => { 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 } thorin::Error::RelocationWithInvalidSymbol(section, offset) => { diag = handler.struct_err(fluent::codegen_ssa_thorin_relocation_with_invalid_symbol); diag.set_arg("section", section); - diag.set_arg("offset", format!("0x{:08x}", offset)); + diag.set_arg("offset", format!("0x{offset:08x}")); diag } thorin::Error::MultipleRelocations(section, offset) => { diag = handler.struct_err(fluent::codegen_ssa_thorin_multiple_relocations); diag.set_arg("section", section); - diag.set_arg("offset", format!("0x{:08x}", offset)); + diag.set_arg("offset", format!("0x{offset:08x}")); diag } thorin::Error::UnsupportedRelocation(section, offset) => { diag = handler.struct_err(fluent::codegen_ssa_thorin_unsupported_relocation); diag.set_arg("section", section); - diag.set_arg("offset", format!("0x{:08x}", offset)); + diag.set_arg("offset", format!("0x{offset:08x}")); diag } thorin::Error::MissingDwoName(id) => { 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 } thorin::Error::NoCompilationUnits => { @@ -251,7 +251,7 @@ impl IntoDiagnostic<'_> for ThorinErrorWrapper { } thorin::Error::StrAtOffset(_, 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 } thorin::Error::ParseIndex(_, section) => { @@ -261,7 +261,7 @@ impl IntoDiagnostic<'_> for ThorinErrorWrapper { } thorin::Error::UnitNotInIndex(unit) => { 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 } thorin::Error::RowNotInIndex(_, row) => { @@ -275,7 +275,7 @@ impl IntoDiagnostic<'_> for ThorinErrorWrapper { } thorin::Error::EmptyUnit(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 } thorin::Error::MultipleDebugInfoSection => { @@ -292,12 +292,12 @@ impl IntoDiagnostic<'_> for ThorinErrorWrapper { } thorin::Error::DuplicateUnit(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 } thorin::Error::MissingReferencedUnit(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 } thorin::Error::NoOutputObjectCreated => { diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index ed608bdbe9a8a..23c736c15798e 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -703,13 +703,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { with_no_trimmed_paths!({ if layout.abi.is_uninhabited() { // 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 { - format!("attempted to zero-initialize type `{}`, which is invalid", ty) + format!("attempted to zero-initialize type `{ty}`, which is invalid") } else { format!( - "attempted to leave type `{}` uninitialized, which is invalid", - ty + "attempted to leave type `{ty}` uninitialized, which is invalid" ) } }) @@ -1045,10 +1044,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { assert_eq!( fn_abi.args.len(), mir_args + 1, - "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {:?} {:?} {:?}", - instance, - fn_span, - fn_abi, + "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}", ); let location = 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 { let llbb = self.llbb(bb); 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 funclet = cleanup_bx.cleanup_pad(None, &[]); cleanup_bx.br(llbb); @@ -1675,7 +1671,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { match self.cached_llbbs[bb] { CachedLlbb::None => { // 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); Some(llbb) } diff --git a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs index 34b8d8b5a6f02..4167a85ccd590 100644 --- a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs +++ b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs @@ -337,7 +337,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } else { Some(match whole_local_var.or(fallback_var.clone()) { Some(var) if var.name != kw::Empty => var.name.to_string(), - _ => format!("{:?}", local), + _ => format!("{local:?}"), }) }; diff --git a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs index 1f90a28eb8eef..e7539da0a0593 100644 --- a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs +++ b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs @@ -397,8 +397,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { ) -> OperandRef<'tcx, Bx::Value> { assert!( self.rvalue_creates_operand(rvalue, DUMMY_SP), - "cannot codegen {:?} to operand", - rvalue, + "cannot codegen {rvalue:?} to operand", ); match *rvalue { diff --git a/compiler/rustc_codegen_ssa/src/mono_item.rs b/compiler/rustc_codegen_ssa/src/mono_item.rs index b72a1a07866df..6fbf992eda9ec 100644 --- a/compiler/rustc_codegen_ssa/src/mono_item.rs +++ b/compiler/rustc_codegen_ssa/src/mono_item.rs @@ -140,8 +140,8 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> { MonoItem::Fn(instance) => { format!("Fn({:?}, {})", instance.def, instance.args.as_ptr().addr()) } - MonoItem::Static(id) => format!("Static({:?})", id), - MonoItem::GlobalAsm(id) => format!("GlobalAsm({:?})", id), + MonoItem::Static(id) => format!("Static({id:?})"), + MonoItem::GlobalAsm(id) => format!("GlobalAsm({id:?})"), } } } diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index 48c6c75bb1a24..98e561b0aef63 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -369,9 +369,9 @@ pub fn from_target_feature( // We allow comma separation to enable multiple features. target_features.extend(value.as_str().split(',').filter_map(|feature| { 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); - 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('+') { let valid = supported_target_features.contains_key(stripped); if valid { @@ -405,7 +405,7 @@ pub fn from_target_feature( &tcx.sess.parse_sess, feature_gate.unwrap(), item.span(), - format!("the target feature `{}` is currently unstable", feature), + format!("the target feature `{feature}` is currently unstable"), ) .emit(); } diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index b21cb984de67f..e31c68d33d2fe 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -52,7 +52,7 @@ fn eval_body_using_ecx<'mir, 'tcx>( trace!( "eval_body_using_ecx: pushing stack frame for global: {}{}", with_no_trimmed_paths!(ecx.tcx.def_path_str(cid.instance.def_id())), - cid.promoted.map_or_else(String::new, |p| format!("::promoted[{:?}]", p)) + cid.promoted.map_or_else(String::new, |p| format!("::promoted[{p:?}]")) ); ecx.push_stack_frame( diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index 9531d973eb323..206c53c04f771 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -57,7 +57,7 @@ fn slice_branches<'tcx>( ) -> ValTreeCreationResult<'tcx> { let n = place .len(&ecx.tcx.tcx) - .unwrap_or_else(|_| panic!("expected to use len of place {:?}", place)); + .unwrap_or_else(|_| panic!("expected to use len of place {place:?}")); let mut elems = Vec::with_capacity(n as usize); for i in 0..n { diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 04e046fbda352..d83b5bd197fab 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -1016,7 +1016,7 @@ impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug match self.place { Place::Local { frame, local } => { let mut allocs = Vec::new(); - write!(fmt, "{:?}", local)?; + write!(fmt, "{local:?}")?; if frame != self.ecx.frame_idx() { write!(fmt, " ({} frames up)", self.ecx.frame_idx() - frame)?; } @@ -1032,7 +1032,7 @@ impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug fmt, " by {} ref {:?}:", match mplace.meta { - MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta), + MemPlaceMeta::Meta(meta) => format!(" meta({meta:?})"), MemPlaceMeta::None => String::new(), }, mplace.ptr, @@ -1040,13 +1040,13 @@ impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug allocs.extend(mplace.ptr.provenance.map(Provenance::get_alloc_id)); } LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => { - write!(fmt, " {:?}", val)?; + write!(fmt, " {val:?}")?; if let Scalar::Ptr(ptr, _size) = val { allocs.push(ptr.provenance.get_alloc_id()); } } LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => { - write!(fmt, " ({:?}, {:?})", val1, val2)?; + write!(fmt, " ({val1:?}, {val2:?})")?; if let Scalar::Ptr(ptr, _size) = val1 { allocs.push(ptr.provenance.get_alloc_id()); } @@ -1062,7 +1062,7 @@ impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug Some(alloc_id) => { write!(fmt, "by ref {:?}: {:?}", mplace.ptr, self.ecx.dump_alloc(alloc_id)) } - ptr => write!(fmt, " integral by ref: {:?}", ptr), + ptr => write!(fmt, " integral by ref: {ptr:?}"), }, } } diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 04cae23f852a1..d7b1fd95523dc 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -393,17 +393,14 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // For *all* intrinsics we first check `is_uninhabited` to give a more specific // error message. _ if layout.abi.is_uninhabited() => format!( - "aborted execution: attempted to instantiate uninhabited type `{}`", - ty + "aborted execution: attempted to instantiate uninhabited type `{ty}`" ), ValidityRequirement::Inhabited => bug!("handled earlier"), ValidityRequirement::Zero => format!( - "aborted execution: attempted to zero-initialize type `{}`, which is invalid", - ty + "aborted execution: attempted to zero-initialize type `{ty}`, which is invalid" ), ValidityRequirement::UninitMitigated0x01Fill => format!( - "aborted execution: attempted to leave type `{}` uninitialized, which is invalid", - ty + "aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid" ), ValidityRequirement::Uninit => bug!("assert_uninit_valid doesn't exist"), }; @@ -419,9 +416,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { assert_eq!(input_len, dest_len, "Return vector length must match input length"); assert!( index < dest_len, - "Index `{}` must be in bounds of vector with length {}", - index, - dest_len + "Index `{index}` must be in bounds of vector with length {dest_len}" ); for i in 0..dest_len { @@ -439,9 +434,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let (input, input_len) = self.operand_to_simd(&args[0])?; assert!( index < input_len, - "index `{}` must be in bounds of vector with length {}", - index, - input_len + "index `{index}` must be in bounds of vector with length {input_len}" ); self.copy_op( &self.mplace_index(&input, index)?.into(), diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index 7b44a20ef03da..02d022a2252a1 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -53,7 +53,7 @@ impl fmt::Display for MemoryKind { match self { MemoryKind::Stack => write!(f, "stack variable"), MemoryKind::CallerLocation => write!(f, "caller location"), - MemoryKind::Machine(m) => write!(f, "{}", m), + MemoryKind::Machine(m) => write!(f, "{m}"), } } } @@ -907,7 +907,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> std::fmt::Debug for DumpAllocs<'a, match self.ecx.memory.alloc_map.get(id) { Some((kind, alloc)) => { // normal alloc - write!(fmt, " ({}, ", kind)?; + write!(fmt, " ({kind}, ")?; write_allocation_track_relocs( &mut *fmt, *self.ecx.tcx, diff --git a/compiler/rustc_const_eval/src/interpret/operator.rs b/compiler/rustc_const_eval/src/interpret/operator.rs index e04764636cc14..6f1d312656191 100644 --- a/compiler/rustc_const_eval/src/interpret/operator.rs +++ b/compiler/rustc_const_eval/src/interpret/operator.rs @@ -24,8 +24,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { debug_assert_eq!( Ty::new_tup(self.tcx.tcx, &[ty, self.tcx.types.bool]), dest.layout.ty, - "type mismatch for result of {:?}", - op, + "type mismatch for result of {op:?}", ); // Write the result to `dest`. if let Abi::ScalarPair(..) = dest.layout.abi { @@ -56,7 +55,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { dest: &PlaceTy<'tcx, M::Provenance>, ) -> InterpResult<'tcx> { let (val, _overflowed, ty) = self.overflowing_binary_op(op, left, right)?; - assert_eq!(ty, dest.layout.ty, "type mismatch for result of {:?}", op); + assert_eq!(ty, dest.layout.ty, "type mismatch for result of {op:?}"); self.write_scalar(val, dest) } } diff --git a/compiler/rustc_const_eval/src/interpret/step.rs b/compiler/rustc_const_eval/src/interpret/step.rs index 619da8abb7d22..1e7e3e743dc50 100644 --- a/compiler/rustc_const_eval/src/interpret/step.rs +++ b/compiler/rustc_const_eval/src/interpret/step.rs @@ -178,7 +178,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // The operand always has the same type as the result. let val = self.read_immediate(&self.eval_operand(operand, Some(dest.layout))?)?; let val = self.unary_op(un_op, &val)?; - assert_eq!(val.layout, dest.layout, "layout mismatch for result of {:?}", un_op); + assert_eq!(val.layout, dest.layout, "layout mismatch for result of {un_op:?}"); self.write_immediate(*val, &dest)?; } diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 21c655988a0e1..b62f56d03db75 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -164,14 +164,14 @@ fn write_path(out: &mut String, path: &[PathElem]) { for elem in path.iter() { match elem { - Field(name) => write!(out, ".{}", name), + Field(name) => write!(out, ".{name}"), EnumTag => write!(out, "."), - Variant(name) => write!(out, ".", name), + Variant(name) => write!(out, "."), GeneratorTag => write!(out, "."), GeneratorState(idx) => write!(out, ".", idx.index()), - CapturedVar(name) => write!(out, ".", name), - TupleElem(idx) => write!(out, ".{}", idx), - ArrayElem(idx) => write!(out, "[{}]", idx), + CapturedVar(name) => write!(out, "."), + TupleElem(idx) => write!(out, ".{idx}"), + ArrayElem(idx) => write!(out, "[{idx}]"), // `.` does not match Rust syntax, but it is more readable for long paths -- and // some of the other items here also are not Rust syntax. Actually we can't // even use the usual syntax because we are just showing the projections, diff --git a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs index 81337079af232..e785196c744c3 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs @@ -310,8 +310,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { if let Some(feature) = feature && ccx.tcx.sess.is_nightly_build() { err.help(format!( - "add `#![feature({})]` to the crate attributes to enable", - feature, + "add `#![feature({feature})]` to the crate attributes to enable", )); } @@ -346,10 +345,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallUnstable { err.help("const-stable functions can only call other const-stable functions"); } else if ccx.tcx.sess.is_nightly_build() { if let Some(feature) = feature { - err.help(format!( - "add `#![feature({})]` to the crate attributes to enable", - feature - )); + err.help(format!("add `#![feature({feature})]` to the crate attributes to enable")); } } diff --git a/compiler/rustc_const_eval/src/transform/validate.rs b/compiler/rustc_const_eval/src/transform/validate.rs index 7b2bed302db61..31effadd2c265 100644 --- a/compiler/rustc_const_eval/src/transform/validate.rs +++ b/compiler/rustc_const_eval/src/transform/validate.rs @@ -149,7 +149,7 @@ impl<'a, 'tcx> CfgChecker<'a, 'tcx> { } } } else { - self.fail(location, format!("encountered jump to invalid basic block {:?}", bb)) + self.fail(location, format!("encountered jump to invalid basic block {bb:?}")) } } @@ -222,8 +222,7 @@ impl<'a, 'tcx> CfgChecker<'a, 'tcx> { self.fail( Location { block: bb, statement_index: 0 }, format!( - "Cleanup control flow violation: Cycle involving edge {:?} -> {:?}", - bb, parent, + "Cleanup control flow violation: Cycle involving edge {bb:?} -> {parent:?}", ), ); break; @@ -257,7 +256,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> { if self.body.local_decls.get(local).is_none() { self.fail( location, - format!("local {:?} has no corresponding declaration in `body.local_decls`", local), + format!("local {local:?} has no corresponding declaration in `body.local_decls`"), ); } @@ -272,7 +271,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> { self.storage_liveness.seek_after_primary_effect(location); let locals_with_storage = self.storage_liveness.get(); if !locals_with_storage.contains(local) { - self.fail(location, format!("use of local {:?}, which has no storage here", local)); + self.fail(location, format!("use of local {local:?}, which has no storage here")); } } } @@ -323,7 +322,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> { // DropsLowered`. However, this causes ICEs with generation of drop shims, which // seem to fail to set their `MirPhase` correctly. if matches!(kind, RetagKind::Raw | RetagKind::TwoPhase) { - self.fail(location, format!("explicit `{:?}` is forbidden", kind)); + self.fail(location, format!("explicit `{kind:?}` is forbidden")); } } StatementKind::StorageLive(local) => { @@ -556,7 +555,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { let ty = place.ty(&self.body.local_decls, self.tcx).ty; if !ty.is_copy_modulo_regions(self.tcx, self.param_env) { - self.fail(location, format!("`Operand::Copy` with non-`Copy` type {}", ty)); + self.fail(location, format!("`Operand::Copy` with non-`Copy` type {ty}")); } } } @@ -575,7 +574,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ProjectionElem::Index(index) => { let index_ty = self.body.local_decls[index].ty; if index_ty != self.tcx.types.usize { - self.fail(location, format!("bad index ({:?} != usize)", index_ty)) + self.fail(location, format!("bad index ({index_ty:?} != usize)")) } } ProjectionElem::Deref @@ -586,22 +585,21 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { if base_ty.is_box() { self.fail( location, - format!("{:?} dereferenced after ElaborateBoxDerefs", base_ty), + format!("{base_ty:?} dereferenced after ElaborateBoxDerefs"), ) } } ProjectionElem::Field(f, ty) => { let parent_ty = place_ref.ty(&self.body.local_decls, self.tcx); let fail_out_of_bounds = |this: &mut Self, location| { - this.fail(location, format!("Out of bounds field {:?} for {:?}", f, parent_ty)); + this.fail(location, format!("Out of bounds field {f:?} for {parent_ty:?}")); }; let check_equal = |this: &mut Self, location, f_ty| { if !this.mir_assign_valid_types(ty, f_ty) { this.fail( location, format!( - "Field projection `{:?}.{:?}` specified type `{:?}`, but actual type is `{:?}`", - place_ref, f, ty, f_ty + "Field projection `{place_ref:?}.{f:?}` specified type `{ty:?}`, but actual type is `{f_ty:?}`" ) ) } @@ -649,7 +647,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { let Some(layout) = gen_body.generator_layout() else { self.fail( location, - format!("No generator layout for {:?}", parent_ty), + format!("No generator layout for {parent_ty:?}"), ); return; }; @@ -662,7 +660,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { let Some(f_ty) = layout.field_tys.get(local) else { self.fail( location, - format!("Out of bounds local {:?} for {:?}", local, parent_ty), + format!("Out of bounds local {local:?} for {parent_ty:?}"), ); return; }; @@ -705,7 +703,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { if debuginfo.references != 0 && place.projection.last() == Some(&PlaceElem::Deref) { self.fail( START_BLOCK.start_location(), - format!("debuginfo {:?}, has both ref and deref", debuginfo), + format!("debuginfo {debuginfo:?}, has both ref and deref"), ); } } @@ -715,7 +713,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { if ty.is_union() || ty.is_enum() { self.fail( START_BLOCK.start_location(), - format!("invalid type {:?} for composite debuginfo", ty), + format!("invalid type {ty:?} for composite debuginfo"), ); } if f.projection.iter().any(|p| !matches!(p, PlaceElem::Field(..))) { @@ -742,7 +740,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { && cntxt != PlaceContext::NonUse(NonUseContext::VarDebugInfo) && place.projection[1..].contains(&ProjectionElem::Deref) { - self.fail(location, format!("{:?}, has deref at the wrong place", place)); + self.fail(location, format!("{place:?}, has deref at the wrong place")); } self.super_place(place, cntxt, location); @@ -802,7 +800,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { Offset => { check_kinds!(a, "Cannot offset non-pointer type {:?}", ty::RawPtr(..)); if b != self.tcx.types.isize && b != self.tcx.types.usize { - self.fail(location, format!("Cannot offset by non-isize type {:?}", b)); + self.fail(location, format!("Cannot offset by non-isize type {b:?}")); } } Eq | Lt | Le | Ne | Ge | Gt => { @@ -867,13 +865,12 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { self.fail( location, format!( - "Cannot perform checked arithmetic on unequal types {:?} and {:?}", - a, b + "Cannot perform checked arithmetic on unequal types {a:?} and {b:?}" ), ); } } - _ => self.fail(location, format!("There is no checked version of {:?}", op)), + _ => self.fail(location, format!("There is no checked version of {op:?}")), } } Rvalue::UnaryOp(op, operand) => { @@ -1078,7 +1075,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { if !ty.is_bool() { self.fail( location, - format!("`assume` argument must be `bool`, but got: `{}`", ty), + format!("`assume` argument must be `bool`, but got: `{ty}`"), ); } } @@ -1091,7 +1088,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { } else { self.fail( location, - format!("Expected src to be ptr in copy_nonoverlapping, got: {}", src_ty), + format!("Expected src to be ptr in copy_nonoverlapping, got: {src_ty}"), ); return; }; @@ -1101,19 +1098,19 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { } else { self.fail( location, - format!("Expected dst to be ptr in copy_nonoverlapping, got: {}", dst_ty), + format!("Expected dst to be ptr in copy_nonoverlapping, got: {dst_ty}"), ); return; }; // since CopyNonOverlapping is parametrized by 1 type, // we only need to check that they are equal and not keep an extra parameter. if !self.mir_assign_valid_types(op_src_ty, op_dst_ty) { - self.fail(location, format!("bad arg ({:?} != {:?})", op_src_ty, op_dst_ty)); + self.fail(location, format!("bad arg ({op_src_ty:?} != {op_dst_ty:?})")); } let op_cnt_ty = count.ty(&self.body.local_decls, self.tcx); if op_cnt_ty != self.tcx.types.usize { - self.fail(location, format!("bad arg ({:?} != usize)", op_cnt_ty)) + self.fail(location, format!("bad arg ({op_cnt_ty:?} != usize)")) } } StatementKind::SetDiscriminant { place, .. } => { @@ -1125,8 +1122,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { self.fail( location, format!( - "`SetDiscriminant` is only allowed on ADTs and generators, not {:?}", - pty + "`SetDiscriminant` is only allowed on ADTs and generators, not {pty:?}" ), ); } @@ -1141,7 +1137,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { // DropsLowered`. However, this causes ICEs with generation of drop shims, which // seem to fail to set their `MirPhase` correctly. if matches!(kind, RetagKind::Raw | RetagKind::TwoPhase) { - self.fail(location, format!("explicit `{:?}` is forbidden", kind)); + self.fail(location, format!("explicit `{kind:?}` is forbidden")); } } StatementKind::StorageLive(_) @@ -1174,7 +1170,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { if Scalar::<()>::try_from_uint(value, size).is_none() { self.fail( location, - format!("the value {:#x} is not a proper {:?}", value, switch_ty), + format!("the value {value:#x} is not a proper {switch_ty:?}"), ) } } @@ -1185,7 +1181,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ty::FnPtr(..) | ty::FnDef(..) => {} _ => self.fail( location, - format!("encountered non-callable type {} in `Call` terminator", func_ty), + format!("encountered non-callable type {func_ty} in `Call` terminator"), ), } } @@ -1195,8 +1191,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { self.fail( location, format!( - "encountered non-boolean condition of type {} in `Assert` terminator", - cond_ty + "encountered non-boolean condition of type {cond_ty} in `Assert` terminator" ), ); } diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index 1879ece59e329..ba9f4c181ff5a 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -71,17 +71,17 @@ pub enum TranslationBundleError { impl fmt::Display for TranslationBundleError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - TranslationBundleError::ReadFtl(e) => write!(f, "could not read ftl file: {}", e), + TranslationBundleError::ReadFtl(e) => write!(f, "could not read ftl file: {e}"), TranslationBundleError::ParseFtl(e) => { - write!(f, "could not parse ftl file: {}", e) + write!(f, "could not parse ftl file: {e}") } - TranslationBundleError::AddResource(e) => write!(f, "failed to add resource: {}", e), + TranslationBundleError::AddResource(e) => write!(f, "failed to add resource: {e}"), TranslationBundleError::MissingLocale => write!(f, "missing locale directory"), TranslationBundleError::ReadLocalesDir(e) => { - write!(f, "could not read locales dir: {}", e) + write!(f, "could not read locales dir: {e}") } TranslationBundleError::ReadLocalesDirEntry(e) => { - write!(f, "could not read locales dir entry: {}", e) + write!(f, "could not read locales dir entry: {e}") } TranslationBundleError::LocaleIsNotDir => { write!(f, "`$sysroot/share/locales/$locale` is not a directory") diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index ed0d06ed0ff77..a96e317df55dc 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -420,13 +420,13 @@ impl Diagnostic { let expected_label = if expected_label.is_empty() { "expected".to_string() } else { - format!("expected {}", expected_label) + format!("expected {expected_label}") }; let found_label = found_label.to_string(); let found_label = if found_label.is_empty() { "found".to_string() } else { - format!("found {}", found_label) + format!("found {found_label}") }; let (found_padding, expected_padding) = if expected_label.len() > found_label.len() { (expected_label.len() - found_label.len(), 0) @@ -439,13 +439,13 @@ impl Diagnostic { StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle), StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight), })); - msg.push((format!("`{}\n", expected_extra), Style::NoStyle)); + msg.push((format!("`{expected_extra}\n"), Style::NoStyle)); msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle)); msg.extend(found.0.iter().map(|x| match *x { StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle), StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight), })); - msg.push((format!("`{}", found_extra), Style::NoStyle)); + msg.push((format!("`{found_extra}"), Style::NoStyle)); // For now, just attach these as notes. self.highlighted_note(msg); @@ -454,7 +454,7 @@ impl Diagnostic { pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self { self.highlighted_note(vec![ - (format!("`{}` from trait: `", name), Style::NoStyle), + (format!("`{name}` from trait: `"), Style::NoStyle), (signature, Style::Highlight), ("`".to_string(), Style::NoStyle), ]); diff --git a/compiler/rustc_errors/src/diagnostic_impls.rs b/compiler/rustc_errors/src/diagnostic_impls.rs index 10fe7fc74a873..9c972342f251e 100644 --- a/compiler/rustc_errors/src/diagnostic_impls.rs +++ b/compiler/rustc_errors/src/diagnostic_impls.rs @@ -102,7 +102,7 @@ impl IntoDiagnosticArg for bool { impl IntoDiagnosticArg for char { fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { - DiagnosticArgValue::Str(Cow::Owned(format!("{:?}", self))) + DiagnosticArgValue::Str(Cow::Owned(format!("{self:?}"))) } } diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index a0fa4115c3e49..7f69a93c64917 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -2145,7 +2145,7 @@ impl EmitterWriter { &mut self.dst, self.short_message, ) { - panic!("failed to emit error: {}", e) + panic!("failed to emit error: {e}") } } if !self.short_message { @@ -2161,7 +2161,7 @@ impl EmitterWriter { true, None, ) { - panic!("failed to emit error: {}", err); + panic!("failed to emit error: {err}"); } } for sugg in suggestions { @@ -2180,7 +2180,7 @@ impl EmitterWriter { true, None, ) { - panic!("failed to emit error: {}", e); + panic!("failed to emit error: {e}"); } } SuggestionStyle::HideCodeInline @@ -2193,22 +2193,22 @@ impl EmitterWriter { &Level::Help, max_line_num_len, ) { - panic!("failed to emit error: {}", e); + panic!("failed to emit error: {e}"); } } } } } } - Err(e) => panic!("failed to emit error: {}", e), + Err(e) => panic!("failed to emit error: {e}"), } let mut dst = self.dst.writable(); match writeln!(dst) { - Err(e) => panic!("failed to emit error: {}", e), + Err(e) => panic!("failed to emit error: {e}"), _ => { if let Err(e) = dst.flush() { - panic!("failed to emit error: {}", e) + panic!("failed to emit error: {e}") } } } diff --git a/compiler/rustc_errors/src/json.rs b/compiler/rustc_errors/src/json.rs index f32d6b96b9b24..55f7c48502463 100644 --- a/compiler/rustc_errors/src/json.rs +++ b/compiler/rustc_errors/src/json.rs @@ -159,7 +159,7 @@ impl Emitter for JsonEmitter { } .and_then(|_| self.dst.flush()); if let Err(e) = result { - panic!("failed to print diagnostics: {:?}", e); + panic!("failed to print diagnostics: {e:?}"); } } @@ -172,7 +172,7 @@ impl Emitter for JsonEmitter { } .and_then(|_| self.dst.flush()); if let Err(e) = result { - panic!("failed to print notification: {:?}", e); + panic!("failed to print notification: {e:?}"); } } @@ -194,7 +194,7 @@ impl Emitter for JsonEmitter { } .and_then(|_| self.dst.flush()); if let Err(e) = result { - panic!("failed to print future breakage report: {:?}", e); + panic!("failed to print future breakage report: {e:?}"); } } @@ -208,7 +208,7 @@ impl Emitter for JsonEmitter { } .and_then(|_| self.dst.flush()); if let Err(e) = result { - panic!("failed to print unused externs: {:?}", e); + panic!("failed to print unused externs: {e:?}"); } } diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 1da02e1bb012f..768c4cf6fb589 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -1739,13 +1739,11 @@ impl HandlerInner { (count, delayed_count, as_bug) => { if delayed_count > 0 { panic!( - "aborting after {} errors and {} delayed bugs due to `-Z treat-err-as-bug={}`", - count, delayed_count, as_bug, + "aborting after {count} errors and {delayed_count} delayed bugs due to `-Z treat-err-as-bug={as_bug}`", ) } else { panic!( - "aborting after {} errors due to `-Z treat-err-as-bug={}`", - count, as_bug, + "aborting after {count} errors due to `-Z treat-err-as-bug={as_bug}`", ) } } @@ -1871,7 +1869,7 @@ pub fn add_elided_lifetime_in_path_suggestion( } let anon_lts = vec!["'_"; n].join(", "); let suggestion = - if incl_angl_brckt { format!("<{}>", anon_lts) } else { format!("{}, ", anon_lts) }; + if incl_angl_brckt { format!("<{anon_lts}>") } else { format!("{anon_lts}, ") }; diag.span_suggestion_verbose( insertion_span.shrink_to_hi(), format!("indicate the anonymous lifetime{}", pluralize!(n)), diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 4ec5ac22e9074..05d7c243a2048 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -369,7 +369,7 @@ impl<'a> StripUnconfigured<'a> { let TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _) = orig_trees.next().unwrap() else { - panic!("Bad tokens for attribute {:?}", attr); + panic!("Bad tokens for attribute {attr:?}"); }; let pound_span = pound_token.span; @@ -379,7 +379,7 @@ impl<'a> StripUnconfigured<'a> { let TokenTree::Token(bang_token @ Token { kind: TokenKind::Not, .. }, _) = orig_trees.next().unwrap() else { - panic!("Bad tokens for attribute {:?}", attr); + panic!("Bad tokens for attribute {attr:?}"); }; trees.push(AttrTokenTree::Token(bang_token, Spacing::Alone)); } @@ -390,7 +390,7 @@ impl<'a> StripUnconfigured<'a> { Delimiter::Bracket, item.tokens .as_ref() - .unwrap_or_else(|| panic!("Missing tokens for {:?}", item)) + .unwrap_or_else(|| panic!("Missing tokens for {item:?}")) .to_attr_token_stream(), ); trees.push(bracket_group); diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 3b6db9fd39c29..165c6d47c8a7d 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -803,7 +803,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { &self.cx.sess.parse_sess, sym::proc_macro_hygiene, span, - format!("custom attributes cannot be applied to {}", kind), + format!("custom attributes cannot be applied to {kind}"), ) .emit(); } @@ -1707,7 +1707,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { &UNUSED_ATTRIBUTES, attr.span, self.cx.current_expansion.lint_node_id, - format!("unused attribute `{}`", attr_name), + format!("unused attribute `{attr_name}`"), BuiltinLintDiagnostics::UnusedBuiltinAttribute { attr_name, macro_name: pprust::path_to_string(&call.path), diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index 03de33dc8543c..e060375646c2d 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -257,7 +257,7 @@ pub(super) fn emit_frag_parse_err( e.span_suggestion_verbose( site_span, "surround the macro invocation with `{}` to interpret the expansion as a statement", - format!("{{ {}; }}", snippet), + format!("{{ {snippet}; }}"), Applicability::MaybeIncorrect, ); } diff --git a/compiler/rustc_expand/src/mbe/macro_check.rs b/compiler/rustc_expand/src/mbe/macro_check.rs index 34f998274e995..95f5bb2d2e230 100644 --- a/compiler/rustc_expand/src/mbe/macro_check.rs +++ b/compiler/rustc_expand/src/mbe/macro_check.rs @@ -593,7 +593,7 @@ fn check_ops_is_prefix( return; } } - buffer_lint(sess, span.into(), node_id, format!("unknown macro variable `{}`", name)); + buffer_lint(sess, span.into(), node_id, format!("unknown macro variable `{name}`")); } /// Returns whether `binder_ops` is a prefix of `occurrence_ops`. @@ -626,7 +626,7 @@ fn ops_is_prefix( if i >= occurrence_ops.len() { let mut span = MultiSpan::from_span(span); span.push_span_label(binder.span, "expected repetition"); - let message = format!("variable '{}' is still repeating at this depth", name); + let message = format!("variable '{name}' is still repeating at this depth"); buffer_lint(sess, span, node_id, message); return; } diff --git a/compiler/rustc_expand/src/mbe/macro_parser.rs b/compiler/rustc_expand/src/mbe/macro_parser.rs index f0e67cfd50e08..9f0f4740e0036 100644 --- a/compiler/rustc_expand/src/mbe/macro_parser.rs +++ b/compiler/rustc_expand/src/mbe/macro_parser.rs @@ -156,7 +156,7 @@ impl Display for MatcherLoc { MatcherLoc::MetaVarDecl { bind, kind, .. } => { write!(f, "meta-variable `${bind}")?; if let Some(kind) = kind { - write!(f, ":{}", kind)?; + write!(f, ":{kind}")?; } write!(f, "`")?; Ok(()) @@ -723,7 +723,7 @@ impl TtParser { .iter() .map(|mp| match &matcher[mp.idx] { MatcherLoc::MetaVarDecl { bind, kind: Some(kind), .. } => { - format!("{} ('{}')", kind, bind) + format!("{kind} ('{bind}')") } _ => unreachable!(), }) @@ -736,7 +736,7 @@ impl TtParser { "local ambiguity when calling macro `{}`: multiple parsing options: {}", self.macro_name, match self.next_mps.len() { - 0 => format!("built-in NTs {}.", nts), + 0 => format!("built-in NTs {nts}."), n => format!("built-in NTs {} or {n} other option{s}.", nts, s = pluralize!(n)), } ), @@ -757,7 +757,7 @@ impl TtParser { match ret_val.entry(MacroRulesNormalizedIdent::new(bind)) { Vacant(spot) => spot.insert(res.next().unwrap()), Occupied(..) => { - return Error(span, format!("duplicated bind name: {}", bind)); + return Error(span, format!("duplicated bind name: {bind}")); } }; } else { diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 102bae2a74491..a0dcd4d985717 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -554,7 +554,7 @@ pub fn compile_declarative_macro( let (transparency, transparency_error) = attr::find_transparency(&def.attrs, macro_rules); match transparency_error { Some(TransparencyError::UnknownTransparency(value, span)) => { - diag.span_err(span, format!("unknown macro transparency: `{}`", value)); + diag.span_err(span, format!("unknown macro transparency: `{value}`")); } Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => { diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes"); @@ -1197,7 +1197,7 @@ fn check_matcher_core<'tt>( may_be = may_be ), ); - err.span_label(sp, format!("not allowed after `{}` fragments", kind)); + err.span_label(sp, format!("not allowed after `{kind}` fragments")); if kind == NonterminalKind::PatWithOr && sess.edition.at_least_rust_2021() @@ -1221,8 +1221,7 @@ fn check_matcher_core<'tt>( &[] => {} &[t] => { err.note(format!( - "only {} is allowed after `{}` fragments", - t, kind, + "only {t} is allowed after `{kind}` fragments", )); } ts => { @@ -1407,9 +1406,9 @@ fn is_in_follow(tok: &mbe::TokenTree, kind: NonterminalKind) -> IsInFollow { fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String { match tt { mbe::TokenTree::Token(token) => pprust::token_to_string(&token).into(), - mbe::TokenTree::MetaVar(_, name) => format!("${}", name), - mbe::TokenTree::MetaVarDecl(_, name, Some(kind)) => format!("${}:{}", name, kind), - mbe::TokenTree::MetaVarDecl(_, name, None) => format!("${}:", name), + mbe::TokenTree::MetaVar(_, name) => format!("${name}"), + mbe::TokenTree::MetaVarDecl(_, name, Some(kind)) => format!("${name}:{kind}"), + mbe::TokenTree::MetaVarDecl(_, name, None) => format!("${name}:"), _ => panic!( "{}", "unexpected mbe::TokenTree::{Sequence or Delimited} \ diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index 40bfa3715be7b..60f6a29fd163a 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -194,7 +194,7 @@ fn parse_tree( Delimiter::Parenthesis => {} _ => { let tok = pprust::token_kind_to_string(&token::OpenDelim(delim)); - let msg = format!("expected `(` or `{{`, found `{}`", tok); + let msg = format!("expected `(` or `{{`, found `{tok}`"); sess.span_diagnostic.span_err(delim_span.entire(), msg); } } diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index 41b24407fa07c..c617cd76e3cb0 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -95,7 +95,7 @@ impl base::AttrProcMacro for AttrProcMacro { |e| { let mut err = ecx.struct_span_err(span, "custom attribute panicked"); if let Some(s) = e.as_str() { - err.help(format!("message: {}", s)); + err.help(format!("message: {s}")); } err.emit() }, @@ -148,7 +148,7 @@ impl MultiItemModifier for DeriveProcMacro { Err(e) => { let mut err = ecx.struct_span_err(span, "proc-macro derive panicked"); if let Some(s) = e.as_str() { - err.help(format!("message: {}", s)); + err.help(format!("message: {s}")); } err.emit(); return ExpandResult::Ready(vec![]); diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index ecd2315112a68..1d18a6abb46aa 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -622,7 +622,7 @@ impl server::SourceFile for Rustc<'_, '_> { impl server::Span for Rustc<'_, '_> { fn debug(&mut self, span: Self::Span) -> String { if self.ecx.ecfg.span_debug { - format!("{:?}", span) + format!("{span:?}") } else { format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0) } diff --git a/compiler/rustc_hir_analysis/src/astconv/errors.rs b/compiler/rustc_hir_analysis/src/astconv/errors.rs index 7f4927bbb98ff..bd311c98facfb 100644 --- a/compiler/rustc_hir_analysis/src/astconv/errors.rs +++ b/compiler/rustc_hir_analysis/src/astconv/errors.rs @@ -197,7 +197,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } } - err.span_label(span, format!("associated type `{}` not found", assoc_name)); + err.span_label(span, format!("associated type `{assoc_name}` not found")); err.emit() } @@ -393,7 +393,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .into_iter() .map(|error| error.root_obligation.predicate) .filter_map(format_pred) - .map(|(p, _)| format!("`{}`", p)) + .map(|(p, _)| format!("`{p}`")) .collect(); bounds.sort(); bounds.dedup(); @@ -652,7 +652,7 @@ pub(crate) fn fn_trait_to_string( } .map(|s| { // `s.empty()` checks to see if the type is the unit tuple, if so we don't want a comma - if parenthesized || s.is_empty() { format!("({})", s) } else { format!("({},)", s) } + if parenthesized || s.is_empty() { format!("({s})") } else { format!("({s},)") } }) .ok(), _ => None, diff --git a/compiler/rustc_hir_analysis/src/astconv/generics.rs b/compiler/rustc_hir_analysis/src/astconv/generics.rs index e81c61d80eddb..1372cc896be3f 100644 --- a/compiler/rustc_hir_analysis/src/astconv/generics.rs +++ b/compiler/rustc_hir_analysis/src/astconv/generics.rs @@ -81,7 +81,7 @@ fn generic_arg_mismatch_err( err.span_suggestion( tcx.def_span(src_def_id), "consider changing this type parameter to a const parameter", - format!("const {}: {}", param_name, param_type), + format!("const {param_name}: {param_type}"), Applicability::MaybeIncorrect, ); }; @@ -102,7 +102,7 @@ fn generic_arg_mismatch_err( err.span_suggestion( arg.span(), "array type provided where a `usize` was expected, try", - format!("{{ {} }}", snippet), + format!("{{ {snippet} }}"), Applicability::MaybeIncorrect, ); } @@ -130,7 +130,7 @@ fn generic_arg_mismatch_err( } else { (arg.descr(), param.kind.descr()) }; - err.note(format!("{} arguments must be provided before {} arguments", first, last)); + err.note(format!("{first} arguments must be provided before {last} arguments")); if let Some(help) = help { err.help(help); } @@ -304,7 +304,7 @@ pub fn create_args_for_parent_generic_args<'tcx, 'a>( "reorder the arguments: {}: `<{}>`", param_types_present .into_iter() - .map(|ord| format!("{}s", ord)) + .map(|ord| format!("{ord}s")) .collect::>() .join(", then "), ordered_params diff --git a/compiler/rustc_hir_analysis/src/astconv/lint.rs b/compiler/rustc_hir_analysis/src/astconv/lint.rs index ff55174f97a76..1bd1270beaf8e 100644 --- a/compiler/rustc_hir_analysis/src/astconv/lint.rs +++ b/compiler/rustc_hir_analysis/src/astconv/lint.rs @@ -34,9 +34,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let param_name = generics.params.next_type_param_name(None); let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() { - (span, format!(", {}: {}", param_name, impl_trait_name)) + (span, format!(", {param_name}: {impl_trait_name}")) } else { - (generics.span, format!("<{}: {}>", param_name, impl_trait_name)) + (generics.span, format!("<{param_name}: {impl_trait_name}>")) }; diag.multipart_suggestion( format!("alternatively use a blanket \ diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index ecbbfd9253903..3235a9ceba1f0 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -1128,7 +1128,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ty_param_name ) }; - err.span_label(span, format!("ambiguous associated type `{}`", assoc_name)); + err.span_label(span, format!("ambiguous associated type `{assoc_name}`")); let mut where_bounds = vec![]; for bound in bounds { @@ -1407,7 +1407,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { _ => { let reported = if variant_resolution.is_some() { // Variant in type position - let msg = format!("expected type, found variant `{}`", assoc_ident); + let msg = format!("expected type, found variant `{assoc_ident}`"); tcx.sess.span_err(span, msg) } else if qself_ty.is_enum() { let mut err = struct_span_err!( @@ -1438,12 +1438,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } else { err.span_label( assoc_ident.span, - format!("variant not found in `{}`", qself_ty), + format!("variant not found in `{qself_ty}`"), ); } if let Some(sp) = tcx.hir().span_if_local(adt_def.did()) { - err.span_label(sp, format!("variant `{}` not found here", assoc_ident)); + err.span_label(sp, format!("variant `{assoc_ident}` not found here")); } err.emit() @@ -2750,7 +2750,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) | ty::BrEnv => { "an anonymous lifetime".to_string() } - ty::BrNamed(_, name) => format!("lifetime `{}`", name), + ty::BrNamed(_, name) => format!("lifetime `{name}`"), }; let mut err = generate_err(&br_name); diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index e0698a72335f3..f3beaf06d08a8 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -342,7 +342,7 @@ pub(super) fn check_opaque_for_inheriting_lifetimes( err.span_suggestion( span, "consider spelling out the type instead", - name.unwrap_or_else(|| format!("{:?}", ty)), + name.unwrap_or_else(|| format!("{ty:?}")), Applicability::MaybeIncorrect, ); } @@ -626,7 +626,7 @@ fn check_item_type(tcx: TyCtxt<'_>, id: hir::ItemId) { "replace the {} parameters with concrete {}{}", kinds, kinds_pl, - egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(), + egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(), ), ) .emit(); @@ -711,7 +711,7 @@ pub(super) fn check_specialization_validity<'tcx>( } else { tcx.sess.delay_span_bug( DUMMY_SP, - format!("parent item: {:?} not marked as default", parent_impl), + format!("parent item: {parent_impl:?} not marked as default"), ); } } diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 89877280a739e..0a6e2e644eb22 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -1744,7 +1744,7 @@ fn compare_generic_param_kinds<'tcx>( tcx.type_of(param.def_id).instantiate_identity() ) } - Type { .. } => format!("{} type parameter", prefix), + Type { .. } => format!("{prefix} type parameter"), Lifetime { .. } => unreachable!(), }; diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index d5c9840887a6e..e076b1fc68cc2 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -134,7 +134,7 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: DefId) -> hir /// Remember to add all intrinsics here, in `compiler/rustc_codegen_llvm/src/intrinsic.rs`, /// and in `library/core/src/intrinsics.rs`. pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { - let param = |n| Ty::new_param(tcx, n, Symbol::intern(&format!("P{}", n))); + let param = |n| Ty::new_param(tcx, n, Symbol::intern(&format!("P{n}"))); let intrinsic_id = it.owner_id.to_def_id(); let intrinsic_name = tcx.item_name(intrinsic_id); let name_str = intrinsic_name.as_str(); @@ -494,7 +494,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { /// Type-check `extern "platform-intrinsic" { ... }` functions. pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { let param = |n| { - let name = Symbol::intern(&format!("P{}", n)); + let name = Symbol::intern(&format!("P{n}")); Ty::new_param(tcx, n, name) }; diff --git a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs index 8423a9550bac3..b0dd5e5787dc2 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs @@ -211,7 +211,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { // register class is usable at all. if let Some(feature) = feature { if !target_features.contains(feature) { - let msg = format!("`{}` target feature is not enabled", feature); + let msg = format!("`{feature}` target feature is not enabled"); let mut err = self.tcx.sess.struct_span_err(expr.span, msg); err.note(format!( "this is required to use type `{}` with register class `{}`", diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index def7a3a9d8857..4cf3587327d23 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -214,7 +214,7 @@ fn missing_items_err( trait_item, tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity(), ); - let code = format!("{}{}\n{}", padding, snippet, padding); + let code = format!("{padding}{snippet}\n{padding}"); if let Some(span) = tcx.hir().span_if_local(trait_item.def_id) { missing_trait_item_label .push(errors::MissingTraitItemLabel { span, item: trait_item.name }); diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 4e194f1c381cb..cb41040cbaae8 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -472,8 +472,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe let bound = if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" }; err.note(format!( - "{} currently required to ensure that impls have maximum flexibility", - bound + "{bound} currently required to ensure that impls have maximum flexibility" )); err.note( "we are soliciting feedback, see issue #87479 \ @@ -989,7 +988,7 @@ fn check_type_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>, all_sized: b let ty = tcx.erase_regions(ty); if ty.has_infer() { tcx.sess - .delay_span_bug(item.span, format!("inference variables in {:?}", ty)); + .delay_span_bug(item.span, format!("inference variables in {ty:?}")); // Just treat unresolved type expression as if it needs drop. true } else { @@ -1863,8 +1862,7 @@ fn report_bivariance( if matches!(param.kind, hir::GenericParamKind::Type { .. }) && !has_explicit_bounds { err.help(format!( - "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead", - param_name + "if you intended `{param_name}` to be a const parameter, use `const {param_name}: usize` instead" )); } err.emit() diff --git a/compiler/rustc_hir_analysis/src/check_unused.rs b/compiler/rustc_hir_analysis/src/check_unused.rs index d10bc5b34ea90..9ad73eeffc6ae 100644 --- a/compiler/rustc_hir_analysis/src/check_unused.rs +++ b/compiler/rustc_hir_analysis/src/check_unused.rs @@ -36,7 +36,7 @@ fn check_unused_traits(tcx: TyCtxt<'_>, (): ()) { } let (path, _) = item.expect_use(); let msg = if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(path.span) { - format!("unused import: `{}`", snippet) + format!("unused import: `{snippet}`") } else { "unused import".to_owned() }; diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index 3f65adcd36ebd..c930537d4aee8 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -171,8 +171,7 @@ fn visit_implementation_of_dispatch_from_dyn(tcx: TyCtxt<'_>, impl_did: LocalDef create_err(&format!( "the trait `DispatchFromDyn` may only be implemented \ for a coercion between structures with the same \ - definition; expected `{}`, found `{}`", - source_path, target_path, + definition; expected `{source_path}`, found `{target_path}`", )) .emit(); diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs index f5326e50614fd..a94c75f918a90 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs @@ -148,8 +148,7 @@ impl<'tcx> InherentCollect<'tcx> { if let ty::Ref(_, subty, _) = ty.kind() { err.note(format!( "you could also try moving the reference to \ - uses of `{}` (such as `self`) within the implementation", - subty + uses of `{subty}` (such as `self`) within the implementation" )); } err.emit(); diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs index 3bd2931265c73..7205b7a21a823 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs @@ -77,8 +77,8 @@ impl<'tcx> InherentOverlapChecker<'tcx> { "duplicate definitions with name `{}`", ident, ); - err.span_label(span, format!("duplicate definitions for `{}`", ident)); - err.span_label(*former, format!("other definition for `{}`", ident)); + err.span_label(span, format!("duplicate definitions for `{ident}`")); + err.span_label(*former, format!("other definition for `{ident}`")); err.emit(); } @@ -114,11 +114,11 @@ impl<'tcx> InherentOverlapChecker<'tcx> { ); err.span_label( self.tcx.def_span(item1.def_id), - format!("duplicate definitions for `{}`", name), + format!("duplicate definitions for `{name}`"), ); err.span_label( self.tcx.def_span(item2.def_id), - format!("other definition for `{}`", name), + format!("other definition for `{name}`"), ); for cause in &overlap.intercrate_ambiguity_causes { diff --git a/compiler/rustc_hir_analysis/src/coherence/orphan.rs b/compiler/rustc_hir_analysis/src/coherence/orphan.rs index 8d9a6f4d44613..bbdb108c59b63 100644 --- a/compiler/rustc_hir_analysis/src/coherence/orphan.rs +++ b/compiler/rustc_hir_analysis/src/coherence/orphan.rs @@ -412,9 +412,8 @@ fn emit_orphan_check_error<'tcx>( .span_label( sp, format!( - "type parameter `{}` must be covered by another type \ - when it appears before the first local type (`{}`)", - param_ty, local_type + "type parameter `{param_ty}` must be covered by another type \ + when it appears before the first local type (`{local_type}`)" ), ) .note( @@ -441,9 +440,8 @@ fn emit_orphan_check_error<'tcx>( .span_label( sp, format!( - "type parameter `{}` must be used as the type parameter for some \ + "type parameter `{param_ty}` must be used as the type parameter for some \ local type", - param_ty, ), ) .note( @@ -541,17 +539,16 @@ fn lint_auto_trait_impl<'tcx>( let self_descr = tcx.def_descr(self_type_did); match arg { ty::util::NotUniqueParam::DuplicateParam(arg) => { - lint.note(format!("`{}` is mentioned multiple times", arg)); + lint.note(format!("`{arg}` is mentioned multiple times")); } ty::util::NotUniqueParam::NotParam(arg) => { - lint.note(format!("`{}` is not a generic parameter", arg)); + lint.note(format!("`{arg}` is not a generic parameter")); } } lint.span_note( item_span, format!( - "try using the same sequence of generic parameters as the {} definition", - self_descr, + "try using the same sequence of generic parameters as the {self_descr} definition", ), ) }, diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index c160cf2df6e5f..f568b75195198 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -195,9 +195,9 @@ pub(crate) fn placeholder_type_error_diag<'tcx>( sugg.push((arg.span, (*type_name).to_string())); } else if let Some(span) = generics.span_for_param_suggestion() { // Account for bounds, we want `fn foo(_: K)` not `fn foo(_: K)`. - sugg.push((span, format!(", {}", type_name))); + sugg.push((span, format!(", {type_name}"))); } else { - sugg.push((generics.span, format!("<{}>", type_name))); + sugg.push((generics.span, format!("<{type_name}>"))); } } @@ -329,7 +329,7 @@ fn bad_placeholder<'tcx>( mut spans: Vec, kind: &'static str, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - let kind = if kind.ends_with('s') { format!("{}es", kind) } else { format!("{}s", kind) }; + let kind = if kind.ends_with('s') { format!("{kind}es") } else { format!("{kind}s") }; spans.sort(); tcx.sess.create_err(errors::PlaceholderNotAllowedItemSignatures { spans, kind }) @@ -425,10 +425,8 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> { | hir::ItemKind::Union(_, generics) => { let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics); let (lt_sp, sugg) = match generics.params { - [] => (generics.span, format!("<{}>", lt_name)), - [bound, ..] => { - (bound.span.shrink_to_lo(), format!("{}, ", lt_name)) - } + [] => (generics.span, format!("<{lt_name}>")), + [bound, ..] => (bound.span.shrink_to_lo(), format!("{lt_name}, ")), }; mpart_sugg = Some(errors::AssociatedTypeTraitUninferredGenericParamsMultipartSuggestion { fspan: lt_sp, @@ -1027,7 +1025,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { } else { tcx.sess.span_err( meta.span(), - format!("unknown meta item passed to `rustc_deny_explicit_impl` {:?}", meta), + format!("unknown meta item passed to `rustc_deny_explicit_impl` {meta:?}"), ); } } @@ -1505,7 +1503,7 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( .sess .source_map() .span_to_snippet(ast_ty.span) - .map_or_else(|_| String::new(), |s| format!(" `{}`", s)); + .map_or_else(|_| String::new(), |s| format!(" `{s}`")); tcx.sess.emit_err(errors::SIMDFFIHighlyExperimental { span: ast_ty.span, snip }); } }; diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index 5e261f8038726..eb93817e823a3 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -2040,8 +2040,7 @@ fn is_late_bound_map( tcx.sess.delay_span_bug( *span, format!( - "Incorrect generic arg count for alias {:?}", - alias_def + "Incorrect generic arg count for alias {alias_def:?}" ), ); None diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index c39edaa157787..a9ef791077ee5 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -156,7 +156,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { let Some(type_dependent_def) = tables.type_dependent_def_id(parent_node_id) else { return Ty::new_error_with_message(tcx, tcx.def_span(def_id), - format!("unable to find type-dependent def for {:?}", parent_node_id), + format!("unable to find type-dependent def for {parent_node_id:?}"), ); }; let idx = segment @@ -197,14 +197,14 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { } else { return Ty::new_error_with_message(tcx, tcx.def_span(def_id), - format!("unable to find const parent for {} in pat {:?}", hir_id, pat), + format!("unable to find const parent for {hir_id} in pat {pat:?}"), ); } } _ => { return Ty::new_error_with_message(tcx, tcx.def_span(def_id), - format!("unexpected const parent path {:?}", parent_node), + format!("unexpected const parent path {parent_node:?}"), ); } }; @@ -544,7 +544,7 @@ fn infer_placeholder_type<'a>( if let Some(ty) = ty.make_suggestable(tcx, false) { err.span_suggestion( span, - format!("provide a type for the {item}", item = kind), + format!("provide a type for the {kind}"), format!("{colon} {ty}"), Applicability::MachineApplicable, ); diff --git a/compiler/rustc_hir_analysis/src/errors.rs b/compiler/rustc_hir_analysis/src/errors.rs index c2d2e5f7e50f6..0babdf7e5b3e7 100644 --- a/compiler/rustc_hir_analysis/src/errors.rs +++ b/compiler/rustc_hir_analysis/src/errors.rs @@ -216,7 +216,7 @@ impl<'a> IntoDiagnostic<'a> for MissingTypeParams { "parameters", self.missing_type_params .iter() - .map(|n| format!("`{}`", n)) + .map(|n| format!("`{n}`")) .collect::>() .join(", "), ); diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check.rs b/compiler/rustc_hir_analysis/src/impl_wf_check.rs index 62f22bda9f900..4f705eaf10aac 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check.rs @@ -77,8 +77,7 @@ fn enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) tcx.sess.delay_span_bug( tcx.def_span(impl_def_id), format!( - "potentially unconstrained type parameters weren't evaluated: {:?}", - impl_self_ty, + "potentially unconstrained type parameters weren't evaluated: {impl_self_ty:?}", ), ); return; @@ -180,7 +179,7 @@ fn report_unused_parameter(tcx: TyCtxt<'_>, span: Span, kind: &str, name: Symbol kind, name ); - err.span_label(span, format!("unconstrained {} parameter", kind)); + err.span_label(span, format!("unconstrained {kind} parameter")); if kind == "const" { err.note( "expressions using a const parameter must map each value to a distinct output value", diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs index 81993789bcf69..8b2c93d8fd311 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs @@ -294,7 +294,7 @@ fn check_duplicate_params<'tcx>( if let (_, [duplicate, ..]) = base_params.partition_dedup() { let param = impl1_args[duplicate.0 as usize]; tcx.sess - .struct_span_err(span, format!("specializing impl repeats parameter `{}`", param)) + .struct_span_err(span, format!("specializing impl repeats parameter `{param}`")) .emit(); } } @@ -523,7 +523,7 @@ fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tc } _ => { tcx.sess - .struct_span_err(span, format!("cannot specialize on predicate `{}`", predicate)) + .struct_span_err(span, format!("cannot specialize on predicate `{predicate}`")) .emit(); } } diff --git a/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs b/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs index 0828fe9e0f23d..6be8d72aed205 100644 --- a/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs +++ b/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs @@ -474,7 +474,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { verb ) } else { - format!("missing generics for {} `{}`", def_kind, def_path) + format!("missing generics for {def_kind} `{def_path}`") } } @@ -599,7 +599,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { let span = self.path_segment.ident.span; // insert a suggestion of the form "Y<'a, 'b>" - let sugg = format!("<{}>", suggested_args); + let sugg = format!("<{suggested_args}>"); debug!("sugg: {:?}", sugg); err.span_suggestion_verbose( @@ -624,7 +624,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { let sugg_suffix = if is_first && (has_non_lt_args || has_bindings) { ", " } else { "" }; - let sugg = format!("{}{}{}", sugg_prefix, suggested_args, sugg_suffix); + let sugg = format!("{sugg_prefix}{suggested_args}{sugg_suffix}"); debug!("sugg: {:?}", sugg); err.span_suggestion_verbose(sugg_span, msg, sugg, Applicability::HasPlaceholders); @@ -649,7 +649,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { let span = self.path_segment.ident.span; // insert a suggestion of the form "Y" - let sugg = format!("<{}>", suggested_args); + let sugg = format!("<{suggested_args}>"); debug!("sugg: {:?}", sugg); err.span_suggestion_verbose( @@ -682,7 +682,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { let sugg_suffix = if is_first && !self.gen_args.bindings.is_empty() { ", " } else { "" }; - let sugg = format!("{}{}{}", sugg_prefix, suggested_args, sugg_suffix); + let sugg = format!("{sugg_prefix}{suggested_args}{sugg_suffix}"); debug!("sugg: {:?}", sugg); err.span_suggestion_verbose(sugg_span, msg, sugg, Applicability::HasPlaceholders); @@ -1024,7 +1024,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { .collect::>() .join(", "); - format!(": {}", params) + format!(": {params}") }; format!( diff --git a/compiler/rustc_hir_analysis/src/variance/terms.rs b/compiler/rustc_hir_analysis/src/variance/terms.rs index 3b286bb9c93cf..ed03c5da26f00 100644 --- a/compiler/rustc_hir_analysis/src/variance/terms.rs +++ b/compiler/rustc_hir_analysis/src/variance/terms.rs @@ -32,8 +32,8 @@ pub enum VarianceTerm<'a> { impl<'a> fmt::Debug for VarianceTerm<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - ConstantTerm(c1) => write!(f, "{:?}", c1), - TransformTerm(v1, v2) => write!(f, "({:?} \u{00D7} {:?})", v1, v2), + ConstantTerm(c1) => write!(f, "{c1:?}"), + TransformTerm(v1, v2) => write!(f, "({v1:?} \u{00D7} {v2:?})"), InferredTerm(id) => write!(f, "[{}]", { let InferredIndex(i) = id; i diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index a24d1ff077f38..f1affaca3dfe7 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -402,7 +402,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .sess .struct_span_err( callee_expr.span, - format!("evaluate({:?}) = {:?}", predicate, result), + format!("evaluate({predicate:?}) = {result:?}"), ) .span_label(predicate_span, "predicate") .emit(); diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index af8afcc0f0b97..5bc0e2ee86c8c 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -144,7 +144,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let reported = self .tcx .sess - .delay_span_bug(span, format!("`{:?}` should be sized but is not?", t)); + .delay_span_bug(span, format!("`{t:?}` should be sized but is not?")); return Err(reported); } }) @@ -644,12 +644,12 @@ impl<'a, 'tcx> CastCheck<'tcx> { err.span_suggestion( self.cast_span, "try casting to a reference instead", - format!("&{}{}", mtstr, s), + format!("&{mtstr}{s}"), Applicability::MachineApplicable, ); } Err(_) => { - let msg = format!("did you mean `&{}{}`?", mtstr, tstr); + let msg = format!("did you mean `&{mtstr}{tstr}`?"); err.span_help(self.cast_span, msg); } } diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 3b1d9c8905b40..cacfdf52d6f88 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -1793,8 +1793,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { err.span_note( sp, format!( - "return type inferred to be `{}` here", - expected + "return type inferred to be `{expected}` here" ), ); } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 29488c9011a19..4ae8020fc42ff 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -1890,7 +1890,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut truncated_fields_error = String::new(); let remaining_fields_names = match &displayable_field_names[..] { - [field1] => format!("`{}`", field1), + [field1] => format!("`{field1}`"), [field1, field2] => format!("`{field1}` and `{field2}`"), [field1, field2, field3] => format!("`{field1}`, `{field2}` and `{field3}`"), _ => { @@ -2117,16 +2117,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } _ => { - err.span_label(variant_ident_span, format!("`{adt}` defined here", adt = ty)); + err.span_label(variant_ident_span, format!("`{ty}` defined here")); err.span_label(field.ident.span, "field does not exist"); err.span_suggestion_verbose( expr_span, - format!( - "`{adt}` is a tuple {kind_name}, use the appropriate syntax", - adt = ty, - kind_name = kind_name, - ), - format!("{adt}(/* fields */)", adt = ty), + format!("`{ty}` is a tuple {kind_name}, use the appropriate syntax",), + format!("{ty}(/* fields */)"), Applicability::HasPlaceholders, ); } @@ -2243,7 +2239,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // dynamic limit, to never omit just one field let limit = if names.len() == 6 { 6 } else { 5 }; let mut display = - names.iter().take(limit).map(|n| format!("`{}`", n)).collect::>().join(", "); + names.iter().take(limit).map(|n| format!("`{n}`")).collect::>().join(", "); if names.len() > limit { display = format!("{} ... and {} others", display, names.len() - limit); } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index fa1056e724a1f..ecafb50f42094 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -61,7 +61,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind); - let msg = format!("unreachable {}", kind); + let msg = format!("unreachable {kind}"); self.tcx().struct_span_lint_hir( lint::builtin::UNREACHABLE_CODE, id, @@ -134,7 +134,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } pub fn tag(&self) -> String { - format!("{:p}", self) + format!("{self:p}") } pub fn local_ty(&self, span: Span, nid: hir::HirId) -> Ty<'tcx> { @@ -1412,9 +1412,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.tcx.sess.delay_span_bug( span, format!( - "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?", - self_ty, - impl_ty, + "instantiate_value_path: (UFCS) {self_ty:?} was a subtype of {impl_ty:?} but now is not?", ), ); } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index a9610009db1ee..0311251f5c3a0 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -689,7 +689,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); err.span_label( full_call_span, - format!("arguments to this {} are incorrect", call_name), + format!("arguments to this {call_name} are incorrect"), ); } else { err = tcx.sess.struct_span_err_with_code( @@ -796,10 +796,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None, None, ); - err.span_label( - full_call_span, - format!("arguments to this {} are incorrect", call_name), - ); + err.span_label(full_call_span, format!("arguments to this {call_name} are incorrect")); if let hir::ExprKind::MethodCall(_, rcvr, _, _) = call_expr.kind && provided_idx.as_usize() == expected_idx.as_usize() @@ -874,7 +871,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if ty.is_unit() { "()".to_string() } else if ty.is_suggestable(tcx, false) { - format!("/* {} */", ty) + format!("/* {ty} */") } else if let Some(fn_def_id) = fn_def_id && self.tcx.def_kind(fn_def_id).is_fn_like() && let self_implicit = @@ -931,12 +928,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (provided_ty, provided_span) = provided_arg_tys[arg_idx]; let provided_ty_name = if !has_error_or_infer([provided_ty]) { // FIXME: not suggestable, use something else - format!(" of type `{}`", provided_ty) + format!(" of type `{provided_ty}`") } else { "".to_string() }; - labels - .push((provided_span, format!("unexpected argument{}", provided_ty_name))); + labels.push((provided_span, format!("unexpected argument{provided_ty_name}"))); let mut span = provided_span; if span.can_be_used_for_suggestions() { if arg_idx.index() > 0 @@ -1009,11 +1005,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { args_span }; let rendered = if !has_error_or_infer([input_ty]) { - format!(" of type `{}`", input_ty) + format!(" of type `{input_ty}`") } else { "".to_string() }; - labels.push((span, format!("an argument{} is missing", rendered))); + labels.push((span, format!("an argument{rendered} is missing"))); suggestion_text = match suggestion_text { SuggestionText::None => SuggestionText::Provide(false), SuggestionText::Provide(_) => SuggestionText::Provide(true), @@ -1034,13 +1030,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let rendered = if !has_error_or_infer([first_expected_ty, second_expected_ty]) { format!( - " of type `{}` and `{}`", - first_expected_ty, second_expected_ty + " of type `{first_expected_ty}` and `{second_expected_ty}`" ) } else { "".to_string() }; - labels.push((span, format!("two arguments{} are missing", rendered))); + labels.push((span, format!("two arguments{rendered} are missing"))); suggestion_text = match suggestion_text { SuggestionText::None | SuggestionText::Provide(_) => { SuggestionText::Provide(true) @@ -1066,13 +1061,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { third_expected_ty, ]) { format!( - " of type `{}`, `{}`, and `{}`", - first_expected_ty, second_expected_ty, third_expected_ty + " of type `{first_expected_ty}`, `{second_expected_ty}`, and `{third_expected_ty}`" ) } else { "".to_string() }; - labels.push((span, format!("three arguments{} are missing", rendered))); + labels.push((span, format!("three arguments{rendered} are missing"))); suggestion_text = match suggestion_text { SuggestionText::None | SuggestionText::Provide(_) => { SuggestionText::Provide(true) @@ -1113,25 +1107,25 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (first_provided_ty, first_span) = provided_arg_tys[first_provided_idx]; let (_, first_expected_ty) = formal_and_expected_inputs[first_expected_idx]; let first_provided_ty_name = if !has_error_or_infer([first_provided_ty]) { - format!(", found `{}`", first_provided_ty) + format!(", found `{first_provided_ty}`") } else { String::new() }; labels.push(( first_span, - format!("expected `{}`{}", first_expected_ty, first_provided_ty_name), + format!("expected `{first_expected_ty}`{first_provided_ty_name}"), )); let (second_provided_ty, second_span) = provided_arg_tys[second_provided_idx]; let (_, second_expected_ty) = formal_and_expected_inputs[second_expected_idx]; let second_provided_ty_name = if !has_error_or_infer([second_provided_ty]) { - format!(", found `{}`", second_provided_ty) + format!(", found `{second_provided_ty}`") } else { String::new() }; labels.push(( second_span, - format!("expected `{}`{}", second_expected_ty, second_provided_ty_name), + format!("expected `{second_expected_ty}`{second_provided_ty_name}"), )); suggestion_text = match suggestion_text { @@ -1144,13 +1138,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (_, expected_ty) = formal_and_expected_inputs[dst_arg]; let (provided_ty, provided_span) = provided_arg_tys[dest_input]; let provided_ty_name = if !has_error_or_infer([provided_ty]) { - format!(", found `{}`", provided_ty) + format!(", found `{provided_ty}`") } else { String::new() }; labels.push(( provided_span, - format!("expected `{}`{}", expected_ty, provided_ty_name), + format!("expected `{expected_ty}`{provided_ty_name}"), )); } @@ -2031,7 +2025,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { ("closure", self.tcx.def_span(def_id)) }; - err.span_note(span, format!("{} defined here", kind)); + err.span_note(span, format!("{kind} defined here")); } else { err.span_note( self.tcx.def_span(def_id), diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index ec19d017c259b..8bbb714541e45 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -397,7 +397,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let struct_pat_shorthand_field = self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr); if let Some(name) = struct_pat_shorthand_field { - sugg.insert(0, (expr.span.shrink_to_lo(), format!("{}: ", name))); + sugg.insert(0, (expr.span.shrink_to_lo(), format!("{name}: "))); } Some(sugg) }) @@ -558,7 +558,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .take(4) .map(|(var_hir_id, upvar)| { let var_name = self.tcx.hir().name(*var_hir_id).to_string(); - let msg = format!("`{}` captured here", var_name); + let msg = format!("`{var_name}` captured here"); (upvar.span, msg) }) .collect::>(); @@ -931,7 +931,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.span_suggestion( fn_return.span(), "consider using an impl return type", - format!("impl {}", all_bounds_str), + format!("impl {all_bounds_str}"), Applicability::MaybeIncorrect, ); } @@ -1070,7 +1070,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .must_apply_modulo_regions() { let suggestion = match self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { - Some(ident) => format!(": {}.clone()", ident), + Some(ident) => format!(": {ident}.clone()"), None => ".clone()".to_string() }; @@ -1248,7 +1248,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let suggestion = match self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { - Some(ident) => format!(": {}.is_some()", ident), + Some(ident) => format!(": {ident}.is_some()"), None => ".is_some()".to_string(), }; diff --git a/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/mod.rs b/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/mod.rs index e01dcf83a3805..e563bd40b6542 100644 --- a/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/mod.rs +++ b/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/mod.rs @@ -125,8 +125,8 @@ impl Debug for TrackedValue { write!(f, "{}", tcx.hir().node_to_string(self.hir_id())) } else { match self { - Self::Variable(hir_id) => write!(f, "Variable({:?})", hir_id), - Self::Temporary(hir_id) => write!(f, "Temporary({:?})", hir_id), + Self::Variable(hir_id) => write!(f, "Variable({hir_id:?})"), + Self::Temporary(hir_id) => write!(f, "Temporary({hir_id:?})"), } } }) diff --git a/compiler/rustc_hir_typeck/src/generator_interior/mod.rs b/compiler/rustc_hir_typeck/src/generator_interior/mod.rs index 86ea092bc4073..6a8171224913b 100644 --- a/compiler/rustc_hir_typeck/src/generator_interior/mod.rs +++ b/compiler/rustc_hir_typeck/src/generator_interior/mod.rs @@ -112,7 +112,7 @@ impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> { self.fcx .tcx .sess - .delay_span_bug(span, format!("Encountered var {:?}", unresolved_term)); + .delay_span_bug(span, format!("Encountered var {unresolved_term:?}")); } else { let note = format!( "the type is part of the {} because of this {}", diff --git a/compiler/rustc_hir_typeck/src/intrinsicck.rs b/compiler/rustc_hir_typeck/src/intrinsicck.rs index 2d85451c9e185..2cd18c4c3fcb4 100644 --- a/compiler/rustc_hir_typeck/src/intrinsicck.rs +++ b/compiler/rustc_hir_typeck/src/intrinsicck.rs @@ -85,7 +85,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ok(SizeSkeleton::Pointer { tail, .. }) => format!("pointer to `{tail}`"), Ok(SizeSkeleton::Known(size)) => { if let Some(v) = u128::from(size.bytes()).checked_mul(8) { - format!("{} bits", v) + format!("{v} bits") } else { // `u128` should definitely be able to hold the size of different architectures // larger sizes should be reported as error `are too big for the current architecture` diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 6835782b5bd8f..7c73f6a89cdb2 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -225,7 +225,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { assert!(mutbl.is_mut()); Ty::new_ptr(self.tcx, ty::TypeAndMut { mutbl: hir::Mutability::Not, ty }) } - other => panic!("Cannot adjust receiver type {:?} to const ptr", other), + other => panic!("Cannot adjust receiver type {other:?} to const ptr"), }; adjustments.push(Adjustment { @@ -262,8 +262,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { let impl_def_id = pick.item.container_id(self.tcx); assert!( self.tcx.impl_trait_ref(impl_def_id).is_none(), - "impl {:?} is not an inherent impl", - impl_def_id + "impl {impl_def_id:?} is not an inherent impl" ); self.fresh_args_for_item(self.span, impl_def_id) } diff --git a/compiler/rustc_hir_typeck/src/method/prelude2021.rs b/compiler/rustc_hir_typeck/src/method/prelude2021.rs index 4efe95c4dc560..5b19a4c525f8d 100644 --- a/compiler/rustc_hir_typeck/src/method/prelude2021.rs +++ b/compiler/rustc_hir_typeck/src/method/prelude2021.rs @@ -97,28 +97,28 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) = pick.autoref_or_ptr_adjustment { - format!("{}{} as *const _", derefs, self_expr) + format!("{derefs}{self_expr} as *const _") } else { - format!("{}{}{}", autoref, derefs, self_expr) + format!("{autoref}{derefs}{self_expr}") }; lint.span_suggestion( sp, "disambiguate the method call", - format!("({})", self_adjusted), + format!("({self_adjusted})"), Applicability::MachineApplicable, ); } else { let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) = pick.autoref_or_ptr_adjustment { - format!("{}(...) as *const _", derefs) + format!("{derefs}(...) as *const _") } else { - format!("{}{}...", autoref, derefs) + format!("{autoref}{derefs}...") }; lint.span_help( sp, - format!("disambiguate the method call with `({})`", self_adjusted,), + format!("disambiguate the method call with `({self_adjusted})`",), ); } @@ -168,7 +168,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .ok()) { // Keep turbofish. - format!("::{}", args) + format!("::{args}") } else { String::new() }, @@ -347,7 +347,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Glob import, so just use its name. return None; } else { - return Some(format!("{}", any_id)); + return Some(format!("{any_id}")); } } @@ -396,9 +396,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let adjusted_text = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) = pick.autoref_or_ptr_adjustment { - format!("{}{} as *const _", derefs, expr_text) + format!("{derefs}{expr_text} as *const _") } else { - format!("{}{}{}", autoref, derefs, expr_text) + format!("{autoref}{derefs}{expr_text}") }; (adjusted_text, precise) diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 3d7187cb16f3d..f6c07931023e3 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -153,7 +153,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { E0034, "multiple applicable items in scope" ); - err.span_label(item_name.span, format!("multiple `{}` found", item_name)); + err.span_label(item_name.span, format!("multiple `{item_name}` found")); self.note_candidates_on_method_error( rcvr_ty, @@ -177,13 +177,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { kind, item_name ); - err.span_label(item_name.span, format!("private {}", kind)); + err.span_label(item_name.span, format!("private {kind}")); let sp = self .tcx .hir() .span_if_local(def_id) .unwrap_or_else(|| self.tcx.def_span(def_id)); - err.span_label(sp, format!("private {} defined here", kind)); + err.span_label(sp, format!("private {kind} defined here")); self.suggest_valid_traits(&mut err, out_of_scope_traits); err.emit(); } @@ -218,7 +218,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { *region, ty::TypeAndMut { ty: *t_type, mutbl: mutability.invert() }, ); - let msg = format!("you need `{}` instead of `{}`", trait_type, rcvr_ty); + let msg = format!("you need `{trait_type}` instead of `{rcvr_ty}`"); let mut kind = &self_expr.kind; while let hir::ExprKind::AddrOf(_, _, expr) | hir::ExprKind::Unary(hir::UnOp::Deref, expr) = kind @@ -637,7 +637,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } // Point at the closure that couldn't satisfy the bound. ty::Closure(def_id, _) => bound_spans - .push((tcx.def_span(*def_id), format!("doesn't satisfy `{}`", quiet))), + .push((tcx.def_span(*def_id), format!("doesn't satisfy `{quiet}`"))), _ => {} } }; @@ -659,7 +659,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let term = pred.skip_binder().term; - let obligation = format!("{} = {}", projection_ty, term); + let obligation = format!("{projection_ty} = {term}"); let quiet = with_forced_trimmed_paths!(format!( "{} = {}", quiet_projection_ty, term @@ -672,7 +672,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let p = poly_trait_ref.trait_ref; let self_ty = p.self_ty(); let path = p.print_only_trait_path(); - let obligation = format!("{}: {}", self_ty, path); + let obligation = format!("{self_ty}: {path}"); let quiet = with_forced_trimmed_paths!(format!("_: {}", path)); bound_span_label(self_ty, &obligation, &quiet); Some((obligation, self_ty)) @@ -825,12 +825,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut preds: Vec<_> = predicates .iter() .filter_map(|pred| format_pred(**pred)) - .map(|(p, _)| format!("`{}`", p)) + .map(|(p, _)| format!("`{p}`")) .collect(); preds.sort(); preds.dedup(); let msg = if let [pred] = &preds[..] { - format!("trait bound {} was not satisfied", pred) + format!("trait bound {pred} was not satisfied") } else { format!("the following trait bounds were not satisfied:\n{}", preds.join("\n"),) }; @@ -875,7 +875,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { suggested_bounds.insert(pred); } } - format!("`{}`\nwhich is required by `{}`", p, parent_p) + format!("`{p}`\nwhich is required by `{parent_p}`") } }, }, @@ -1034,8 +1034,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { "".to_string() }; err.note(format!( - "the {item_kind} was found for\n{}{}", - type_candidates, additional_types + "the {item_kind} was found for\n{type_candidates}{additional_types}" )); } else { 'outer: for inherent_impl_did in self.tcx.inherent_impls(adt.did()) { @@ -1249,8 +1248,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { ( format!( - "the candidate is defined in an impl{} for the type `{}`", - insertion, impl_ty, + "the candidate is defined in an impl{insertion} for the type `{impl_ty}`", ), None, ) @@ -1452,11 +1450,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.span_suggestion( sugg_span, "use associated function syntax instead", - format!("{}::{}{}", ty_str, item_name, args), + format!("{ty_str}::{item_name}{args}"), applicability, ); } else { - err.help(format!("try with `{}::{}`", ty_str, item_name,)); + err.help(format!("try with `{ty_str}::{item_name}`",)); } } @@ -1491,9 +1489,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let expr_span = expr.span.to(item_name.span); err.multipart_suggestion( format!( - "to call the function stored in `{}`, \ + "to call the function stored in `{item_name}`, \ surround the field access with parentheses", - item_name, ), vec![ (expr_span.shrink_to_lo(), '('.to_string()), @@ -1516,7 +1513,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let field_kind = if is_accessible { "field" } else { "private field" }; - err.span_label(item_name.span, format!("{}, not a method", field_kind)); + err.span_label(item_name.span, format!("{field_kind}, not a method")); return true; } false @@ -1669,8 +1666,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { lit.span, format!( "you must specify a concrete type for this numeric value, \ - like `{}`", - concrete_type + like `{concrete_type}`" ), format!("{snippet}_{concrete_type}"), Applicability::MaybeIncorrect, @@ -1685,8 +1681,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let parent_node = self.tcx.hir().get_parent(hir_id); let msg = format!( - "you must specify a type for this binding, like `{}`", - concrete_type, + "you must specify a type for this binding, like `{concrete_type}`", ); match (filename, parent_node) { @@ -2194,7 +2189,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some((last_self_name, _, ref mut last_trait_names)) = derives_grouped.last_mut() { if last_self_name == &self_name { - last_trait_names.push_str(format!(", {}", trait_name).as_str()); + last_trait_names.push_str(format!(", {trait_name}").as_str()); continue; } } @@ -2226,8 +2221,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for (self_name, self_span, traits) in &derives_grouped { err.span_suggestion_verbose( self_span.shrink_to_lo(), - format!("consider annotating `{}` with `#[derive({})]`", self_name, traits), - format!("#[derive({})]\n", traits), + format!("consider annotating `{self_name}` with `#[derive({traits})]`"), + format!("#[derive({traits})]\n"), Applicability::MaybeIncorrect, ); } @@ -2475,7 +2470,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if pick.autoderefs == 0 && !skip { err.span_label( pick.item.ident(self.tcx).span, - format!("the method is available for `{}` here", rcvr_ty), + format!("the method is available for `{rcvr_ty}` here"), ); } break; @@ -2521,13 +2516,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if pick.autoderefs == 0 && !skip { err.span_label( pick.item.ident(self.tcx).span, - format!("the method is available for `{}` here", new_rcvr_t), + format!("the method is available for `{new_rcvr_t}` here"), ); err.multipart_suggestion( "consider wrapping the receiver expression with the \ appropriate type", vec![ - (rcvr.span.shrink_to_lo(), format!("{}({}", pre, post)), + (rcvr.span.shrink_to_lo(), format!("{pre}({post}")), (rcvr.span.shrink_to_hi(), ")".to_string()), ], Applicability::MaybeIncorrect, @@ -2767,7 +2762,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; err.span_suggestions( sp, - message(format!("add {} supertrait for", article)), + message(format!("add {article} supertrait for")), candidates.iter().map(|t| { format!("{} {}", sep, self.tcx.def_path_str(t.def_id),) }), @@ -2836,7 +2831,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { trait_infos => { let mut msg = message(param_type.map_or_else( || "implement".to_string(), // FIXME: it might only need to be imported into scope, not implemented. - |param| format!("restrict type parameter `{}` with", param), + |param| format!("restrict type parameter `{param}` with"), )); for (i, trait_info) in trait_infos.iter().enumerate() { msg.push_str(&format!( @@ -2860,8 +2855,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } trait_infos => { let mut msg = format!( - "the following traits define an item `{}`, but are explicitly unimplemented:", - item_name + "the following traits define an item `{item_name}`, but are explicitly unimplemented:" ); for trait_info in trait_infos { msg.push_str(&format!("\n{}", self.tcx.def_path_str(trait_info.def_id))); @@ -3027,13 +3021,13 @@ fn print_disambiguation_help<'tcx>( .join(", "), ); let trait_name = if !fn_has_self_parameter { - format!("<{} as {}>", rcvr_ty, trait_name) + format!("<{rcvr_ty} as {trait_name}>") } else { trait_name }; - (span, format!("{}::{}{}", trait_name, item_name, args)) + (span, format!("{trait_name}::{item_name}{args}")) } else { - (span.with_hi(item_name.span.lo()), format!("<{} as {}>::", rcvr_ty, trait_name)) + (span.with_hi(item_name.span.lo()), format!("<{rcvr_ty} as {trait_name}>::")) }; err.span_suggestion_verbose( span, @@ -3041,7 +3035,7 @@ fn print_disambiguation_help<'tcx>( "disambiguate the {} for {}", def_kind_descr, if let Some(candidate) = candidate { - format!("candidate #{}", candidate) + format!("candidate #{candidate}") } else { "the candidate".to_string() }, diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 8bf95d4bf9a6c..6ffa3b0a0b34b 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -516,7 +516,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn endpoint_has_type(&self, err: &mut Diagnostic, span: Span, ty: Ty<'_>) { if !ty.references_error() { - err.span_label(span, format!("this is of type `{}`", ty)); + err.span_label(span, format!("this is of type `{ty}`")); } } @@ -540,7 +540,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); let msg = |ty| { let ty = self.resolve_vars_if_possible(ty); - format!("this is of type `{}` but it should be `char` or numeric", ty) + format!("this is of type `{ty}` but it should be `char` or numeric") }; let mut one_side_err = |first_span, first_ty, second: Option<(bool, Ty<'tcx>, Span)>| { err.span_label(first_span, msg(first_ty)); @@ -653,7 +653,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) }); let pre = if in_match { "in the same arm, " } else { "" }; - err.note(format!("{}a binding must have the same type in all alternatives", pre)); + err.note(format!("{pre}a binding must have the same type in all alternatives")); self.suggest_adding_missing_ref_or_removing_ref( &mut err, span, @@ -1710,7 +1710,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.span_suggestion_verbose( qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()), "use the tuple variant pattern syntax instead", - format!("({})", sugg), + format!("({sugg})"), appl, ); return Some(err); @@ -1812,7 +1812,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { const LIMIT: usize = 3; match witnesses { [] => bug!(), - [witness] => format!("`{}`", witness), + [witness] => format!("`{witness}`"), [head @ .., tail] if head.len() < LIMIT => { let head: Vec<_> = head.iter().map(<_>::to_string).collect(); format!("`{}` and `{}`", head.join("`, `"), tail) @@ -1834,8 +1834,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { "ensure that all fields are mentioned explicitly by adding the suggested fields", ); lint.note(format!( - "the pattern is of type `{}` and the `non_exhaustive_omitted_patterns` attribute was found", - ty, + "the pattern is of type `{ty}` and the `non_exhaustive_omitted_patterns` attribute was found", )); lint @@ -1864,10 +1863,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { let fields = unmentioned_fields .iter() - .map(|(_, name)| format!("`{}`", name)) + .map(|(_, name)| format!("`{name}`")) .collect::>() .join(", "); - format!("fields {}{}", fields, inaccessible) + format!("fields {fields}{inaccessible}") }; let mut err = struct_span_err!( self.tcx.sess, @@ -1876,7 +1875,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { "pattern does not mention {}", field_names ); - err.span_label(pat.span, format!("missing {}", field_names)); + err.span_label(pat.span, format!("missing {field_names}")); let len = unmentioned_fields.len(); let (prefix, postfix, sp) = match fields { [] => match &pat.kind { @@ -1909,11 +1908,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .iter() .map(|(_, name)| { let field_name = name.to_string(); - if is_number(&field_name) { - format!("{}: _", field_name) - } else { - field_name - } + if is_number(&field_name) { format!("{field_name}: _") } else { field_name } }) .collect::>() .join(", "), @@ -1930,7 +1925,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { s = pluralize!(len), them = if len == 1 { "it" } else { "them" }, ), - format!("{}..{}", prefix, postfix), + format!("{prefix}..{postfix}"), Applicability::MachineApplicable, ); err diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 22fe823acb768..be939560c459d 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -109,11 +109,11 @@ impl MigrationWarningReason { fn migration_message(&self) -> String { let base = "changes to closure capture in Rust 2021 will affect"; if !self.auto_traits.is_empty() && self.drop_order { - format!("{} drop order and which traits the closure implements", base) + format!("{base} drop order and which traits the closure implements") } else if self.drop_order { - format!("{} drop order", base) + format!("{base} drop order") } else { - format!("{} which traits the closure implements", base) + format!("{base} which traits the closure implements") } } } @@ -824,8 +824,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { lint.note("for more information, see "); let diagnostic_msg = format!( - "add a dummy let to cause {} to be fully captured", - migrated_variables_concat + "add a dummy let to cause {migrated_variables_concat} to be fully captured" ); let closure_span = self.tcx.hir().span_with_body(closure_hir_id); @@ -1943,7 +1942,7 @@ fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String let mut projections_str = String::new(); for (i, item) in place.projections.iter().enumerate() { let proj = match item.kind { - ProjectionKind::Field(a, b) => format!("({:?}, {:?})", a, b), + ProjectionKind::Field(a, b) => format!("({a:?}, {b:?})"), ProjectionKind::Deref => String::from("Deref"), ProjectionKind::Index => String::from("Index"), ProjectionKind::Subslice => String::from("Subslice"), @@ -1966,7 +1965,7 @@ fn construct_capture_kind_reason_string<'tcx>( let capture_kind_str = match capture_info.capture_kind { ty::UpvarCapture::ByValue => "ByValue".into(), - ty::UpvarCapture::ByRef(kind) => format!("{:?}", kind), + ty::UpvarCapture::ByRef(kind) => format!("{kind:?}"), }; format!("{place_str} captured as {capture_kind_str} here") @@ -1987,7 +1986,7 @@ fn construct_capture_info_string<'tcx>( let capture_kind_str = match capture_info.capture_kind { ty::UpvarCapture::ByValue => "ByValue".into(), - ty::UpvarCapture::ByRef(kind) => format!("{:?}", kind), + ty::UpvarCapture::ByRef(kind) => format!("{kind:?}"), }; format!("{place_str} -> {capture_kind_str}") } diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index 2329a1f63ceca..6f47623ec43db 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -217,7 +217,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { // When encountering `return [0][0]` outside of a `fn` body we can encounter a base // that isn't in the type table. We assume more relevant errors have already been // emitted, so we delay an ICE if none have. (#64638) - self.tcx().sess.delay_span_bug(e.span, format!("bad base: `{:?}`", base)); + self.tcx().sess.delay_span_bug(e.span, format!("bad base: `{base:?}`")); } if let Some(base_ty) = base_ty && let ty::Ref(_, base_ty_inner, _) = *base_ty.kind() @@ -231,7 +231,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { Ty::new_error_with_message( self.fcx.tcx, e.span, - format!("bad index {:?} for base: `{:?}`", index, base), + format!("bad index {index:?} for base: `{base:?}`"), ) }); if self.is_builtin_index(e, base_ty_inner, index_ty) { @@ -488,10 +488,8 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { let span = self.tcx().hir().span(hir_id); // We need to buffer the errors in order to guarantee a consistent // order when emitting them. - let err = self - .tcx() - .sess - .struct_span_err(span, format!("user args: {:?}", user_args)); + let err = + self.tcx().sess.struct_span_err(span, format!("user args: {user_args:?}")); err.buffer(&mut errors_buffer); } } diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index 52a84b204d00b..5e7ae3ecdb85d 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -241,16 +241,16 @@ fn dump_graph(query: &DepGraphQuery) { { // 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()); for (source, target) in &edges { - write!(file, "{:?} -> {:?}\n", source, target).unwrap(); + write!(file, "{source:?} -> {target:?}\n").unwrap(); } } { // dump a .dot file in graphviz format: - let dot_path = format!("{}.dot", path); + let dot_path = format!("{path}.dot"); let mut v = Vec::new(); dot::render(&GraphvizDepGraph(nodes, edges), &mut v).unwrap(); fs::write(dot_path, v).unwrap(); @@ -285,7 +285,7 @@ impl<'a> dot::Labeller<'a> for GraphvizDepGraph { dot::Id::new("DependencyGraph").unwrap() } fn node_id(&self, n: &DepKind) -> dot::Id<'_> { - let s: String = format!("{:?}", n) + let s: String = format!("{n:?}") .chars() .map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' }) .collect(); @@ -293,7 +293,7 @@ impl<'a> dot::Labeller<'a> for GraphvizDepGraph { dot::Id::new(s).unwrap() } fn node_label(&self, n: &DepKind) -> dot::LabelText<'_> { - dot::LabelText::label(format!("{:?}", n)) + dot::LabelText::label(format!("{n:?}")) } } diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index f9cd01fd80dbb..5dd06c6ca4f40 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -300,7 +300,7 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { }, _ => self.tcx.sess.emit_fatal(errors::UndefinedCleanDirty { span: attr.span, - kind: format!("{:?}", node), + kind: format!("{node:?}"), }), }; let labels = diff --git a/compiler/rustc_incremental/src/persist/fs.rs b/compiler/rustc_incremental/src/persist/fs.rs index 929a1e149b6ad..1111a1a17e29b 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -427,13 +427,11 @@ fn copy_files(sess: &Session, target_dir: &Path, source_dir: &Path) -> Result SourceKindMultiSuggestion<'a> { _ => ("", ""), }; let (start_span, start_span_code, end_span) = match should_wrap_expr { - Some(end_span) => { - (data.span(), format!("{}{}{}{{ ", arrow, ty_info, post), Some(end_span)) - } - None => (data.span(), format!("{}{}{}", arrow, ty_info, post), None), + Some(end_span) => (data.span(), format!("{arrow}{ty_info}{post}{{ "), Some(end_span)), + None => (data.span(), format!("{arrow}{ty_info}{post}"), None), }; Self::ClosureReturn { start_span, start_span_code, end_span } } @@ -404,9 +402,9 @@ impl AddToDiagnostic for AddLifetimeParamsSuggestion<'_> { debug!(?lifetime_sub.ident.span); let make_suggestion = |ident: Ident| { 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() { - format!("{} ", suggestion_param_name) + format!("{suggestion_param_name} ") } else { suggestion_param_name.clone() }; @@ -419,9 +417,9 @@ impl AddToDiagnostic for AddLifetimeParamsSuggestion<'_> { let new_param_suggestion = if let Some(first) = 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 { - (generics.span, format!("<{}>", suggestion_param_name)) + (generics.span, format!("<{suggestion_param_name}>")) }; suggestions.push(new_param_suggestion); @@ -1320,7 +1318,7 @@ impl AddToDiagnostic for SuggestTuplePatternMany { message, self.compatible_variants.into_iter().map(|variant| { 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()), ] }), diff --git a/compiler/rustc_infer/src/errors/note_and_explain.rs b/compiler/rustc_infer/src/errors/note_and_explain.rs index 7328241dfbcaf..bd168f047faf5 100644 --- a/compiler/rustc_infer/src/errors/note_and_explain.rs +++ b/compiler/rustc_infer/src/errors/note_and_explain.rs @@ -80,7 +80,7 @@ impl<'a> DescriptionCtx<'a> { // We shouldn't really be having unification failures with ReVar // and ReLateBound though. ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => { - (alt_span, "revar", format!("{:?}", region)) + (alt_span, "revar", format!("{region:?}")) } }; Some(DescriptionCtx { span, kind, arg }) diff --git a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs index 1fd5d2adf8098..54d901f20da9d 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -205,7 +205,7 @@ impl CanonicalizeMode for CanonicalizeQueryResponse { // `delay_span_bug` to allow type error over an ICE. canonicalizer.tcx.sess.delay_span_bug( rustc_span::DUMMY_SP, - format!("unexpected region in query response: `{:?}`", r), + format!("unexpected region in query response: `{r:?}`"), ); r } diff --git a/compiler/rustc_infer/src/infer/combine.rs b/compiler/rustc_infer/src/infer/combine.rs index 38f8ad744a6ad..ddc8e7e50eb48 100644 --- a/compiler/rustc_infer/src/infer/combine.rs +++ b/compiler/rustc_infer/src/infer/combine.rs @@ -177,7 +177,7 @@ impl<'tcx> InferCtxt<'tcx> { self.tcx.check_tys_might_be_eq(canonical).map_err(|_| { self.tcx.sess.delay_span_bug( DUMMY_SP, - format!("cannot relate consts of different types (a={:?}, b={:?})", a, b,), + format!("cannot relate consts of different types (a={a:?}, b={b:?})",), ) }) }); diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index d3978e242a854..51c033793d3d3 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -238,7 +238,7 @@ fn msg_span_from_named_region<'tcx>( let text = if name == kw::UnderscoreLifetime { "the anonymous lifetime as defined here".to_string() } else { - format!("the lifetime `{}` as defined here", name) + format!("the lifetime `{name}` as defined here") }; (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)), ), } @@ -280,7 +280,7 @@ fn emit_msg_span( span: Option, suffix: &str, ) { - let message = format!("{}{}{}", prefix, description, suffix); + let message = format!("{prefix}{description}{suffix}"); if let Some(span) = span { err.span_note(span, message); @@ -296,7 +296,7 @@ fn label_msg_span( span: Option, suffix: &str, ) { - let message = format!("{}{}{}", prefix, description, suffix); + let message = format!("{prefix}{description}{suffix}"); if let Some(span) = span { err.span_label(span, message); @@ -333,7 +333,7 @@ pub fn unexpected_hidden_region_diagnostic<'tcx>( explain_free_region( tcx, &mut err, - &format!("hidden type `{}` captures ", hidden_ty), + &format!("hidden type `{hidden_ty}` captures "), hidden_region, "", ); @@ -345,7 +345,7 @@ pub fn unexpected_hidden_region_diagnostic<'tcx>( fn_returns, hidden_region.to_string(), None, - format!("captures `{}`", hidden_region), + format!("captures `{hidden_region}`"), None, Some(reg_info.def_id), ) @@ -373,7 +373,7 @@ pub fn unexpected_hidden_region_diagnostic<'tcx>( note_and_explain_region( tcx, &mut err, - &format!("hidden type `{}` captures ", hidden_ty), + &format!("hidden type `{hidden_ty}` captures "), hidden_region, "", 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))); } 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 @@ -726,7 +726,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { err.span_suggestion( span, "consider dereferencing the boxed value", - format!("*{}", snippet), + format!("*{snippet}"), Applicability::MachineApplicable, ); } @@ -785,13 +785,13 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { if prior_arms.len() <= 4 { for sp in prior_arms { 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() { any_multiline_arm |= source_map.is_multiline(*sp); err.span_label( *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) { @@ -1661,7 +1661,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { .. })) = values { - Cow::from(format!("expected this to be `{}`", expected)) + Cow::from(format!("expected this to be `{expected}`")) } else { terr.to_string(self.tcx) }; @@ -2368,13 +2368,13 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } 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) { 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::Opaque => format!("the opaque type `{}`", p), + ty::AliasKind::Weak => format!("the type alias `{p}`"), + ty::AliasKind::Opaque => format!("the opaque type `{p}`"), }, }; @@ -2388,7 +2388,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { span, impl_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"; if let Some((sp, has_lifetimes)) = type_param_span { let suggestion = - if has_lifetimes { format!(" + {}", sub) } else { format!(": {}", sub) }; + if has_lifetimes { format!(" + {sub}") } else { format!(": {sub}") }; let mut suggestions = vec![(sp, suggestion)]; for add_lt_sugg in add_lt_suggs.into_iter().flatten() { suggestions.push(add_lt_sugg); @@ -2413,7 +2413,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { Applicability::MaybeIncorrect, // Issue #41966 ); } else { - let consider = format!("{} `{}: {}`...", msg, bound_kind, sub); + let consider = format!("{msg} `{bound_kind}: {sub}`..."); err.help(consider); } } @@ -2422,13 +2422,10 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { |err: &mut Diagnostic, type_param_span: Option<(Span, bool)>| { let msg = "consider introducing an explicit lifetime bound"; if let Some((sp, has_lifetimes)) = type_param_span { - let suggestion = if has_lifetimes { - format!(" + {}", new_lt) - } else { - format!(": {}", new_lt) - }; + let suggestion = + if has_lifetimes { format!(" + {new_lt}") } else { format!(": {new_lt}") }; 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() { sugg.push(lt); sugg.rotate_right(1); @@ -2508,7 +2505,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { "{} may not live long enough", 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,); err.span_suggestion( generics.tail_span_for_predicate_suggestion(), @@ -2564,7 +2561,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { note_and_explain_region( self.tcx, &mut err, - &format!("{} must be valid for ", labeled_user_string), + &format!("{labeled_user_string} must be valid for "), sub, "...", None, @@ -2814,10 +2811,10 @@ impl<'tcx> InferCtxt<'tcx> { br_string(br), 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, _) => { 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"), }; diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index 36b56fe782c32..9dfa45858a79b 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -246,7 +246,7 @@ fn closure_as_fn_str<'tcx>(infcx: &InferCtxt<'tcx>, ty: Ty<'tcx>) -> String { } else { format!(" -> {}", ty_to_string(infcx, fn_sig.output().skip_binder(), None)) }; - format!("fn({}){}", args, ret) + format!("fn({args}){ret}") } impl<'tcx> InferCtxt<'tcx> { diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs index 40dc649761138..d08b6ba5e47d9 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -235,10 +235,10 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { } 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(), }; - let captures = format!("captures data from {}", arg); + let captures = format!("captures data from {arg}"); suggest_new_region_bound( tcx, &mut err, @@ -269,11 +269,11 @@ pub fn suggest_new_region_bound( // FIXME: account for the need of parens in `&(dyn Trait + '_)` let consider = "consider changing"; 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 = - 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 plus_lt = format!(" + {}", lifetime_name); + let plus_lt = format!(" + {lifetime_name}"); for fn_return in fn_returns { if fn_return.span.desugaring_kind().is_some() { // Skip `async` desugaring `impl Future`. @@ -383,12 +383,7 @@ pub fn suggest_new_region_bound( if let LifetimeName::ImplicitObjectLifetimeDefault = lt.res { err.span_suggestion_verbose( fn_return.span.shrink_to_hi(), - format!( - "{declare} the trait object {captures}, {explicit}", - declare = declare, - captures = captures, - explicit = explicit, - ), + format!("{declare} the trait object {captures}, {explicit}",), &plus_lt, Applicability::MaybeIncorrect, ); @@ -400,7 +395,7 @@ pub fn suggest_new_region_bound( if let Some(explicit_static) = &explicit_static { err.span_suggestion_verbose( lt.ident.span, - format!("{} the trait object's {}", consider, explicit_static), + format!("{consider} the trait object's {explicit_static}"), &lifetime_name, Applicability::MaybeIncorrect, ); diff --git a/compiler/rustc_infer/src/infer/error_reporting/note.rs b/compiler/rustc_infer/src/infer/error_reporting/note.rs index 7144084c78ebe..a5d99bc148774 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note.rs @@ -227,7 +227,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { span, impl_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 if let Some(generics) = self.tcx.hir().get_generics(impl_item_def_id) @@ -245,10 +245,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { let mut err = self.report_concrete_failure(*parent, sub, sup); let trait_item_span = self.tcx.def_span(trait_item_def_id); let item_name = self.tcx.item_name(impl_item_def_id.to_def_id()); - err.span_label( - trait_item_span, - format!("definition of `{}` from trait", item_name), - ); + err.span_label(trait_item_span, format!("definition of `{item_name}` from trait")); self.suggest_copy_trait_method_bounds( trait_item_def_id, impl_item_def_id, diff --git a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs index 8e3f6b97e8f55..372539d73b130 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs @@ -47,7 +47,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { diag.span_suggestion( sp, "use a float literal", - format!("{}.0", snippet), + format!("{snippet}.0"), MachineApplicable, ); } @@ -134,7 +134,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { if matched_end_of_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( tcx, generics, @@ -148,7 +148,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { // Suggest adding a bound to an existing trait // or if the trait doesn't exist, add the trait // 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( tcx, generics, @@ -213,8 +213,7 @@ impl Trait for X { } diag.help(format!( "every closure has a distinct type and so could not always match the \ - caller-chosen type of parameter `{}`", - p + caller-chosen type of parameter `{p}`" )); } (ty::Param(p), _) | (_, ty::Param(p)) => { diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index ce5d3791a48f3..f1d53cb59cd46 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -575,12 +575,12 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { if param_hir.pat.span == param_hir.ty_span { // for `|x|`, `|_|`, `|x: impl Foo|` let Ok(pat) = self.tcx.sess.source_map().span_to_snippet(param_hir.pat.span) else { return; }; - suggestion += &format!("{}: &_", pat); + suggestion += &format!("{pat}: &_"); } else { // for `|x: ty|`, `|_: ty|` 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; }; - suggestion += &format!("{}: &{}", pat, ty); + suggestion += &format!("{pat}: &{ty}"); } has_suggestion = true; } else { diff --git a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs index 485e34fe2bf99..be424424f3ae8 100644 --- a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs +++ b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs @@ -837,9 +837,8 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> { self.var_infos[node_idx].origin.span(), format!( "collect_error_for_expanding_node() could not find \ - error for var {:?} in universe {:?}, lower_bounds={:#?}, \ - upper_bounds={:#?}", - node_idx, node_universe, lower_bounds, upper_bounds + error for var {node_idx:?} in universe {node_universe:?}, lower_bounds={lower_bounds:#?}, \ + upper_bounds={upper_bounds:#?}" ), ); } diff --git a/compiler/rustc_infer/src/infer/nll_relate/mod.rs b/compiler/rustc_infer/src/infer/nll_relate/mod.rs index 71c07f31bc952..c80491643913c 100644 --- a/compiler/rustc_infer/src/infer/nll_relate/mod.rs +++ b/compiler/rustc_infer/src/infer/nll_relate/mod.rs @@ -557,7 +557,7 @@ where // Forbid inference variables in the RHS. self.infcx.tcx.sess.delay_span_bug( self.delegate.span(), - format!("unexpected inference var {:?}", b,), + format!("unexpected inference var {b:?}",), ); Ok(a) } diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index 0681f414ce900..f36802e128435 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -253,7 +253,7 @@ where // this point it never will be self.tcx.sess.delay_span_bug( origin.span(), - format!("unresolved inference variable in outlives: {:?}", v), + format!("unresolved inference variable in outlives: {v:?}"), ); } } diff --git a/compiler/rustc_infer/src/infer/outlives/verify.rs b/compiler/rustc_infer/src/infer/outlives/verify.rs index 2bc6546ba28da..4279d0ab7ab3b 100644 --- a/compiler/rustc_infer/src/infer/outlives/verify.rs +++ b/compiler/rustc_infer/src/infer/outlives/verify.rs @@ -179,7 +179,7 @@ impl<'cx, 'tcx> VerifyBoundCx<'cx, 'tcx> { // this point it never will be self.tcx.sess.delay_span_bug( rustc_span::DUMMY_SP, - format!("unresolved inference variable in outlives: {:?}", v), + format!("unresolved inference variable in outlives: {v:?}"), ); // add a bound that never holds VerifyBound::AnyBound(vec![]) diff --git a/compiler/rustc_infer/src/infer/region_constraints/mod.rs b/compiler/rustc_infer/src/infer/region_constraints/mod.rs index 613da8a0b4576..708c51cabebc6 100644 --- a/compiler/rustc_infer/src/infer/region_constraints/mod.rs +++ b/compiler/rustc_infer/src/infer/region_constraints/mod.rs @@ -704,8 +704,8 @@ impl fmt::Debug for RegionSnapshot { impl<'tcx> fmt::Debug for GenericKind<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - GenericKind::Param(ref p) => write!(f, "{:?}", p), - GenericKind::Alias(ref p) => write!(f, "{:?}", p), + GenericKind::Param(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> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - GenericKind::Param(ref p) => write!(f, "{}", p), - GenericKind::Alias(ref p) => write!(f, "{}", p), + GenericKind::Param(ref p) => write!(f, "{p}"), + GenericKind::Alias(ref p) => write!(f, "{p}"), } } } diff --git a/compiler/rustc_infer/src/traits/error_reporting/mod.rs b/compiler/rustc_infer/src/traits/error_reporting/mod.rs index 9f440f39849a8..e72a43630e9b5 100644 --- a/compiler/rustc_infer/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/traits/error_reporting/mod.rs @@ -28,11 +28,11 @@ impl<'tcx> InferCtxt<'tcx> { 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) { 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 } @@ -56,7 +56,7 @@ pub fn report_object_safety_error<'tcx>( "the trait `{}` cannot be made into an object", 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 multi_span = vec![]; diff --git a/compiler/rustc_infer/src/traits/project.rs b/compiler/rustc_infer/src/traits/project.rs index e375d611936ea..afba2e50a23c5 100644 --- a/compiler/rustc_infer/src/traits/project.rs +++ b/compiler/rustc_infer/src/traits/project.rs @@ -190,7 +190,7 @@ impl<'tcx> ProjectionCache<'_, 'tcx> { } let fresh_key = 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 @@ -229,7 +229,7 @@ impl<'tcx> ProjectionCache<'_, 'tcx> { /// be different). pub fn ambiguous(&mut self, key: ProjectionCacheKey<'tcx>) { 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 @@ -237,14 +237,14 @@ impl<'tcx> ProjectionCache<'_, 'tcx> { /// an error here. pub fn recur(&mut self, key: ProjectionCacheKey<'tcx>) { 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 /// error. pub fn error(&mut self, key: ProjectionCacheKey<'tcx>) { let fresh = self.map().insert(key, ProjectionCacheEntry::Error); - assert!(!fresh, "never started projecting `{:?}`", key); + assert!(!fresh, "never started projecting `{key:?}`"); } } diff --git a/compiler/rustc_infer/src/traits/structural_impls.rs b/compiler/rustc_infer/src/traits/structural_impls.rs index 1563d92af0ea7..8a7c59da09ebb 100644 --- a/compiler/rustc_infer/src/traits/structural_impls.rs +++ b/compiler/rustc_infer/src/traits/structural_impls.rs @@ -38,17 +38,17 @@ impl<'tcx> fmt::Debug for traits::FulfillmentError<'tcx> { impl<'tcx> fmt::Debug for traits::FulfillmentErrorCode<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - super::CodeSelectionError(ref e) => write!(f, "{:?}", e), - super::CodeProjectionError(ref e) => write!(f, "{:?}", e), + super::CodeSelectionError(ref e) => write!(f, "{e:?}"), + super::CodeProjectionError(ref e) => write!(f, "{e:?}"), super::CodeSubtypeError(ref a, ref b) => { - write!(f, "CodeSubtypeError({:?}, {:?})", a, b) + write!(f, "CodeSubtypeError({a:?}, {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: true } => write!(f, "Overflow"), - super::CodeCycle(ref cycle) => write!(f, "Cycle({:?})", cycle), + super::CodeCycle(ref cycle) => write!(f, "Cycle({cycle:?})"), } } } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 84aca80b0dec0..cf6e7f16f071e 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -1716,7 +1716,7 @@ impl EarlyLintPass for EllipsisInclusiveRangePatterns { let end = expr_to_string(&end); let replace = match start { Some(start) => format!("&({}..={})", expr_to_string(&start), end), - None => format!("&(..={})", end), + None => format!("&(..={end})"), }; if join.edition() >= Edition::Edition2021 { cx.sess().emit_err(BuiltinEllipsisInclusiveRangePatterns { diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 7c701fd4fe16e..65c56bff84104 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -411,7 +411,7 @@ impl LintStore { } let complete_name = if let Some(tool_name) = tool_name { - format!("{}::{}", tool_name, lint_name) + format!("{tool_name}::{lint_name}") } else { lint_name.to_string() }; @@ -424,7 +424,7 @@ impl LintStore { // 1. The tool is currently running, so this lint really doesn't exist. // FIXME: should this handle tools that never register a lint, like rustfmt? debug!("lints={:?}", self.by_name.keys().collect::>()); - let tool_prefix = format!("{}::", tool_name); + let tool_prefix = format!("{tool_name}::"); return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) { self.no_lint_suggestion(&complete_name) } else { @@ -445,11 +445,11 @@ impl LintStore { } match self.by_name.get(&complete_name) { Some(Renamed(new_name, _)) => CheckLintNameResult::Warning( - format!("lint `{}` has been renamed to `{}`", complete_name, new_name), + format!("lint `{complete_name}` has been renamed to `{new_name}`"), Some(new_name.to_owned()), ), Some(Removed(reason)) => CheckLintNameResult::Warning( - format!("lint `{}` has been removed: {}", complete_name, reason), + format!("lint `{complete_name}` has been removed: {reason}"), None, ), None => match self.lint_groups.get(&*complete_name) { @@ -503,7 +503,7 @@ impl LintStore { lint_name: &str, tool_name: &str, ) -> CheckLintNameResult<'_> { - let complete_name = format!("{}::{}", tool_name, lint_name); + let complete_name = format!("{tool_name}::{lint_name}"); match self.by_name.get(&complete_name) { None => match self.lint_groups.get(&*complete_name) { // Now we are sure, that this lint exists nowhere @@ -618,12 +618,10 @@ pub trait LintContext: Sized { _ => ("", "s"), }; db.span_label(span, format!( - "this comment contains {}invisible unicode text flow control codepoint{}", - an, - s, + "this comment contains {an}invisible unicode text flow control codepoint{s}", )); for (c, span) in &spans { - db.span_label(*span, format!("{:?}", c)); + db.span_label(*span, format!("{c:?}")); } db.note( "these kind of unicode codepoints change the way text flows on \ @@ -648,7 +646,7 @@ pub trait LintContext: Sized { let opt_colon = if s.trim_start().starts_with("::") { "" } else { "::" }; - (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable) + (format!("crate{opt_colon}{s}"), Applicability::MachineApplicable) } Err(_) => ("crate::".to_string(), Applicability::HasPlaceholders), }; @@ -704,7 +702,7 @@ pub trait LintContext: Sized { let introduced = if is_imported { "imported" } else { "defined" }; db.span_label( span, - format!("the item `{}` is already {} here", ident, introduced), + format!("the item `{ident}` is already {introduced} here"), ); } } @@ -908,7 +906,7 @@ pub trait LintContext: Sized { BuiltinLintDiagnostics::NamedArgumentUsedPositionally{ position_sp_to_replace, position_sp_for_msg, named_arg_sp, named_arg_name, is_formatting_arg} => { db.span_label(named_arg_sp, "this named argument is referred to by position in formatting string"); if let Some(positional_arg_for_msg) = position_sp_for_msg { - let msg = format!("this formatting argument uses named argument `{}` by position", named_arg_name); + let msg = format!("this formatting argument uses named argument `{named_arg_name}` by position"); db.span_label(positional_arg_for_msg, msg); } @@ -949,11 +947,11 @@ pub trait LintContext: Sized { ); } BuiltinLintDiagnostics::AmbiguousGlobReexports { name, namespace, first_reexport_span, duplicate_reexport_span } => { - db.span_label(first_reexport_span, format!("the name `{}` in the {} namespace is first re-exported here", name, namespace)); - db.span_label(duplicate_reexport_span, format!("but the name `{}` in the {} namespace is also re-exported here", name, namespace)); + db.span_label(first_reexport_span, format!("the name `{name}` in the {namespace} namespace is first re-exported here")); + db.span_label(duplicate_reexport_span, format!("but the name `{name}` in the {namespace} namespace is also re-exported here")); } BuiltinLintDiagnostics::HiddenGlobReexports { name, namespace, glob_reexport_span, private_item_span } => { - db.span_note(glob_reexport_span, format!("the name `{}` in the {} namespace is supposed to be publicly re-exported here", name, namespace)); + db.span_note(glob_reexport_span, format!("the name `{name}` in the {namespace} namespace is supposed to be publicly re-exported here")); db.span_note(private_item_span, "but the private item here shadows it".to_owned()); } BuiltinLintDiagnostics::UnusedQualifications { removal_span } => { @@ -1281,8 +1279,8 @@ impl<'tcx> LateContext<'tcx> { // This shouldn't ever be needed, but just in case: with_no_trimmed_paths!({ Ok(vec![match trait_ref { - Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)), - None => Symbol::intern(&format!("<{}>", self_ty)), + Some(trait_ref) => Symbol::intern(&format!("{trait_ref:?}")), + None => Symbol::intern(&format!("<{self_ty}>")), }]) }) } @@ -1306,7 +1304,7 @@ impl<'tcx> LateContext<'tcx> { ))) } None => { - with_no_trimmed_paths!(Symbol::intern(&format!("", self_ty))) + with_no_trimmed_paths!(Symbol::intern(&format!(""))) } }); diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 0c80141a756d4..fb407be1f02a6 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -945,7 +945,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { ); } } else { - panic!("renamed lint does not exist: {}", new_name); + panic!("renamed lint does not exist: {new_name}"); } } } diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index 1dea758bb294b..2f2a5a933471a 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -776,7 +776,7 @@ impl AddToDiagnostic for HiddenUnicodeCodepointsDiagLabels { ) -> rustc_errors::SubdiagnosticMessage, { for (c, span) in self.spans { - diag.span_label(span, format!("{:?}", c)); + diag.span_label(span, format!("{c:?}")); } } } @@ -808,7 +808,7 @@ impl AddToDiagnostic for HiddenUnicodeCodepointsDiagSub { spans .into_iter() .map(|(c, span)| { - let c = format!("{:?}", c); + let c = format!("{c:?}"); (span, c[1..c.len() - 1].to_string()) }) .collect(), @@ -823,7 +823,7 @@ impl AddToDiagnostic for HiddenUnicodeCodepointsDiagSub { "escaped", spans .into_iter() - .map(|(c, _)| format!("{:?}", c)) + .map(|(c, _)| format!("{c:?}")) .collect::>() .join(", "), ); diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index f78da284a3a16..a3c5ca4cda19c 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -414,7 +414,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { match path { MustUsePath::Suppressed => {} MustUsePath::Boxed(path) => { - let descr_pre = &format!("{}boxed ", descr_pre); + let descr_pre = &format!("{descr_pre}boxed "); emit_must_use_untranslated( cx, path, @@ -426,7 +426,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { ); } MustUsePath::Opaque(path) => { - let descr_pre = &format!("{}implementer{} of ", descr_pre, plural_suffix); + let descr_pre = &format!("{descr_pre}implementer{plural_suffix} of "); emit_must_use_untranslated( cx, path, @@ -438,7 +438,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { ); } MustUsePath::TraitObject(path) => { - let descr_post = &format!(" trait object{}{}", plural_suffix, descr_post); + let descr_post = &format!(" trait object{plural_suffix}{descr_post}"); emit_must_use_untranslated( cx, path, @@ -451,7 +451,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { } MustUsePath::TupleElement(elems) => { for (index, path) in elems { - let descr_post = &format!(" in tuple element {}", index); + let descr_post = &format!(" in tuple element {index}"); emit_must_use_untranslated( cx, path, @@ -464,7 +464,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { } } MustUsePath::Array(path, len) => { - let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix); + let descr_pre = &format!("{descr_pre}array{plural_suffix} of "); emit_must_use_untranslated( cx, path, diff --git a/compiler/rustc_log/src/lib.rs b/compiler/rustc_log/src/lib.rs index 3cbb2c21e289e..e7b80c64184bf 100644 --- a/compiler/rustc_log/src/lib.rs +++ b/compiler/rustc_log/src/lib.rs @@ -123,7 +123,7 @@ where return Ok(()); } let backtrace = std::backtrace::Backtrace::capture(); - writeln!(writer, "stack backtrace: \n{:?}", backtrace) + writeln!(writer, "stack backtrace: \n{backtrace:?}") } } diff --git a/compiler/rustc_macros/src/serialize.rs b/compiler/rustc_macros/src/serialize.rs index 8d017d149f629..f1e7b8eb6c74c 100644 --- a/compiler/rustc_macros/src/serialize.rs +++ b/compiler/rustc_macros/src/serialize.rs @@ -43,7 +43,7 @@ fn decodable_body( let ty_name = s.ast().ident.to_string(); let decode_body = match s.variants() { [] => { - let message = format!("`{}` has no variants to decode", ty_name); + let message = format!("`{ty_name}` has no variants to decode"); quote! { panic!(#message) } diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index 441959967623f..fb9dd660d2f1a 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -908,7 +908,7 @@ pub fn list_file_metadata( let flavor = get_flavor_from_path(path); match get_metadata_section(target, flavor, path, metadata_loader) { Ok(metadata) => metadata.list_crate_metadata(out), - Err(msg) => write!(out, "{}\n", msg), + Err(msg) => write!(out, "{msg}\n"), } } diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 0bc16fc64ff78..0154fcd799aa4 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -51,7 +51,7 @@ mod encoder; mod table; pub(crate) fn rustc_version(cfg_version: &'static str) -> String { - format!("rustc {}", cfg_version) + format!("rustc {cfg_version}") } /// Metadata encoding version. diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 2dc5b8969934f..4e242c684e38d 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -380,7 +380,7 @@ impl<'tcx> DepNodeParams> for HirId { let local_id = local_id .as_u64() .try_into() - .unwrap_or_else(|_| panic!("local id should be u32, found {:?}", local_id)); + .unwrap_or_else(|_| panic!("local id should be u32, found {local_id:?}")); Some(HirId { owner: OwnerId { def_id }, local_id: ItemLocalId::from_u32(local_id) }) } else { None diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index 0ddbe7d1c2922..3ad9b0d79e794 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -35,7 +35,7 @@ impl rustc_query_system::dep_graph::DepKind for DepKind { if let Some(def_id) = node.extract_def_id(tcx) { write!(f, "{}", tcx.def_path_debug_str(def_id))?; } else if let Some(ref s) = tcx.dep_graph.dep_node_debug_str(*node) { - write!(f, "{}", s)?; + write!(f, "{s}")?; } else { write!(f, "{}", node.hash)?; } diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 1fd68dc5cb28e..3987219580d30 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -534,7 +534,7 @@ impl<'hir> Map<'hir> { (m, span, hir_id) } Some(OwnerNode::Crate(item)) => (item, item.spans.inner_span, hir_id), - node => panic!("not a module: {:?}", node), + node => panic!("not a module: {node:?}"), } } diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index 6ce1ad8f43e8b..9ecc7580f5cfc 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -218,14 +218,12 @@ pub fn explain_lint_level_source( let hyphen_case_lint_name = name.replace('_', "-"); if lint_flag_val.as_str() == name { err.note_once(format!( - "requested on the command line with `{} {}`", - flag, hyphen_case_lint_name + "requested on the command line with `{flag} {hyphen_case_lint_name}`" )); } else { let hyphen_case_flag_val = lint_flag_val.as_str().replace('_', "-"); err.note_once(format!( - "`{} {}` implied by `{} {}`", - flag, hyphen_case_lint_name, flag, hyphen_case_flag_val + "`{flag} {hyphen_case_lint_name}` implied by `{flag} {hyphen_case_flag_val}`" )); } } @@ -237,8 +235,7 @@ pub fn explain_lint_level_source( if lint_attr_name.as_str() != name { let level_str = level.as_str(); err.note_once(format!( - "`#[{}({})]` implied by `#[{}({})]`", - level_str, name, level_str, lint_attr_name + "`#[{level_str}({name})]` implied by `#[{level_str}({lint_attr_name})]`" )); } } @@ -416,12 +413,11 @@ pub fn struct_lint_level( FutureIncompatibilityReason::EditionError(edition) => { let current_edition = sess.edition(); format!( - "this is accepted in the current edition (Rust {}) but is a hard error in Rust {}!", - current_edition, edition + "this is accepted in the current edition (Rust {current_edition}) but is a hard error in Rust {edition}!" ) } FutureIncompatibilityReason::EditionSemanticsChange(edition) => { - format!("this changes meaning in Rust {}", edition) + format!("this changes meaning in Rust {edition}") } FutureIncompatibilityReason::Custom(reason) => reason.to_owned(), }; diff --git a/compiler/rustc_middle/src/middle/stability.rs b/compiler/rustc_middle/src/middle/stability.rs index 60844c17e4718..908ab8b613e88 100644 --- a/compiler/rustc_middle/src/middle/stability.rs +++ b/compiler/rustc_middle/src/middle/stability.rs @@ -107,7 +107,7 @@ pub fn report_unstable( soft_handler: impl FnOnce(&'static Lint, Span, String), ) { let msg = match reason { - Some(r) => format!("use of unstable library feature '{}': {}", feature, r), + Some(r) => format!("use of unstable library feature '{feature}': {r}"), None => format!("use of unstable library feature '{}'", &feature), }; @@ -170,7 +170,7 @@ pub fn deprecation_suggestion( if let Some(suggestion) = suggestion { diag.span_suggestion_verbose( span, - format!("replace the use of the deprecated {}", kind), + format!("replace the use of the deprecated {kind}"), suggestion, Applicability::MachineApplicable, ); @@ -189,12 +189,12 @@ fn deprecation_message( path: &str, ) -> String { let message = if is_in_effect { - format!("use of deprecated {} `{}`", kind, path) + format!("use of deprecated {kind} `{path}`") } else { let since = since.as_ref().map(Symbol::as_str); if since == Some("TBD") { - format!("use of {} `{}` that will be deprecated in a future Rust version", kind, path) + format!("use of {kind} `{path}` that will be deprecated in a future Rust version") } else { format!( "use of {} `{}` that will be deprecated in future version {}", @@ -206,7 +206,7 @@ fn deprecation_message( }; match note { - Some(reason) => format!("{}: {}", message, reason), + Some(reason) => format!("{message}: {reason}"), None => message, } } @@ -312,7 +312,7 @@ fn suggestion_for_allocator_api( return Some(( inner_types, "consider wrapping the inner types in tuple".to_string(), - format!("({})", snippet), + format!("({snippet})"), Applicability::MaybeIncorrect, )); } @@ -599,7 +599,7 @@ impl<'tcx> TyCtxt<'tcx> { |span, def_id| { // The API could be uncallable for other reasons, for example when a private module // was referenced. - self.sess.delay_span_bug(span, format!("encountered unmarked API: {:?}", def_id)); + self.sess.delay_span_bug(span, format!("encountered unmarked API: {def_id:?}")); }, ) } diff --git a/compiler/rustc_middle/src/mir/generic_graph.rs b/compiler/rustc_middle/src/mir/generic_graph.rs index d1f3561c02c5d..d1753427e740b 100644 --- a/compiler/rustc_middle/src/mir/generic_graph.rs +++ b/compiler/rustc_middle/src/mir/generic_graph.rs @@ -7,7 +7,7 @@ use rustc_middle::ty::TyCtxt; pub fn mir_fn_to_generic_graph<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'_>) -> Graph { let def_id = body.source.def_id(); let def_name = graphviz_safe_def_name(def_id); - let graph_name = format!("Mir_{}", def_name); + let graph_name = format!("Mir_{def_name}"); let dark_mode = tcx.sess.opts.unstable_opts.graphviz_dark_mode; // Nodes @@ -48,7 +48,7 @@ fn bb_to_graph_node(block: BasicBlock, body: &Body<'_>, dark_mode: bool) -> Node }; let style = NodeStyle { title_bg: Some(bgcolor.to_owned()), ..Default::default() }; - let mut stmts: Vec = data.statements.iter().map(|x| format!("{:?}", x)).collect(); + let mut stmts: Vec = data.statements.iter().map(|x| format!("{x:?}")).collect(); // add the terminator to the stmts, gsgdt can print it out separately let mut terminator_head = String::new(); diff --git a/compiler/rustc_middle/src/mir/generic_graphviz.rs b/compiler/rustc_middle/src/mir/generic_graphviz.rs index ccae7e159b1f1..299b50525cb1e 100644 --- a/compiler/rustc_middle/src/mir/generic_graphviz.rs +++ b/compiler/rustc_middle/src/mir/generic_graphviz.rs @@ -70,8 +70,8 @@ impl< writeln!(w, r#" graph [{}];"#, graph_attrs.join(" "))?; let content_attrs_str = content_attrs.join(" "); - writeln!(w, r#" node [{}];"#, content_attrs_str)?; - writeln!(w, r#" edge [{}];"#, content_attrs_str)?; + writeln!(w, r#" node [{content_attrs_str}];"#)?; + writeln!(w, r#" edge [{content_attrs_str}];"#)?; // Graph label if let Some(graph_label) = &self.graph_label { @@ -112,7 +112,7 @@ impl< // (format!("{:?}", node), color) // }; let color = if dark_mode { "dimgray" } else { "gray" }; - let (blk, bgcolor) = (format!("{:?}", node), color); + let (blk, bgcolor) = (format!("{node:?}"), color); write!( w, r#"{blk}"#, @@ -151,7 +151,7 @@ impl< } else { "".to_owned() }; - writeln!(w, r#" {} -> {} [label=<{}>];"#, src, trg, escaped_edge_label)?; + writeln!(w, r#" {src} -> {trg} [label=<{escaped_edge_label}>];"#)?; } Ok(()) } @@ -163,7 +163,7 @@ impl< W: Write, { let escaped_label = dot::escape_html(label); - writeln!(w, r#" label=<

{}



>;"#, escaped_label) + writeln!(w, r#" label=<

{escaped_label}



>;"#) } fn node(&self, node: G::Node) -> String { diff --git a/compiler/rustc_middle/src/mir/graphviz.rs b/compiler/rustc_middle/src/mir/graphviz.rs index 2de73db3a3cfb..5c7de86443008 100644 --- a/compiler/rustc_middle/src/mir/graphviz.rs +++ b/compiler/rustc_middle/src/mir/graphviz.rs @@ -127,5 +127,5 @@ fn write_graph_label<'tcx, W: std::fmt::Write>( } fn escape(t: &T) -> String { - dot::escape_html(&format!("{:?}", t)) + dot::escape_html(&format!("{t:?}")) } diff --git a/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs b/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs index d4dd56a42c1ed..2c6bb908f39f6 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs @@ -542,11 +542,7 @@ impl InitMaskMaterialized { debug_assert_eq!( result, find_bit_slow(self, start, end, is_init), - "optimized implementation of find_bit is wrong for start={:?} end={:?} is_init={} init_mask={:#?}", - start, - end, - is_init, - self + "optimized implementation of find_bit is wrong for start={start:?} end={end:?} is_init={is_init} init_mask={self:#?}" ); result diff --git a/compiler/rustc_middle/src/mir/interpret/error.rs b/compiler/rustc_middle/src/mir/interpret/error.rs index 372452ea29a8d..a83c5af9293d1 100644 --- a/compiler/rustc_middle/src/mir/interpret/error.rs +++ b/compiler/rustc_middle/src/mir/interpret/error.rs @@ -156,7 +156,7 @@ impl<'tcx> InterpErrorInfo<'tcx> { } fn print_backtrace(backtrace: &Backtrace) { - eprintln!("\n\nAn error occurred in miri:\n{}", backtrace); + eprintln!("\n\nAn error occurred in miri:\n{backtrace}"); } impl From for InterpErrorInfo<'_> { diff --git a/compiler/rustc_middle/src/mir/interpret/mod.rs b/compiler/rustc_middle/src/mir/interpret/mod.rs index 69c15e9cc0607..8b5a8d1730106 100644 --- a/compiler/rustc_middle/src/mir/interpret/mod.rs +++ b/compiler/rustc_middle/src/mir/interpret/mod.rs @@ -176,7 +176,7 @@ impl<'tcx> GlobalId<'tcx> { pub fn display(self, tcx: TyCtxt<'tcx>) -> String { let instance_name = with_no_trimmed_paths!(tcx.def_path_str(self.instance.def.def_id())); if let Some(promoted) = self.promoted { - format!("{}::{:?}", instance_name, promoted) + format!("{instance_name}::{promoted:?}") } else { instance_name } diff --git a/compiler/rustc_middle/src/mir/interpret/value.rs b/compiler/rustc_middle/src/mir/interpret/value.rs index 0416411dfe14a..f158b91c78941 100644 --- a/compiler/rustc_middle/src/mir/interpret/value.rs +++ b/compiler/rustc_middle/src/mir/interpret/value.rs @@ -135,8 +135,8 @@ static_assert_size!(Scalar, 24); impl fmt::Debug for Scalar { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Scalar::Ptr(ptr, _size) => write!(f, "{:?}", ptr), - Scalar::Int(int) => write!(f, "{:?}", int), + Scalar::Ptr(ptr, _size) => write!(f, "{ptr:?}"), + Scalar::Int(int) => write!(f, "{int:?}"), } } } @@ -144,8 +144,8 @@ impl fmt::Debug for Scalar { impl fmt::Display for Scalar { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Scalar::Ptr(ptr, _size) => write!(f, "pointer to {:?}", ptr), - Scalar::Int(int) => write!(f, "{}", int), + Scalar::Ptr(ptr, _size) => write!(f, "pointer to {ptr:?}"), + Scalar::Int(int) => write!(f, "{int}"), } } } @@ -153,8 +153,8 @@ impl fmt::Display for Scalar { impl fmt::LowerHex for Scalar { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Scalar::Ptr(ptr, _size) => write!(f, "pointer to {:?}", ptr), - Scalar::Int(int) => write!(f, "{:#x}", int), + Scalar::Ptr(ptr, _size) => write!(f, "pointer to {ptr:?}"), + Scalar::Int(int) => write!(f, "{int:#x}"), } } } diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 97f53a59fd66c..88581f6e0f027 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -619,7 +619,7 @@ impl> Decodable for ClearCrossCrate { let val = T::decode(d); ClearCrossCrate::Set(val) } - tag => panic!("Invalid tag for ClearCrossCrate: {:?}", tag), + tag => panic!("Invalid tag for ClearCrossCrate: {tag:?}"), } } } @@ -1048,12 +1048,12 @@ pub enum VarDebugInfoContents<'tcx> { impl<'tcx> Debug for VarDebugInfoContents<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { match self { - VarDebugInfoContents::Const(c) => write!(fmt, "{}", c), - VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p), + VarDebugInfoContents::Const(c) => write!(fmt, "{c}"), + VarDebugInfoContents::Place(p) => write!(fmt, "{p:?}"), VarDebugInfoContents::Composite { ty, fragments } => { - write!(fmt, "{:?}{{ ", ty)?; + write!(fmt, "{ty:?}{{ ")?; for f in fragments.iter() { - write!(fmt, "{:?}, ", f)?; + write!(fmt, "{f:?}, ")?; } write!(fmt, "}}") } @@ -1317,55 +1317,47 @@ impl AssertKind { match self { BoundsCheck { ref len, ref index } => write!( f, - "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}", - len, index + "\"index out of bounds: the length is {{}} but the index is {{}}\", {len:?}, {index:?}" ), OverflowNeg(op) => { - write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op) + write!(f, "\"attempt to negate `{{}}`, which would overflow\", {op:?}") } - DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op), + DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {op:?}"), RemainderByZero(op) => write!( f, - "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}", - op + "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {op:?}" ), Overflow(BinOp::Add, l, r) => write!( f, - "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute `{{}} + {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Sub, l, r) => write!( f, - "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute `{{}} - {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Mul, l, r) => write!( f, - "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute `{{}} * {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Div, l, r) => write!( f, - "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute `{{}} / {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Rem, l, r) => write!( f, - "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Shr, _, r) => { - write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r) + write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {r:?}") } Overflow(BinOp::Shl, _, r) => { - write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r) + write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {r:?}") } MisalignedPointerDereference { required, found } => { write!( f, - "\"misaligned pointer dereference: address must be a multiple of {{}} but is {{}}\", {:?}, {:?}", - required, found + "\"misaligned pointer dereference: address must be a multiple of {{}} but is {{}}\", {required:?}, {found:?}" ) } _ => write!(f, "\"{}\"", self.description()), @@ -1461,9 +1453,9 @@ impl Debug for Statement<'_> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { use self::StatementKind::*; match self.kind { - Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv), + Assign(box (ref place, ref rv)) => write!(fmt, "{place:?} = {rv:?}"), FakeRead(box (ref cause, ref place)) => { - write!(fmt, "FakeRead({:?}, {:?})", cause, place) + write!(fmt, "FakeRead({cause:?}, {place:?})") } Retag(ref kind, ref place) => write!( fmt, @@ -1476,20 +1468,20 @@ impl Debug for Statement<'_> { }, place, ), - StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place), - StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place), + StorageLive(ref place) => write!(fmt, "StorageLive({place:?})"), + StorageDead(ref place) => write!(fmt, "StorageDead({place:?})"), SetDiscriminant { ref place, variant_index } => { - write!(fmt, "discriminant({:?}) = {:?}", place, variant_index) + write!(fmt, "discriminant({place:?}) = {variant_index:?}") } - Deinit(ref place) => write!(fmt, "Deinit({:?})", place), + Deinit(ref place) => write!(fmt, "Deinit({place:?})"), PlaceMention(ref place) => { - write!(fmt, "PlaceMention({:?})", place) + write!(fmt, "PlaceMention({place:?})") } AscribeUserType(box (ref place, ref c_ty), ref variance) => { - write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty) + write!(fmt, "AscribeUserType({place:?}, {variance:?}, {c_ty:?})") } Coverage(box self::Coverage { ref kind, code_region: Some(ref rgn) }) => { - write!(fmt, "Coverage::{:?} for {:?}", kind, rgn) + write!(fmt, "Coverage::{kind:?} for {rgn:?}") } Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind), Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"), @@ -1769,13 +1761,13 @@ impl Debug for Place<'_> { for elem in self.projection.iter() { match elem { ProjectionElem::OpaqueCast(ty) => { - write!(fmt, " as {})", ty)?; + write!(fmt, " as {ty})")?; } ProjectionElem::Downcast(Some(name), _index) => { - write!(fmt, " as {})", name)?; + write!(fmt, " as {name})")?; } ProjectionElem::Downcast(None, index) => { - write!(fmt, " as variant#{:?})", index)?; + write!(fmt, " as variant#{index:?})")?; } ProjectionElem::Deref => { write!(fmt, ")")?; @@ -1784,25 +1776,25 @@ impl Debug for Place<'_> { write!(fmt, ".{:?}: {:?})", field.index(), ty)?; } ProjectionElem::Index(ref index) => { - write!(fmt, "[{:?}]", index)?; + write!(fmt, "[{index:?}]")?; } ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => { - write!(fmt, "[{:?} of {:?}]", offset, min_length)?; + write!(fmt, "[{offset:?} of {min_length:?}]")?; } ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => { - write!(fmt, "[-{:?} of {:?}]", offset, min_length)?; + write!(fmt, "[-{offset:?} of {min_length:?}]")?; } ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => { - write!(fmt, "[{:?}:]", from)?; + write!(fmt, "[{from:?}:]")?; } ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => { - write!(fmt, "[:-{:?}]", to)?; + write!(fmt, "[:-{to:?}]")?; } ProjectionElem::Subslice { from, to, from_end: true } => { - write!(fmt, "[{:?}:-{:?}]", from, to)?; + write!(fmt, "[{from:?}:-{to:?}]")?; } ProjectionElem::Subslice { from, to, from_end: false } => { - write!(fmt, "[{:?}..{:?}]", from, to)?; + write!(fmt, "[{from:?}..{to:?}]")?; } } } @@ -1896,9 +1888,9 @@ impl<'tcx> Debug for Operand<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { use self::Operand::*; match *self { - Constant(ref a) => write!(fmt, "{:?}", a), - Copy(ref place) => write!(fmt, "{:?}", place), - Move(ref place) => write!(fmt, "move {:?}", place), + Constant(ref a) => write!(fmt, "{a:?}"), + Copy(ref place) => write!(fmt, "{place:?}"), + Move(ref place) => write!(fmt, "move {place:?}"), } } } @@ -1937,11 +1929,11 @@ impl<'tcx> Operand<'tcx> { let param_env_and_ty = ty::ParamEnv::empty().and(ty); let type_size = tcx .layout_of(param_env_and_ty) - .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e)) + .unwrap_or_else(|e| panic!("could not compute layout for {ty:?}: {e:?}")) .size; let scalar_size = match val { Scalar::Int(int) => int.size(), - _ => panic!("Invalid scalar type {:?}", val), + _ => panic!("Invalid scalar type {val:?}"), }; scalar_size == type_size }); @@ -2057,26 +2049,26 @@ impl<'tcx> Debug for Rvalue<'tcx> { use self::Rvalue::*; match *self { - Use(ref place) => write!(fmt, "{:?}", place), + Use(ref place) => write!(fmt, "{place:?}"), Repeat(ref a, b) => { - write!(fmt, "[{:?}; ", a)?; + write!(fmt, "[{a:?}; ")?; pretty_print_const(b, fmt, false)?; write!(fmt, "]") } - Len(ref a) => write!(fmt, "Len({:?})", a), + Len(ref a) => write!(fmt, "Len({a:?})"), Cast(ref kind, ref place, ref ty) => { - write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind) + write!(fmt, "{place:?} as {ty:?} ({kind:?})") } - BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{:?}({:?}, {:?})", op, a, b), + BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{op:?}({a:?}, {b:?})"), CheckedBinaryOp(ref op, box (ref a, ref b)) => { - write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b) + write!(fmt, "Checked{op:?}({a:?}, {b:?})") } - UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a), - Discriminant(ref place) => write!(fmt, "discriminant({:?})", place), + UnaryOp(ref op, ref a) => write!(fmt, "{op:?}({a:?})"), + Discriminant(ref place) => write!(fmt, "discriminant({place:?})"), NullaryOp(ref op, ref t) => match op { - NullOp::SizeOf => write!(fmt, "SizeOf({:?})", t), - NullOp::AlignOf => write!(fmt, "AlignOf({:?})", t), - NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({:?}, {:?})", t, fields), + NullOp::SizeOf => write!(fmt, "SizeOf({t:?})"), + NullOp::AlignOf => write!(fmt, "AlignOf({t:?})"), + NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t:?}, {fields:?})"), }, ThreadLocalRef(did) => ty::tls::with(|tcx| { let muta = tcx.static_mutability(did).unwrap().prefix_str(); @@ -2103,10 +2095,10 @@ impl<'tcx> Debug for Rvalue<'tcx> { // Do not even print 'static String::new() }; - write!(fmt, "&{}{}{:?}", region, kind_str, place) + write!(fmt, "&{region}{kind_str}{place:?}") } - CopyForDeref(ref place) => write!(fmt, "deref_copy {:#?}", place), + CopyForDeref(ref place) => write!(fmt, "deref_copy {place:#?}"), AddressOf(mutability, ref place) => { let kind_str = match mutability { @@ -2114,7 +2106,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { Mutability::Not => "const", }; - write!(fmt, "&raw {} {:?}", kind_str, place) + write!(fmt, "&raw {kind_str} {place:?}") } Aggregate(ref kind, ref places) => { @@ -2127,7 +2119,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { }; match **kind { - AggregateKind::Array(_) => write!(fmt, "{:?}", places), + AggregateKind::Array(_) => write!(fmt, "{places:?}"), AggregateKind::Tuple => { if places.is_empty() { @@ -2213,7 +2205,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { } ShallowInitBox(ref place, ref ty) => { - write!(fmt, "ShallowInitBox({:?}, {:?})", place, ty) + write!(fmt, "ShallowInitBox({place:?}, {ty:?})") } } } @@ -2757,7 +2749,7 @@ rustc_index::newtype_index! { impl<'tcx> Debug for Constant<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { - write!(fmt, "{}", self) + write!(fmt, "{self}") } } @@ -2833,7 +2825,7 @@ fn pretty_print_const_value<'tcx>( let ty = tcx.lift(ty).unwrap(); if tcx.sess.verbose() { - fmt.write_str(&format!("ConstValue({:?}: {})", ct, ty))?; + fmt.write_str(&format!("ConstValue({ct:?}: {ty})"))?; return Ok(()); } @@ -2903,7 +2895,7 @@ fn pretty_print_const_value<'tcx>( fmt.write_str(")")?; } ty::Adt(def, _) if def.variants().is_empty() => { - fmt.write_str(&format!("{{unreachable(): {}}}", ty))?; + fmt.write_str(&format!("{{unreachable(): {ty}}}"))?; } ty::Adt(def, args) => { let variant_idx = contents diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index f4133dfbc95b9..ddb6cc15bc189 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -223,7 +223,7 @@ impl<'tcx> MonoItem<'tcx> { impl<'tcx> fmt::Display for MonoItem<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - MonoItem::Fn(instance) => write!(f, "fn {}", instance), + MonoItem::Fn(instance) => write!(f, "fn {instance}"), MonoItem::Static(def_id) => { write!(f, "static {}", Instance::new(def_id, GenericArgs::empty())) } @@ -534,17 +534,17 @@ impl<'tcx> CodegenUnitNameBuilder<'tcx> { format!("{}.{:08x}{}", tcx.crate_name(cnum), stable_crate_id, local_crate_id) }); - write!(cgu_name, "{}", crate_prefix).unwrap(); + write!(cgu_name, "{crate_prefix}").unwrap(); // Add the components for component in components { - write!(cgu_name, "-{}", component).unwrap(); + write!(cgu_name, "-{component}").unwrap(); } if let Some(special_suffix) = special_suffix { // We add a dot in here so it cannot clash with anything in a regular // Rust identifier - write!(cgu_name, ".{}", special_suffix).unwrap(); + write!(cgu_name, ".{special_suffix}").unwrap(); } Symbol::intern(&cgu_name) diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 8cbab31451b2f..27e3913709231 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -124,14 +124,14 @@ fn dump_matched_mir_node<'tcx, F>( let def_path = ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id())); // ignore-tidy-odd-backticks the literal below is fine - write!(file, "// MIR for `{}", def_path)?; + write!(file, "// MIR for `{def_path}")?; match body.source.promoted { None => write!(file, "`")?, - Some(promoted) => write!(file, "::{:?}`", promoted)?, + Some(promoted) => write!(file, "::{promoted:?}`")?, } - writeln!(file, " {} {}", disambiguator, pass_name)?; + writeln!(file, " {disambiguator} {pass_name}")?; if let Some(ref layout) = body.generator_layout() { - writeln!(file, "/* generator_layout = {:#?} */", layout)?; + writeln!(file, "/* generator_layout = {layout:#?} */")?; } writeln!(file)?; extra_data(PassWhere::BeforeCFG, &mut file)?; @@ -169,7 +169,7 @@ fn dump_file_basename<'tcx>( ) -> String { let source = body.source; let promotion_id = match source.promoted { - Some(id) => format!("-{:?}", id), + Some(id) => format!("-{id:?}"), None => String::new(), }; @@ -203,8 +203,7 @@ fn dump_file_basename<'tcx>( }; format!( - "{}.{}{}{}{}.{}.{}", - crate_name, item_name, shim_disambiguator, promotion_id, pass_num, pass_name, disambiguator, + "{crate_name}.{item_name}{shim_disambiguator}{promotion_id}{pass_num}.{pass_name}.{disambiguator}", ) } @@ -215,7 +214,7 @@ fn dump_path(tcx: TyCtxt<'_>, basename: &str, extension: &str) -> PathBuf { let mut file_path = PathBuf::new(); file_path.push(Path::new(&tcx.sess.opts.unstable_opts.dump_mir_dir)); - let file_name = format!("{}.{}", basename, extension,); + let file_name = format!("{basename}.{extension}",); file_path.push(&file_name); @@ -233,12 +232,12 @@ fn create_dump_file_with_basename( fs::create_dir_all(parent).map_err(|e| { io::Error::new( e.kind(), - format!("IO error creating MIR dump directory: {:?}; {}", parent, e), + format!("IO error creating MIR dump directory: {parent:?}; {e}"), ) })?; } Ok(io::BufWriter::new(fs::File::create(&file_path).map_err(|e| { - io::Error::new(e.kind(), format!("IO error creating MIR dump file: {:?}; {}", file_path, e)) + io::Error::new(e.kind(), format!("IO error creating MIR dump file: {file_path:?}; {e}")) })?)) } @@ -346,28 +345,24 @@ where // Basic block label at the top. let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" }; - writeln!(w, "{}{:?}{}: {{", INDENT, block, cleanup_text)?; + writeln!(w, "{INDENT}{block:?}{cleanup_text}: {{")?; // List of statements in the middle. let mut current_location = Location { block, statement_index: 0 }; for statement in &data.statements { extra_data(PassWhere::BeforeLocation(current_location), w)?; - let indented_body = format!("{0}{0}{1:?};", INDENT, statement); + let indented_body = format!("{INDENT}{INDENT}{statement:?};"); if tcx.sess.opts.unstable_opts.mir_include_spans { writeln!( w, "{:A$} // {}{}", indented_body, - if tcx.sess.verbose() { - format!("{:?}: ", current_location) - } else { - String::new() - }, + if tcx.sess.verbose() { format!("{current_location:?}: ") } else { String::new() }, comment(tcx, statement.source_info), A = ALIGN, )?; } else { - writeln!(w, "{}", indented_body)?; + writeln!(w, "{indented_body}")?; } write_extra(tcx, w, |visitor| { @@ -387,12 +382,12 @@ where w, "{:A$} // {}{}", indented_terminator, - if tcx.sess.verbose() { format!("{:?}: ", current_location) } else { String::new() }, + if tcx.sess.verbose() { format!("{current_location:?}: ") } else { String::new() }, comment(tcx, data.terminator().source_info), A = ALIGN, )?; } else { - writeln!(w, "{}", indented_terminator)?; + writeln!(w, "{indented_terminator}")?; } write_extra(tcx, w, |visitor| { @@ -402,7 +397,7 @@ where extra_data(PassWhere::AfterLocation(current_location), w)?; extra_data(PassWhere::AfterTerminator(block), w)?; - writeln!(w, "{}}}", INDENT) + writeln!(w, "{INDENT}}}") } /// After we print the main statement, we sometimes dump extra @@ -457,25 +452,25 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { self.tcx.sess.source_map().span_to_embeddable_string(*span) )); if let Some(user_ty) = user_ty { - self.push(&format!("+ user_ty: {:?}", user_ty)); + self.push(&format!("+ user_ty: {user_ty:?}")); } // FIXME: this is a poor version of `pretty_print_const_value`. let fmt_val = |val: &ConstValue<'tcx>| match val { ConstValue::ZeroSized => "".to_string(), - ConstValue::Scalar(s) => format!("Scalar({:?})", s), + ConstValue::Scalar(s) => format!("Scalar({s:?})"), ConstValue::Slice { .. } => "Slice(..)".to_string(), ConstValue::ByRef { .. } => "ByRef(..)".to_string(), }; let fmt_valtree = |valtree: &ty::ValTree<'tcx>| match valtree { - ty::ValTree::Leaf(leaf) => format!("ValTree::Leaf({:?})", leaf), + ty::ValTree::Leaf(leaf) => format!("ValTree::Leaf({leaf:?})"), ty::ValTree::Branch(_) => "ValTree::Branch(..)".to_string(), }; let val = match literal { ConstantKind::Ty(ct) => match ct.kind() { - ty::ConstKind::Param(p) => format!("Param({})", p), + ty::ConstKind::Param(p) => format!("Param({p})"), ty::ConstKind::Unevaluated(uv) => { format!("Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,) } @@ -514,20 +509,20 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { match **kind { AggregateKind::Closure(def_id, args) => { self.push("closure"); - self.push(&format!("+ def_id: {:?}", def_id)); - self.push(&format!("+ args: {:#?}", args)); + self.push(&format!("+ def_id: {def_id:?}")); + self.push(&format!("+ args: {args:#?}")); } AggregateKind::Generator(def_id, args, movability) => { self.push("generator"); - self.push(&format!("+ def_id: {:?}", def_id)); - self.push(&format!("+ args: {:#?}", args)); - self.push(&format!("+ movability: {:?}", movability)); + self.push(&format!("+ def_id: {def_id:?}")); + self.push(&format!("+ args: {args:#?}")); + self.push(&format!("+ movability: {movability:?}")); } AggregateKind::Adt(_, _, _, Some(user_ty), _) => { self.push("adt"); - self.push(&format!("+ user_ty: {:?}", user_ty)); + self.push(&format!("+ user_ty: {user_ty:?}")); } _ => {} @@ -578,7 +573,7 @@ fn write_scope_tree( comment(tcx, var_debug_info.source_info), )?; } else { - writeln!(w, "{}", indented_debug_info)?; + writeln!(w, "{indented_debug_info}")?; } } @@ -600,7 +595,7 @@ fn write_scope_tree( format!("{0:1$}let {2}{3:?}: {4:?}", INDENT, indent, mut_str, local, local_decl.ty); if let Some(user_ty) = &local_decl.user_ty { for user_ty in user_ty.projections() { - write!(indented_decl, " as {:?}", user_ty).unwrap(); + write!(indented_decl, " as {user_ty:?}").unwrap(); } } indented_decl.push(';'); @@ -617,7 +612,7 @@ fn write_scope_tree( comment(tcx, local_decl.source_info), )?; } else { - writeln!(w, "{}", indented_decl,)?; + writeln!(w, "{indented_decl}",)?; } } @@ -654,10 +649,10 @@ fn write_scope_tree( tcx.sess.source_map().span_to_embeddable_string(span), )?; } else { - writeln!(w, "{}", indented_header)?; + writeln!(w, "{indented_header}")?; } } else { - writeln!(w, "{}", indented_header)?; + writeln!(w, "{indented_header}")?; } write_scope_tree(tcx, body, scope_tree, w, child, depth + 1)?; @@ -844,7 +839,7 @@ fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fm for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) { write!(w, " ")?; } - writeln!(w, " │ {}", ascii) + writeln!(w, " │ {ascii}") } /// Number of bytes to print per allocation hex dump line. @@ -880,7 +875,7 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( if num_lines > 0 { write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?; } else { - write!(w, "{}", prefix)?; + write!(w, "{prefix}")?; } let mut i = Size::ZERO; @@ -913,10 +908,10 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( let offset = Size::from_bytes(offset); let provenance_width = |bytes| bytes * 3; let ptr = Pointer::new(prov, offset); - let mut target = format!("{:?}", ptr); + let mut target = format!("{ptr:?}"); if target.len() > provenance_width(ptr_size.bytes_usize() - 1) { // This is too long, try to save some space. - target = format!("{:#?}", ptr); + target = format!("{ptr:#?}"); } if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE { // This branch handles the situation where a provenance starts in the current line @@ -935,10 +930,10 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?; ascii.clear(); - write!(w, "{0:─^1$}╼", target, overflow_width)?; + write!(w, "{target:─^overflow_width$}╼")?; } else { oversized_ptr(&mut target, remainder_width); - write!(w, "╾{0:─^1$}", target, remainder_width)?; + write!(w, "╾{target:─^remainder_width$}")?; line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?; write!(w, "{0:─^1$}╼", "", overflow_width)?; @@ -955,7 +950,7 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( let provenance_width = provenance_width(ptr_size.bytes_usize() - 1); oversized_ptr(&mut target, provenance_width); ascii.push('╾'); - write!(w, "╾{0:─^1$}╼", target, provenance_width)?; + write!(w, "╾{target:─^provenance_width$}╼")?; for _ in 0..ptr_size.bytes() - 2 { ascii.push('─'); } @@ -972,7 +967,7 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( // Format is similar to "oversized" above. let j = i.bytes_usize(); let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0]; - write!(w, "╾{:02x}{:#?} (1 ptr byte)╼", c, prov)?; + write!(w, "╾{c:02x}{prov:#?} (1 ptr byte)╼")?; i += Size::from_bytes(1); } else if alloc .init_mask() @@ -984,7 +979,7 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( // Checked definedness (and thus range) and provenance. This access also doesn't // influence interpreter execution but is only for debugging. let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0]; - write!(w, "{:02x}", c)?; + write!(w, "{c:02x}")?; if c.is_ascii_control() || c >= 0x80 { ascii.push('.'); } else { @@ -1018,7 +1013,7 @@ fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write) -> io::Res _ => tcx.is_closure(def_id), }; match (kind, body.source.promoted) { - (_, Some(i)) => write!(w, "{:?} in ", i)?, + (_, Some(i)) => write!(w, "{i:?} in ")?, (DefKind::Const | DefKind::AssocConst, _) => write!(w, "const ")?, (DefKind::Static(hir::Mutability::Not), _) => write!(w, "static ")?, (DefKind::Static(hir::Mutability::Mut), _) => write!(w, "static mut ")?, @@ -1051,7 +1046,7 @@ fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write) -> io::Res if let Some(yield_ty) = body.yield_ty() { writeln!(w)?; - writeln!(w, "yields {}", yield_ty)?; + writeln!(w, "yields {yield_ty}")?; } write!(w, " ")?; diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index e8cb9860ee594..71bec49af93e6 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -198,7 +198,7 @@ impl Debug for GeneratorLayout<'_> { if fmt.alternate() { write!(fmt, "{:9}({:?})", variant_name, self.0) } else { - write!(fmt, "{}", variant_name) + write!(fmt, "{variant_name}") } } } diff --git a/compiler/rustc_middle/src/mir/spanview.rs b/compiler/rustc_middle/src/mir/spanview.rs index 730c551576acd..20a9e6889e40a 100644 --- a/compiler/rustc_middle/src/mir/spanview.rs +++ b/compiler/rustc_middle/src/mir/spanview.rs @@ -159,10 +159,10 @@ where indent_to_initial_start_col, source_map.span_to_snippet(spanview_span).expect("function should have printable source") ); - writeln!(w, "{}", HEADER)?; - writeln!(w, "{}", title)?; - writeln!(w, "{}", STYLE_SECTION)?; - writeln!(w, "{}", START_BODY)?; + writeln!(w, "{HEADER}")?; + writeln!(w, "{title}")?; + writeln!(w, "{STYLE_SECTION}")?; + writeln!(w, "{START_BODY}")?; write!( w, r#"
{}"#, @@ -226,7 +226,7 @@ where write_coverage_gap(tcx, from_pos, end_pos, w)?; } writeln!(w, r#"
"#)?; - writeln!(w, "{}", FOOTER)?; + writeln!(w, "{FOOTER}")?; Ok(()) } @@ -561,17 +561,16 @@ where } for (i, line) in html_snippet.lines().enumerate() { if i > 0 { - write!(w, "{}", NEW_LINE_SPAN)?; + write!(w, "{NEW_LINE_SPAN}")?; } write!( w, - r#"{}"#, - maybe_alt_class, layer, maybe_title_attr, line + r#"{line}"# )?; } // Check for and translate trailing newlines, because `str::lines()` ignores them if html_snippet.ends_with('\n') { - write!(w, "{}", NEW_LINE_SPAN)?; + write!(w, "{NEW_LINE_SPAN}")?; } if layer == 1 { write!(w, "
")?; diff --git a/compiler/rustc_middle/src/mir/terminator.rs b/compiler/rustc_middle/src/mir/terminator.rs index 1b9c1438f406c..6de843515950d 100644 --- a/compiler/rustc_middle/src/mir/terminator.rs +++ b/compiler/rustc_middle/src/mir/terminator.rs @@ -280,7 +280,7 @@ impl<'tcx> Debug for TerminatorKind<'tcx> { match (successor_count, unwind) { (0, None) => Ok(()), - (0, Some(unwind)) => write!(fmt, " -> {}", unwind), + (0, Some(unwind)) => write!(fmt, " -> {unwind}"), (1, None) => write!(fmt, " -> {:?}", self.successors().next().unwrap()), _ => { write!(fmt, " -> [")?; @@ -307,22 +307,22 @@ impl<'tcx> TerminatorKind<'tcx> { use self::TerminatorKind::*; match self { Goto { .. } => write!(fmt, "goto"), - SwitchInt { discr, .. } => write!(fmt, "switchInt({:?})", discr), + SwitchInt { discr, .. } => write!(fmt, "switchInt({discr:?})"), Return => write!(fmt, "return"), GeneratorDrop => write!(fmt, "generator_drop"), Resume => write!(fmt, "resume"), Terminate => write!(fmt, "abort"), - Yield { value, resume_arg, .. } => write!(fmt, "{:?} = yield({:?})", resume_arg, value), + Yield { value, resume_arg, .. } => write!(fmt, "{resume_arg:?} = yield({value:?})"), Unreachable => write!(fmt, "unreachable"), - Drop { place, .. } => write!(fmt, "drop({:?})", place), + Drop { place, .. } => write!(fmt, "drop({place:?})"), Call { func, args, destination, .. } => { - write!(fmt, "{:?} = ", destination)?; - write!(fmt, "{:?}(", func)?; + write!(fmt, "{destination:?} = ")?; + write!(fmt, "{func:?}(")?; for (index, arg) in args.iter().enumerate() { if index > 0 { write!(fmt, ", ")?; } - write!(fmt, "{:?}", arg)?; + write!(fmt, "{arg:?}")?; } write!(fmt, ")") } @@ -331,7 +331,7 @@ impl<'tcx> TerminatorKind<'tcx> { if !expected { write!(fmt, "!")?; } - write!(fmt, "{:?}, ", cond)?; + write!(fmt, "{cond:?}, ")?; msg.fmt_assert_args(fmt)?; write!(fmt, ")") } @@ -344,7 +344,7 @@ impl<'tcx> TerminatorKind<'tcx> { let print_late = |&late| if late { "late" } else { "" }; match op { InlineAsmOperand::In { reg, value } => { - write!(fmt, "in({}) {:?}", reg, value)?; + write!(fmt, "in({reg}) {value:?}")?; } InlineAsmOperand::Out { reg, late, place: Some(place) } => { write!(fmt, "{}out({}) {:?}", print_late(late), reg, place)?; @@ -371,17 +371,17 @@ impl<'tcx> TerminatorKind<'tcx> { write!(fmt, "in{}out({}) {:?} => _", print_late(late), reg, in_value)?; } InlineAsmOperand::Const { value } => { - write!(fmt, "const {:?}", value)?; + write!(fmt, "const {value:?}")?; } InlineAsmOperand::SymFn { value } => { - write!(fmt, "sym_fn {:?}", value)?; + write!(fmt, "sym_fn {value:?}")?; } InlineAsmOperand::SymStatic { def_id } => { - write!(fmt, "sym_static {:?}", def_id)?; + write!(fmt, "sym_static {def_id:?}")?; } } } - write!(fmt, ", options({:?}))", options) + write!(fmt, ", options({options:?}))") } } } diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index b36f0df78f129..cfb2715bda58b 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -1277,7 +1277,7 @@ rustc_queries! { query vtable_allocation(key: (Ty<'tcx>, Option>)) -> mir::interpret::AllocId { desc { |tcx| "vtable const allocation for <{} as {}>", key.0, - key.1.map(|trait_ref| format!("{}", trait_ref)).unwrap_or("_".to_owned()) + key.1.map(|trait_ref| format!("{trait_ref}")).unwrap_or("_".to_owned()) } } diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index e070b05472023..8e2e71fd87984 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -659,7 +659,7 @@ impl<'tcx> Pat<'tcx> { impl<'tcx> IntoDiagnosticArg for Pat<'tcx> { fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { - format!("{}", self).into_diagnostic_arg() + format!("{self}").into_diagnostic_arg() } } @@ -789,7 +789,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> { match self.kind { PatKind::Wild => write!(f, "_"), - PatKind::AscribeUserType { ref subpattern, .. } => write!(f, "{}: _", subpattern), + PatKind::AscribeUserType { ref subpattern, .. } => write!(f, "{subpattern}: _"), PatKind::Binding { mutability, name, mode, ref subpattern, .. } => { let is_mut = match mode { BindingMode::ByValue => mutability == Mutability::Mut, @@ -801,9 +801,9 @@ impl<'tcx> fmt::Display for Pat<'tcx> { if is_mut { write!(f, "mut ")?; } - write!(f, "{}", name)?; + write!(f, "{name}")?; if let Some(ref subpattern) = *subpattern { - write!(f, " @ {}", subpattern)?; + write!(f, " @ {subpattern}")?; } Ok(()) } @@ -833,7 +833,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> { }; if let Some((variant, name)) = &variant_and_name { - write!(f, "{}", name)?; + write!(f, "{name}")?; // Only for Adt we can have `S {...}`, // which we handle separately here. @@ -893,13 +893,13 @@ impl<'tcx> fmt::Display for Pat<'tcx> { } _ => bug!("{} is a bad Deref pattern type", self.ty), } - write!(f, "{}", subpattern) + write!(f, "{subpattern}") } - PatKind::Constant { value } => write!(f, "{}", value), + PatKind::Constant { value } => write!(f, "{value}"), PatKind::Range(box PatRange { lo, hi, end }) => { - write!(f, "{}", lo)?; - write!(f, "{}", end)?; - write!(f, "{}", hi) + write!(f, "{lo}")?; + write!(f, "{end}")?; + write!(f, "{hi}") } PatKind::Slice { ref prefix, ref slice, ref suffix } | PatKind::Array { ref prefix, ref slice, ref suffix } => { @@ -911,7 +911,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> { write!(f, "{}", start_or_comma())?; match slice.kind { PatKind::Wild => {} - _ => write!(f, "{}", slice)?, + _ => write!(f, "{slice}")?, } write!(f, "..")?; } diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index b7ffed57a0be0..ff551de6f6fbe 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -795,49 +795,48 @@ impl ObjectSafetyViolation { "where clause cannot reference non-lifetime `for<...>` variables".into() } ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => { - format!("associated function `{}` has no `self` parameter", name).into() + format!("associated function `{name}` has no `self` parameter").into() } ObjectSafetyViolation::Method( name, MethodViolationCode::ReferencesSelfInput(_), DUMMY_SP, - ) => format!("method `{}` references the `Self` type in its parameters", name).into(), + ) => format!("method `{name}` references the `Self` type in its parameters").into(), ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => { - format!("method `{}` references the `Self` type in this parameter", name).into() + format!("method `{name}` references the `Self` type in this parameter").into() } ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => { - format!("method `{}` references the `Self` type in its return type", name).into() + format!("method `{name}` references the `Self` type in its return type").into() } ObjectSafetyViolation::Method( name, MethodViolationCode::ReferencesImplTraitInTrait(_), _, - ) => format!("method `{}` references an `impl Trait` type in its return type", name) - .into(), + ) => { + format!("method `{name}` references an `impl Trait` type in its return type").into() + } ObjectSafetyViolation::Method(name, MethodViolationCode::AsyncFn, _) => { - format!("method `{}` is `async`", name).into() + format!("method `{name}` is `async`").into() } ObjectSafetyViolation::Method( name, MethodViolationCode::WhereClauseReferencesSelf, _, - ) => { - format!("method `{}` references the `Self` type in its `where` clause", name).into() - } + ) => format!("method `{name}` references the `Self` type in its `where` clause").into(), ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => { - format!("method `{}` has generic type parameters", name).into() + format!("method `{name}` has generic type parameters").into() } ObjectSafetyViolation::Method( name, MethodViolationCode::UndispatchableReceiver(_), _, - ) => format!("method `{}`'s `self` parameter cannot be dispatched on", name).into(), + ) => format!("method `{name}`'s `self` parameter cannot be dispatched on").into(), ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => { - format!("it contains associated `const` `{}`", name).into() + format!("it contains associated `const` `{name}`").into() } ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(), ObjectSafetyViolation::GAT(name, _) => { - format!("it contains the generic associated type `{}`", name).into() + format!("it contains the generic associated type `{name}`").into() } } } @@ -855,8 +854,7 @@ impl ObjectSafetyViolation { err.span_suggestion( add_self_sugg.1, format!( - "consider turning `{}` into a method by giving it a `&self` argument", - name + "consider turning `{name}` into a method by giving it a `&self` argument" ), add_self_sugg.0.to_string(), Applicability::MaybeIncorrect, @@ -864,9 +862,8 @@ impl ObjectSafetyViolation { err.span_suggestion( make_sized_sugg.1, format!( - "alternatively, consider constraining `{}` so it does not apply to \ - trait objects", - name + "alternatively, consider constraining `{name}` so it does not apply to \ + trait objects" ), make_sized_sugg.0.to_string(), Applicability::MaybeIncorrect, @@ -879,7 +876,7 @@ impl ObjectSafetyViolation { ) => { err.span_suggestion( *span, - format!("consider changing method `{}`'s `self` parameter to be `&self`", name), + format!("consider changing method `{name}`'s `self` parameter to be `&self`"), "&Self", Applicability::MachineApplicable, ); @@ -887,7 +884,7 @@ impl ObjectSafetyViolation { ObjectSafetyViolation::AssocConst(name, _) | ObjectSafetyViolation::GAT(name, _) | ObjectSafetyViolation::Method(name, ..) => { - err.help(format!("consider moving `{}` to another trait", name)); + err.help(format!("consider moving `{name}` to another trait")); } } } diff --git a/compiler/rustc_middle/src/traits/solve/inspect/format.rs b/compiler/rustc_middle/src/traits/solve/inspect/format.rs index d0d2080b6a160..0a8322a611c09 100644 --- a/compiler/rustc_middle/src/traits/solve/inspect/format.rs +++ b/compiler/rustc_middle/src/traits/solve/inspect/format.rs @@ -68,7 +68,7 @@ impl<'a, 'b> ProofTreeFormatter<'a, 'b> { writeln!(self.f, "NESTED GOALS ADDED TO CALLER: [")?; self.nested(|this| { for goal in goal.returned_goals.iter() { - writeln!(this.f, "ADDED GOAL: {:?},", goal)?; + writeln!(this.f, "ADDED GOAL: {goal:?},")?; } Ok(()) })?; @@ -101,7 +101,7 @@ impl<'a, 'b> ProofTreeFormatter<'a, 'b> { writeln!(self.f, "NORMALIZING SELF TY FOR ASSEMBLY:") } CandidateKind::Candidate { name, result } => { - writeln!(self.f, "CANDIDATE {}: {:?}", name, result) + writeln!(self.f, "CANDIDATE {name}: {result:?}") } }?; diff --git a/compiler/rustc_middle/src/traits/specialization_graph.rs b/compiler/rustc_middle/src/traits/specialization_graph.rs index 18a57b6181a9e..e48b46d12c48a 100644 --- a/compiler/rustc_middle/src/traits/specialization_graph.rs +++ b/compiler/rustc_middle/src/traits/specialization_graph.rs @@ -43,7 +43,7 @@ impl Graph { /// The parent of a given impl, which is the `DefId` of the trait when the /// impl is a "specialization root". pub fn parent(&self, child: DefId) -> DefId { - *self.parent.get(&child).unwrap_or_else(|| panic!("Failed to get parent for {:?}", child)) + *self.parent.get(&child).unwrap_or_else(|| panic!("Failed to get parent for {child:?}")) } } diff --git a/compiler/rustc_middle/src/traits/structural_impls.rs b/compiler/rustc_middle/src/traits/structural_impls.rs index e2cd118500b65..df81afd595280 100644 --- a/compiler/rustc_middle/src/traits/structural_impls.rs +++ b/compiler/rustc_middle/src/traits/structural_impls.rs @@ -7,17 +7,17 @@ use std::fmt; impl<'tcx, N: fmt::Debug> fmt::Debug for traits::ImplSource<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - super::ImplSource::UserDefined(ref v) => write!(f, "{:?}", v), + super::ImplSource::UserDefined(ref v) => write!(f, "{v:?}"), - super::ImplSource::Builtin(ref d) => write!(f, "{:?}", d), + super::ImplSource::Builtin(ref d) => write!(f, "{d:?}"), - super::ImplSource::Object(ref d) => write!(f, "{:?}", d), + super::ImplSource::Object(ref d) => write!(f, "{d:?}"), super::ImplSource::Param(ref n, ct) => { - write!(f, "ImplSourceParamData({:?}, {:?})", n, ct) + write!(f, "ImplSourceParamData({n:?}, {ct:?})") } - super::ImplSource::TraitUpcasting(ref d) => write!(f, "{:?}", d), + super::ImplSource::TraitUpcasting(ref d) => write!(f, "{d:?}"), } } } diff --git a/compiler/rustc_middle/src/ty/closure.rs b/compiler/rustc_middle/src/ty/closure.rs index 91eefa2c1251f..42f2260497555 100644 --- a/compiler/rustc_middle/src/ty/closure.rs +++ b/compiler/rustc_middle/src/ty/closure.rs @@ -348,7 +348,7 @@ pub fn place_to_string_for_capture<'tcx>(tcx: TyCtxt<'tcx>, place: &HirPlace<'tc for (i, proj) in place.projections.iter().enumerate() { match proj.kind { HirProjectionKind::Deref => { - curr_string = format!("*{}", curr_string); + curr_string = format!("*{curr_string}"); } HirProjectionKind::Field(idx, variant) => match place.ty_before_projection(i).kind() { ty::Adt(def, ..) => { diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index 4ef70107f194a..cce10417e1b0c 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -212,7 +212,7 @@ impl<'tcx> Const<'tcx> { Err(e) => { tcx.sess.delay_span_bug( expr.span, - format!("Const::from_anon_const: couldn't lit_to_const {:?}", e), + format!("Const::from_anon_const: couldn't lit_to_const {e:?}"), ); } } @@ -267,7 +267,7 @@ impl<'tcx> Const<'tcx> { pub fn from_bits(tcx: TyCtxt<'tcx>, bits: u128, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> Self { let size = tcx .layout_of(ty) - .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e)) + .unwrap_or_else(|e| panic!("could not compute layout for {ty:?}: {e:?}")) .size; ty::Const::new_value( tcx, diff --git a/compiler/rustc_middle/src/ty/consts/int.rs b/compiler/rustc_middle/src/ty/consts/int.rs index 624195cfb282b..b16163edf1448 100644 --- a/compiler/rustc_middle/src/ty/consts/int.rs +++ b/compiler/rustc_middle/src/ty/consts/int.rs @@ -463,7 +463,7 @@ impl TryFrom for Double { impl fmt::Debug for ScalarInt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Dispatch to LowerHex below. - write!(f, "0x{:x}", self) + write!(f, "0x{self:x}") } } diff --git a/compiler/rustc_middle/src/ty/consts/kind.rs b/compiler/rustc_middle/src/ty/consts/kind.rs index 6c76075c214dd..db4a15fbee538 100644 --- a/compiler/rustc_middle/src/ty/consts/kind.rs +++ b/compiler/rustc_middle/src/ty/consts/kind.rs @@ -17,7 +17,7 @@ pub struct UnevaluatedConst<'tcx> { impl rustc_errors::IntoDiagnosticArg for UnevaluatedConst<'_> { fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> { - format!("{:?}", self).into_diagnostic_arg() + format!("{self:?}").into_diagnostic_arg() } } diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index 905e855896e42..8570f83dcc66b 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -126,7 +126,7 @@ pub fn suggest_arbitrary_trait_bound<'tcx>( if constraint.ends_with('>') { constraint = format!("{}, {} = {}>", &constraint[..constraint.len() - 1], name, term); } else { - constraint.push_str(&format!("<{} = {}>", name, term)); + constraint.push_str(&format!("<{name} = {term}>")); } } @@ -274,9 +274,9 @@ pub fn suggest_constraining_type_params<'a>( if span_to_replace.is_some() { constraint.clone() } else if bound_list_non_empty { - format!(" + {}", constraint) + format!(" + {constraint}") } else { - format!(" {}", constraint) + format!(" {constraint}") }, SuggestChangingConstraintsMessage::RestrictBoundFurther, )) @@ -337,7 +337,7 @@ pub fn suggest_constraining_type_params<'a>( generics.tail_span_for_predicate_suggestion(), constraints .iter() - .map(|&(constraint, _)| format!(", {}: {}", param_name, constraint)) + .map(|&(constraint, _)| format!(", {param_name}: {constraint}")) .collect::(), SuggestChangingConstraintsMessage::RestrictTypeFurther { ty: param_name }, )); @@ -358,7 +358,7 @@ pub fn suggest_constraining_type_params<'a>( // default (``), so we suggest adding `where T: Bar`. suggestions.push(( generics.tail_span_for_predicate_suggestion(), - format!(" where {}: {}", param_name, constraint), + format!(" where {param_name}: {constraint}"), SuggestChangingConstraintsMessage::RestrictTypeFurther { ty: param_name }, )); continue; @@ -371,7 +371,7 @@ pub fn suggest_constraining_type_params<'a>( if let Some(colon_span) = param.colon_span { suggestions.push(( colon_span.shrink_to_hi(), - format!(" {}", constraint), + format!(" {constraint}"), SuggestChangingConstraintsMessage::RestrictType { ty: param_name }, )); continue; @@ -383,7 +383,7 @@ pub fn suggest_constraining_type_params<'a>( // - help: consider restricting this type parameter with `T: Foo` suggestions.push(( param.span.shrink_to_hi(), - format!(": {}", constraint), + format!(": {constraint}"), SuggestChangingConstraintsMessage::RestrictType { ty: param_name }, )); } @@ -401,10 +401,10 @@ pub fn suggest_constraining_type_params<'a>( Cow::from("consider further restricting this bound") } SuggestChangingConstraintsMessage::RestrictType { ty } => { - Cow::from(format!("consider restricting type parameter `{}`", ty)) + Cow::from(format!("consider restricting type parameter `{ty}`")) } SuggestChangingConstraintsMessage::RestrictTypeFurther { ty } => { - Cow::from(format!("consider further restricting type parameter `{}`", ty)) + Cow::from(format!("consider further restricting type parameter `{ty}`")) } SuggestChangingConstraintsMessage::RemoveMaybeUnsized => { Cow::from("consider removing the `?Sized` bound to make the type parameter `Sized`") diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index c794c3faded11..d6feb38ded691 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -90,9 +90,9 @@ impl<'tcx> TypeError<'tcx> { // A naive approach to making sure that we're not reporting silly errors such as: // (expected closure, found closure). if expected == found { - format!("expected {}, found a different {}", expected, found) + format!("expected {expected}, found a different {found}") } else { - format!("expected {}, found {}", expected, found) + format!("expected {expected}, found {found}") } } @@ -131,7 +131,7 @@ impl<'tcx> TypeError<'tcx> { ) .into(), ArgCount => "incorrect number of function parameters".into(), - FieldMisMatch(adt, field) => format!("field type mismatch: {}.{}", adt, field).into(), + FieldMisMatch(adt, field) => format!("field type mismatch: {adt}.{field}").into(), RegionsDoesNotOutlive(..) => "lifetime mismatch".into(), // Actually naming the region here is a bit confusing because context is lacking RegionsInsufficientlyPolymorphic(..) => { @@ -164,7 +164,7 @@ impl<'tcx> TypeError<'tcx> { ty::IntVarValue::IntType(ty) => ty.name_str(), ty::IntVarValue::UintType(ty) => ty.name_str(), }; - format!("expected `{}`, found `{}`", expected, found).into() + format!("expected `{expected}`, found `{found}`").into() } FloatMismatch(ref values) => format!( "expected `{}`, found `{}`", diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index 48e88daa89073..8913bf76d347a 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -308,13 +308,13 @@ fn fmt_instance( InstanceDef::ReifyShim(_) => write!(f, " - shim(reify)"), InstanceDef::ThreadLocalShim(_) => write!(f, " - shim(tls)"), InstanceDef::Intrinsic(_) => write!(f, " - intrinsic"), - InstanceDef::Virtual(_, num) => write!(f, " - virtual#{}", num), - InstanceDef::FnPtrShim(_, ty) => write!(f, " - shim({})", ty), + InstanceDef::Virtual(_, num) => write!(f, " - virtual#{num}"), + InstanceDef::FnPtrShim(_, ty) => write!(f, " - shim({ty})"), InstanceDef::ClosureOnceShim { .. } => write!(f, " - shim"), InstanceDef::DropGlue(_, None) => write!(f, " - shim(None)"), - InstanceDef::DropGlue(_, Some(ty)) => write!(f, " - shim(Some({}))", ty), - InstanceDef::CloneShim(_, ty) => write!(f, " - shim({})", ty), - InstanceDef::FnPtrAddrShim(_, ty) => write!(f, " - shim({})", ty), + InstanceDef::DropGlue(_, Some(ty)) => write!(f, " - shim(Some({ty}))"), + InstanceDef::CloneShim(_, ty) => write!(f, " - shim({ty})"), + InstanceDef::FnPtrAddrShim(_, ty) => write!(f, " - shim({ty})"), } } @@ -336,9 +336,7 @@ impl<'tcx> Instance<'tcx> { pub fn new(def_id: DefId, args: GenericArgsRef<'tcx>) -> Instance<'tcx> { assert!( !args.has_escaping_bound_vars(), - "args of instance {:?} not normalized for codegen: {:?}", - def_id, - args + "args of instance {def_id:?} not normalized for codegen: {args:?}" ); Instance { def: InstanceDef::Item(def_id), args } } @@ -425,7 +423,7 @@ impl<'tcx> Instance<'tcx> { ) -> Option> { debug!("resolve(def_id={:?}, args={:?})", def_id, args); // Use either `resolve_closure` or `resolve_for_vtable` - assert!(!tcx.is_closure(def_id), "Called `resolve_for_fn_ptr` on closure: {:?}", def_id); + assert!(!tcx.is_closure(def_id), "Called `resolve_for_fn_ptr` on closure: {def_id:?}"); Instance::resolve(tcx, param_env, def_id, args).ok().flatten().map(|mut resolved| { match resolved.def { InstanceDef::Item(def) if resolved.def.requires_caller_location(tcx) => { diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 62805d1e8b5c9..2f5d376c70009 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -246,9 +246,9 @@ impl<'tcx> LayoutError<'tcx> { impl<'tcx> fmt::Display for LayoutError<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - LayoutError::Unknown(ty) => write!(f, "the type `{}` has an unknown layout", ty), + LayoutError::Unknown(ty) => write!(f, "the type `{ty}` has an unknown layout"), LayoutError::SizeOverflow(ty) => { - write!(f, "values of the type `{}` are too big for the current architecture", ty) + write!(f, "values of the type `{ty}` are too big for the current architecture") } LayoutError::NormalizationFailure(t, e) => write!( f, diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 0411890ab5139..26e48023a4f1f 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -980,9 +980,9 @@ pub struct Term<'tcx> { impl Debug for Term<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let data = if let Some(ty) = self.ty() { - format!("Term::Ty({:?})", ty) + format!("Term::Ty({ty:?})") } else if let Some(ct) = self.ct() { - format!("Term::Ct({:?})", ct) + format!("Term::Ct({ct:?})") } else { unreachable!() }; diff --git a/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs b/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs index 3c2c4483c7356..2415d50b2784a 100644 --- a/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs +++ b/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs @@ -20,8 +20,8 @@ pub enum NormalizationError<'tcx> { impl<'tcx> NormalizationError<'tcx> { pub fn get_type_for_failure(&self) -> String { match self { - NormalizationError::Type(t) => format!("{}", t), - NormalizationError::Const(c) => format!("{}", c), + NormalizationError::Type(t) => format!("{t}"), + NormalizationError::Const(c) => format!("{c}"), } } } diff --git a/compiler/rustc_middle/src/ty/opaque_types.rs b/compiler/rustc_middle/src/ty/opaque_types.rs index 7ae8be2dab398..0ff5ac9030426 100644 --- a/compiler/rustc_middle/src/ty/opaque_types.rs +++ b/compiler/rustc_middle/src/ty/opaque_types.rs @@ -124,7 +124,7 @@ impl<'tcx> TypeFolder> for ReverseMapper<'tcx> { match self.map.get(&r.into()).map(|k| k.unpack()) { Some(GenericArgKind::Lifetime(r1)) => r1, - Some(u) => panic!("region mapped to unexpected kind: {:?}", u), + Some(u) => panic!("region mapped to unexpected kind: {u:?}"), None if self.do_not_error => self.tcx.lifetimes.re_static, None => { let e = self @@ -134,9 +134,8 @@ impl<'tcx> TypeFolder> for ReverseMapper<'tcx> { .span_label( self.span, format!( - "lifetime `{}` is part of concrete type but not used in \ - parameter list of the `impl Trait` type alias", - r + "lifetime `{r}` is part of concrete type but not used in \ + parameter list of the `impl Trait` type alias" ), ) .emit(); @@ -169,7 +168,7 @@ impl<'tcx> TypeFolder> for ReverseMapper<'tcx> { // Found it in the substitution list; replace with the parameter from the // opaque type. Some(GenericArgKind::Type(t1)) => t1, - Some(u) => panic!("type mapped to unexpected kind: {:?}", u), + Some(u) => panic!("type mapped to unexpected kind: {u:?}"), None => { debug!(?param, ?self.map); if !self.ignore_errors { @@ -178,9 +177,8 @@ impl<'tcx> TypeFolder> for ReverseMapper<'tcx> { .struct_span_err( self.span, format!( - "type parameter `{}` is part of concrete type but not \ - used in parameter list for the `impl Trait` type alias", - ty + "type parameter `{ty}` is part of concrete type but not \ + used in parameter list for the `impl Trait` type alias" ), ) .emit(); @@ -205,7 +203,7 @@ impl<'tcx> TypeFolder> for ReverseMapper<'tcx> { // Found it in the substitution list, replace with the parameter from the // opaque type. Some(GenericArgKind::Const(c1)) => c1, - Some(u) => panic!("const mapped to unexpected kind: {:?}", u), + Some(u) => panic!("const mapped to unexpected kind: {u:?}"), None => { let guar = self .tcx diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index e5633223464a5..e999677eb8dd8 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -1497,7 +1497,7 @@ pub trait PrettyPrinter<'tcx>: let data = int.assert_bits(self.tcx().data_layout.pointer_size); self = self.typed_value( |mut this| { - write!(this, "0x{:x}", data)?; + write!(this, "0x{data:x}")?; Ok(this) }, |this| this.print_type(ty), @@ -1510,7 +1510,7 @@ pub trait PrettyPrinter<'tcx>: if int.size() == Size::ZERO { write!(this, "transmute(())")?; } else { - write!(this, "transmute(0x{:x})", int)?; + write!(this, "transmute(0x{int:x})")?; } Ok(this) }; @@ -2348,10 +2348,10 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { } else { cont }; - let _ = write!(cx, "{}", w); + let _ = write!(cx, "{w}"); }; let do_continue = |cx: &mut Self, cont: Symbol| { - let _ = write!(cx, "{}", cont); + let _ = write!(cx, "{cont}"); }; define_scoped_cx!(self); @@ -2387,7 +2387,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { let (new_value, map) = if self.should_print_verbose() { for var in value.bound_vars().iter() { start_or_continue(&mut self, "for<", ", "); - write!(self, "{:?}", var)?; + write!(self, "{var:?}")?; } start_or_continue(&mut self, "", "> "); (value.clone().skip_binder(), BTreeMap::default()) diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 9d380a58d9fa3..28d216cfe5c45 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -73,9 +73,9 @@ impl fmt::Debug for ty::BoundRegionKind { ty::BrAnon(span) => write!(f, "BrAnon({span:?})"), ty::BrNamed(did, name) => { if did.is_crate_root() { - write!(f, "BrNamed({})", name) + write!(f, "BrNamed({name})") } else { - write!(f, "BrNamed({:?}, {})", did, name) + write!(f, "BrNamed({did:?}, {name})") } } ty::BrEnv => write!(f, "BrEnv"), @@ -205,7 +205,7 @@ impl<'tcx> fmt::Debug for ty::ClauseKind<'tcx> { ty::ClauseKind::RegionOutlives(ref pair) => pair.fmt(f), ty::ClauseKind::TypeOutlives(ref pair) => pair.fmt(f), ty::ClauseKind::Projection(ref pair) => pair.fmt(f), - ty::ClauseKind::WellFormed(ref data) => write!(f, "WellFormed({:?})", data), + ty::ClauseKind::WellFormed(ref data) => write!(f, "WellFormed({data:?})"), ty::ClauseKind::ConstEvaluatable(ct) => { write!(f, "ConstEvaluatable({ct:?})") } @@ -220,12 +220,12 @@ impl<'tcx> fmt::Debug for ty::PredicateKind<'tcx> { ty::PredicateKind::Subtype(ref pair) => pair.fmt(f), ty::PredicateKind::Coerce(ref pair) => pair.fmt(f), ty::PredicateKind::ObjectSafe(trait_def_id) => { - write!(f, "ObjectSafe({:?})", trait_def_id) + write!(f, "ObjectSafe({trait_def_id:?})") } ty::PredicateKind::ClosureKind(closure_def_id, closure_args, kind) => { - write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_args, kind) + write!(f, "ClosureKind({closure_def_id:?}, {closure_args:?}, {kind:?})") } - ty::PredicateKind::ConstEquate(c1, c2) => write!(f, "ConstEquate({:?}, {:?})", c1, c2), + ty::PredicateKind::ConstEquate(c1, c2) => write!(f, "ConstEquate({c1:?}, {c2:?})"), ty::PredicateKind::Ambiguous => write!(f, "Ambiguous"), ty::PredicateKind::AliasRelate(t1, t2, dir) => { write!(f, "AliasRelate({t1:?}, {dir:?}, {t2:?})") diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 553b76cad4ed7..90ecc8aa85781 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -57,7 +57,7 @@ impl<'tcx> fmt::Display for Discr<'tcx> { let x = self.val; // sign extend the raw representation to be an i128 let x = size.sign_extend(x) as i128; - write!(fmt, "{}", x) + write!(fmt, "{x}") } _ => write!(fmt, "{}", self.val), } diff --git a/compiler/rustc_middle/src/ty/vtable.rs b/compiler/rustc_middle/src/ty/vtable.rs index 443791d0af4ba..97402caa0013b 100644 --- a/compiler/rustc_middle/src/ty/vtable.rs +++ b/compiler/rustc_middle/src/ty/vtable.rs @@ -29,8 +29,8 @@ impl<'tcx> fmt::Debug for VtblEntry<'tcx> { VtblEntry::MetadataSize => write!(f, "MetadataSize"), VtblEntry::MetadataAlign => write!(f, "MetadataAlign"), VtblEntry::Vacant => write!(f, "Vacant"), - VtblEntry::Method(instance) => write!(f, "Method({})", instance), - VtblEntry::TraitVPtr(trait_ref) => write!(f, "TraitVPtr({})", trait_ref), + VtblEntry::Method(instance) => write!(f, "Method({instance})"), + VtblEntry::TraitVPtr(trait_ref) => write!(f, "TraitVPtr({trait_ref})"), } } } diff --git a/compiler/rustc_middle/src/util/bug.rs b/compiler/rustc_middle/src/util/bug.rs index 43ee0343f5aa6..634ed5ec54ba4 100644 --- a/compiler/rustc_middle/src/util/bug.rs +++ b/compiler/rustc_middle/src/util/bug.rs @@ -29,7 +29,7 @@ fn opt_span_bug_fmt>( location: &Location<'_>, ) -> ! { tls::with_opt(move |tcx| { - let msg = format!("{}: {}", location, args); + let msg = format!("{location}: {args}"); match (tcx, span) { (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, msg), (Some(tcx), None) => tcx.sess.diagnostic().bug(msg), diff --git a/compiler/rustc_middle/src/util/common.rs b/compiler/rustc_middle/src/util/common.rs index 08977049db02d..df101a2f6e4c6 100644 --- a/compiler/rustc_middle/src/util/common.rs +++ b/compiler/rustc_middle/src/util/common.rs @@ -17,7 +17,7 @@ pub fn to_readable_str(mut val: usize) -> String { groups.push(group.to_string()); break; } else { - groups.push(format!("{:03}", group)); + groups.push(format!("{group:03}")); } } diff --git a/compiler/rustc_mir_build/src/build/custom/parse.rs b/compiler/rustc_mir_build/src/build/custom/parse.rs index c494929cbff58..60c4a041696bc 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse.rs +++ b/compiler/rustc_mir_build/src/build/custom/parse.rs @@ -74,7 +74,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { kind @ StmtKind::Let { pattern, .. } => { return Err(ParseError { span: pattern.span, - item_description: format!("{:?}", kind), + item_description: format!("{kind:?}"), expected: "expression".to_string(), }); } diff --git a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs index 7817c3d0d8090..3220a184d49ba 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs @@ -774,8 +774,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Not in a closure debug_assert!( local == ty::CAPTURE_STRUCT_LOCAL, - "Expected local to be Local(1), found {:?}", - local + "Expected local to be Local(1), found {local:?}" ); // Not in a closure debug_assert!( diff --git a/compiler/rustc_mir_build/src/build/matches/mod.rs b/compiler/rustc_mir_build/src/build/matches/mod.rs index 6f14891cb7865..ed3ac7cb3ec7d 100644 --- a/compiler/rustc_mir_build/src/build/matches/mod.rs +++ b/compiler/rustc_mir_build/src/build/matches/mod.rs @@ -1627,9 +1627,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // at least the first candidate ought to be tested assert!( total_candidate_count > candidates.len(), - "{}, {:#?}", - total_candidate_count, - candidates + "{total_candidate_count}, {candidates:#?}" ); debug!("tested_candidates: {}", total_candidate_count - candidates.len()); debug!("untested_candidates: {}", candidates.len()); diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/build/matches/test.rs index 275878a39195b..484e8490919d4 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/build/matches/test.rs @@ -175,16 +175,14 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { debug_assert_ne!( target_blocks[idx.index()], otherwise_block, - "no candidates for tested discriminant: {:?}", - discr, + "no candidates for tested discriminant: {discr:?}", ); Some((discr.val, target_blocks[idx.index()])) } else { debug_assert_eq!( target_blocks[idx.index()], otherwise_block, - "found candidates for untested discriminant: {:?}", - discr, + "found candidates for untested discriminant: {discr:?}", ); None } diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index 17295fe1d344a..1ae8031ef3c56 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -94,8 +94,7 @@ fn mir_build(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> { || body.basic_blocks.has_free_regions() || body.var_debug_info.has_free_regions() || body.yield_ty().has_free_regions()), - "Unexpected free regions in MIR: {:?}", - body, + "Unexpected free regions in MIR: {body:?}", ); body @@ -977,9 +976,9 @@ pub(crate) fn parse_float_into_scalar( match float_ty { ty::FloatTy::F32 => { let Ok(rust_f) = num.parse::() else { return None }; - let mut f = num.parse::().unwrap_or_else(|e| { - panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e) - }); + let mut f = num + .parse::() + .unwrap_or_else(|e| panic!("apfloat::ieee::Single failed to parse `{num}`: {e:?}")); assert!( u128::from(rust_f.to_bits()) == f.to_bits(), @@ -1000,9 +999,9 @@ pub(crate) fn parse_float_into_scalar( } ty::FloatTy::F64 => { let Ok(rust_f) = num.parse::() else { return None }; - let mut f = num.parse::().unwrap_or_else(|e| { - panic!("apfloat::ieee::Double failed to parse `{}`: {:?}", num, e) - }); + let mut f = num + .parse::() + .unwrap_or_else(|e| panic!("apfloat::ieee::Double failed to parse `{num}`: {e:?}")); assert!( u128::from(rust_f.to_bits()) == f.to_bits(), diff --git a/compiler/rustc_mir_build/src/errors.rs b/compiler/rustc_mir_build/src/errors.rs index 820ab93851e7b..3ff3387a78114 100644 --- a/compiler/rustc_mir_build/src/errors.rs +++ b/compiler/rustc_mir_build/src/errors.rs @@ -454,17 +454,13 @@ impl<'a> IntoDiagnostic<'a> for NonExhaustivePatternsTypeNotEmpty<'_, '_, '_> { if self.span.eq_ctxt(self.expr_span) { // Get the span for the empty match body `{}`. let (indentation, more) = if let Some(snippet) = sm.indentation_before(self.span) { - (format!("\n{}", snippet), " ") + (format!("\n{snippet}"), " ") } else { (" ".to_string(), "") }; suggestion = Some(( self.span.shrink_to_hi().with_hi(self.expr_span.hi()), - format!( - " {{{indentation}{more}_ => todo!(),{indentation}}}", - indentation = indentation, - more = more, - ), + format!(" {{{indentation}{more}_ => todo!(),{indentation}}}",), )); } diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 711a9126c04a3..ff4620948fa1f 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -229,9 +229,7 @@ impl<'tcx> Cx<'tcx> { let param_env_ty = self.param_env.and(discr_ty); let size = tcx .layout_of(param_env_ty) - .unwrap_or_else(|e| { - panic!("could not compute layout for {:?}: {:?}", param_env_ty, e) - }) + .unwrap_or_else(|e| panic!("could not compute layout for {param_env_ty:?}: {e:?}")) .size; let lit = ScalarInt::try_from_uint(discr_offset as u128, size).unwrap(); diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index 38c866c50a2ff..a786e65966423 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -691,7 +691,7 @@ fn non_exhaustive_match<'p, 'tcx>( err = create_e0004( cx.tcx.sess, sp, - format!("non-exhaustive patterns: {} not covered", joined_patterns), + format!("non-exhaustive patterns: {joined_patterns} not covered"), ); err.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns)); patterns_len = witnesses.len(); @@ -721,15 +721,13 @@ fn non_exhaustive_match<'p, 'tcx>( && matches!(witnesses[0].ctor(), Constructor::NonExhaustive) { err.note(format!( - "`{}` does not have a fixed maximum value, so a wildcard `_` is necessary to match \ + "`{scrut_ty}` does not have a fixed maximum value, so a wildcard `_` is necessary to match \ exhaustively", - scrut_ty, )); if cx.tcx.sess.is_nightly_build() { err.help(format!( "add `#![feature(precise_pointer_size_matching)]` to the crate attributes to \ - enable precise `{}` matching", - scrut_ty, + enable precise `{scrut_ty}` matching", )); } } @@ -745,18 +743,13 @@ fn non_exhaustive_match<'p, 'tcx>( [] if sp.eq_ctxt(expr_span) => { // Get the span for the empty match body `{}`. let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) { - (format!("\n{}", snippet), " ") + (format!("\n{snippet}"), " ") } else { (" ".to_string(), "") }; suggestion = Some(( sp.shrink_to_hi().with_hi(expr_span.hi()), - format!( - " {{{indentation}{more}{pattern} => todo!(),{indentation}}}", - indentation = indentation, - more = more, - pattern = pattern, - ), + format!(" {{{indentation}{more}{pattern} => todo!(),{indentation}}}",), )); } [only] => { @@ -765,7 +758,7 @@ fn non_exhaustive_match<'p, 'tcx>( && let Ok(with_trailing) = sm.span_extend_while(only.span, |c| c.is_whitespace() || c == ',') && sm.is_multiline(with_trailing) { - (format!("\n{}", snippet), true) + (format!("\n{snippet}"), true) } else { (" ".to_string(), false) }; @@ -780,7 +773,7 @@ fn non_exhaustive_match<'p, 'tcx>( }; suggestion = Some(( only.span.shrink_to_hi(), - format!("{}{}{} => todo!()", comma, pre_indentation, pattern), + format!("{comma}{pre_indentation}{pattern} => todo!()"), )); } [.., prev, last] => { @@ -803,7 +796,7 @@ fn non_exhaustive_match<'p, 'tcx>( if let Some(spacing) = spacing { suggestion = Some(( last.span.shrink_to_hi(), - format!("{}{}{} => todo!()", comma, spacing, pattern), + format!("{comma}{spacing}{pattern} => todo!()"), )); } } @@ -900,7 +893,7 @@ fn adt_defined_here<'p, 'tcx>( for pat in spans { span.push_span_label(pat, "not covered"); } - err.span_note(span, format!("`{}` defined here", ty)); + err.span_note(span, format!("`{ty}` defined here")); } } diff --git a/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs index 4228597cdc957..bee1c4e4614f4 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs @@ -306,9 +306,9 @@ impl fmt::Debug for IntRange { let (lo, hi) = self.boundaries(); let bias = self.bias; let (lo, hi) = (lo ^ bias, hi ^ bias); - write!(f, "{}", lo)?; + write!(f, "{lo}")?; write!(f, "{}", RangeEnd::Included)?; - write!(f, "{}", hi) + write!(f, "{hi}") } } @@ -1619,7 +1619,7 @@ impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> { // of `std`). So this branch is only reachable when the feature is enabled and // the pattern is a box pattern. let subpattern = self.iter_fields().next().unwrap(); - write!(f, "box {:?}", subpattern) + write!(f, "box {subpattern:?}") } ty::Adt(..) | ty::Tuple(..) => { let variant = match self.ty.kind() { @@ -1638,7 +1638,7 @@ impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> { write!(f, "(")?; for p in self.iter_fields() { write!(f, "{}", start_or_comma())?; - write!(f, "{:?}", p)?; + write!(f, "{p:?}")?; } write!(f, ")") } @@ -1674,11 +1674,11 @@ impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> { write!(f, "]") } &FloatRange(lo, hi, end) => { - write!(f, "{}", lo)?; - write!(f, "{}", end)?; - write!(f, "{}", hi) + write!(f, "{lo}")?; + write!(f, "{end}")?; + write!(f, "{hi}") } - IntRange(range) => write!(f, "{:?}", range), // Best-effort, will render e.g. `false` as `0..=0` + IntRange(range) => write!(f, "{range:?}"), // Best-effort, will render e.g. `false` as `0..=0` Wildcard | Missing { .. } | NonExhaustive => write!(f, "_ : {:?}", self.ty), Or => { for pat in self.iter_fields() { @@ -1686,7 +1686,7 @@ impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> { } Ok(()) } - Str(value) => write!(f, "{}", value), + Str(value) => write!(f, "{value}"), Opaque => write!(f, ""), } } diff --git a/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs b/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs index e5b6350690609..08cfe98bb68b9 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs @@ -459,7 +459,7 @@ impl<'p, 'tcx> fmt::Debug for PatStack<'p, 'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "+")?; for pat in self.iter() { - write!(f, " {:?} +", pat)?; + write!(f, " {pat:?} +")?; } Ok(()) } @@ -530,7 +530,7 @@ impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> { let Matrix { patterns: m, .. } = self; let pretty_printed_matrix: Vec> = - m.iter().map(|row| row.iter().map(|pat| format!("{:?}", pat)).collect()).collect(); + m.iter().map(|row| row.iter().map(|pat| format!("{pat:?}")).collect()).collect(); let column_count = m.iter().map(|row| row.len()).next().unwrap_or(0); assert!(m.iter().all(|row| row.len() == column_count)); diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index fd6b1dc5c0761..8d78ec0482140 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -1099,10 +1099,10 @@ fn debug_with_context_rec( let info_elem = map.places[child].proj_elem.unwrap(); let child_place_str = match info_elem { TrackElem::Discriminant => { - format!("discriminant({})", place_str) + format!("discriminant({place_str})") } TrackElem::Variant(idx) => { - format!("({} as {:?})", place_str, idx) + format!("({place_str} as {idx:?})") } TrackElem::Field(field) => { if place_str.starts_with('*') { diff --git a/compiler/rustc_mir_transform/src/coverage/counters.rs b/compiler/rustc_mir_transform/src/coverage/counters.rs index 658e01d931031..e9c5f856d35fd 100644 --- a/compiler/rustc_mir_transform/src/coverage/counters.rs +++ b/compiler/rustc_mir_transform/src/coverage/counters.rs @@ -282,7 +282,7 @@ impl<'a> BcbCounters<'a> { branching_counter_operand, Op::Subtract, sumup_counter_operand, - || Some(format!("{:?}", expression_branch)), + || Some(format!("{expression_branch:?}")), ); debug!("{:?} gets an expression: {}", expression_branch, self.format_counter(&expression)); let bcb = expression_branch.target_bcb; @@ -324,7 +324,7 @@ impl<'a> BcbCounters<'a> { // program results in a tight infinite loop, but it should still compile. let one_path_to_target = self.bcb_has_one_path_to_target(bcb); if one_path_to_target || self.bcb_predecessors(bcb).contains(&bcb) { - let counter_kind = self.coverage_counters.make_counter(|| Some(format!("{:?}", bcb))); + let counter_kind = self.coverage_counters.make_counter(|| Some(format!("{bcb:?}"))); if one_path_to_target { debug!( "{}{:?} gets a new counter: {}", @@ -392,7 +392,7 @@ impl<'a> BcbCounters<'a> { first_edge_counter_operand, Op::Add, some_sumup_edge_counter_operand.unwrap(), - || Some(format!("{:?}", bcb)), + || Some(format!("{bcb:?}")), ); debug!( "{}{:?} gets a new counter (sum of predecessor counters): {}", @@ -449,7 +449,7 @@ impl<'a> BcbCounters<'a> { // Make a new counter to count this edge. let counter_kind = - self.coverage_counters.make_counter(|| Some(format!("{:?}->{:?}", from_bcb, to_bcb))); + self.coverage_counters.make_counter(|| Some(format!("{from_bcb:?}->{to_bcb:?}"))); debug!( "{}Edge {:?}->{:?} gets a new counter: {}", NESTED_INDENT.repeat(debug_indent_level), diff --git a/compiler/rustc_mir_transform/src/coverage/debug.rs b/compiler/rustc_mir_transform/src/coverage/debug.rs index 7ad9814415922..c9914eb9f8207 100644 --- a/compiler/rustc_mir_transform/src/coverage/debug.rs +++ b/compiler/rustc_mir_transform/src/coverage/debug.rs @@ -630,7 +630,7 @@ pub(super) fn dump_coverage_spanview<'tcx>( .expect("Unexpected error creating MIR spanview HTML file"); let crate_name = tcx.crate_name(def_id.krate); let item_name = tcx.def_path(def_id).to_filename_friendly_no_crate(); - let title = format!("{}.{} - Coverage Spans", crate_name, item_name); + let title = format!("{crate_name}.{item_name} - Coverage Spans"); spanview::write_document(tcx, body_span, span_viewables, &title, &mut file) .expect("Unexpected IO error dumping coverage spans as HTML"); } @@ -779,7 +779,7 @@ fn bcb_to_string_sections<'tcx>( )); } if let Some(counter_kind) = &bcb_data.counter_kind { - sections.push(format!("{:?}", counter_kind)); + sections.push(format!("{counter_kind:?}")); } let non_term_blocks = bcb_data.basic_blocks[0..len - 1] .iter() diff --git a/compiler/rustc_mir_transform/src/coverage/graph.rs b/compiler/rustc_mir_transform/src/coverage/graph.rs index d2a854b26756d..5d843f4ade095 100644 --- a/compiler/rustc_mir_transform/src/coverage/graph.rs +++ b/compiler/rustc_mir_transform/src/coverage/graph.rs @@ -360,8 +360,7 @@ impl BasicCoverageBlockData { if let Some(replaced) = self.counter_kind.replace(counter_kind) { Error::from_string(format!( "attempt to set a BasicCoverageBlock coverage counter more than once; \ - {:?} already had counter {:?}", - self, replaced, + {self:?} already had counter {replaced:?}", )) } else { Ok(operand) @@ -389,9 +388,8 @@ impl BasicCoverageBlockData { // `BasicCoverageBlock`). if self.counter_kind.as_ref().is_some_and(|c| !c.is_expression()) { return Error::from_string(format!( - "attempt to add an incoming edge counter from {:?} when the target BCB already \ - has a `Counter`", - from_bcb + "attempt to add an incoming edge counter from {from_bcb:?} when the target BCB already \ + has a `Counter`" )); } } @@ -401,8 +399,7 @@ impl BasicCoverageBlockData { { Error::from_string(format!( "attempt to set an edge counter more than once; from_bcb: \ - {:?} already had counter {:?}", - from_bcb, replaced, + {from_bcb:?} already had counter {replaced:?}", )) } else { Ok(operand) @@ -612,7 +609,7 @@ impl TraverseCoverageGraphWithLoops { the {}", successor_to_add, if let Some(loop_header) = some_loop_header { - format!("worklist for the loop headed by {:?}", loop_header) + format!("worklist for the loop headed by {loop_header:?}") } else { String::from("non-loop worklist") }, @@ -623,7 +620,7 @@ impl TraverseCoverageGraphWithLoops { "{:?} successor is non-branching. Defer it to the end of the {}", successor_to_add, if let Some(loop_header) = some_loop_header { - format!("worklist for the loop headed by {:?}", loop_header) + format!("worklist for the loop headed by {loop_header:?}") } else { String::from("non-loop worklist") }, diff --git a/compiler/rustc_mir_transform/src/coverage/test_macros/src/lib.rs b/compiler/rustc_mir_transform/src/coverage/test_macros/src/lib.rs index 3d6095d2738cb..f41adf667ec55 100644 --- a/compiler/rustc_mir_transform/src/coverage/test_macros/src/lib.rs +++ b/compiler/rustc_mir_transform/src/coverage/test_macros/src/lib.rs @@ -2,5 +2,5 @@ use proc_macro::TokenStream; #[proc_macro] pub fn let_bcb(item: TokenStream) -> TokenStream { - format!("let bcb{} = graph::BasicCoverageBlock::from_usize({});", item, item).parse().unwrap() + format!("let bcb{item} = graph::BasicCoverageBlock::from_usize({item});").parse().unwrap() } diff --git a/compiler/rustc_mir_transform/src/elaborate_drops.rs b/compiler/rustc_mir_transform/src/elaborate_drops.rs index d5664e2b40a6f..43757a9ea353e 100644 --- a/compiler/rustc_mir_transform/src/elaborate_drops.rs +++ b/compiler/rustc_mir_transform/src/elaborate_drops.rs @@ -358,8 +358,7 @@ impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> { self.tcx.sess.delay_span_bug( terminator.source_info.span, format!( - "drop of untracked, uninitialized value {:?}, place {:?} ({:?})", - bb, place, path + "drop of untracked, uninitialized value {bb:?}, place {place:?} ({path:?})" ), ); } @@ -424,7 +423,7 @@ impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> { if !replace { self.tcx.sess.delay_span_bug( terminator.source_info.span, - format!("drop of untracked value {:?}", bb), + format!("drop of untracked value {bb:?}"), ); } // A drop and replace behind a pointer/array/whatever. diff --git a/compiler/rustc_mir_transform/src/function_item_references.rs b/compiler/rustc_mir_transform/src/function_item_references.rs index fdf6ab33c82f7..a42eacbf22b42 100644 --- a/compiler/rustc_mir_transform/src/function_item_references.rs +++ b/compiler/rustc_mir_transform/src/function_item_references.rs @@ -168,15 +168,15 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { } }; let ident = self.tcx.item_name(fn_id).to_ident_string(); - let ty_params = fn_args.types().map(|ty| format!("{}", ty)); - let const_params = fn_args.consts().map(|c| format!("{}", c)); + let ty_params = fn_args.types().map(|ty| format!("{ty}")); + let const_params = fn_args.consts().map(|c| format!("{c}")); let params = ty_params.chain(const_params).join(", "); let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder(); let variadic = if fn_sig.c_variadic() { ", ..." } else { "" }; let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" }; let sugg = format!( "{} as {}{}fn({}{}){}", - if params.is_empty() { ident.clone() } else { format!("{}::<{}>", ident, params) }, + if params.is_empty() { ident.clone() } else { format!("{ident}::<{params}>") }, unsafety, abi, vec!["_"; num_args].join(", "), diff --git a/compiler/rustc_mir_transform/src/generator.rs b/compiler/rustc_mir_transform/src/generator.rs index eaeaff69cf391..669135f80bc51 100644 --- a/compiler/rustc_mir_transform/src/generator.rs +++ b/compiler/rustc_mir_transform/src/generator.rs @@ -1477,7 +1477,7 @@ impl<'tcx> MirPass<'tcx> for StateTransform { ) } _ => { - tcx.sess.delay_span_bug(body.span, format!("unexpected generator type {}", gen_ty)); + tcx.sess.delay_span_bug(body.span, format!("unexpected generator type {gen_ty}")); return; } }; diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index a430f8da35cf8..8b0a0903d1897 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -57,7 +57,7 @@ struct InstSimplifyContext<'tcx, 'a> { impl<'tcx> InstSimplifyContext<'tcx, '_> { fn should_simplify(&self, source_info: &SourceInfo, rvalue: &Rvalue<'tcx>) -> bool { self.tcx.consider_optimizing(|| { - format!("InstSimplify - Rvalue: {:?} SourceInfo: {:?}", rvalue, source_info) + format!("InstSimplify - Rvalue: {rvalue:?} SourceInfo: {source_info:?}") }) } diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index d419329f2d6bf..734321e97d892 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -615,7 +615,7 @@ fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> { // computes and caches its result. Some(hir::ConstContext::ConstFn) => tcx.ensure_with_value().mir_for_ctfe(did), None => {} - Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other), + Some(other) => panic!("do not use `optimized_mir` for constants: {other:?}"), } debug!("about to call mir_drops_elaborated..."); let body = tcx.mir_drops_elaborated_and_const_checked(did).steal(); diff --git a/compiler/rustc_mir_transform/src/match_branches.rs b/compiler/rustc_mir_transform/src/match_branches.rs index 6eb4849827447..bc29fb8ded16a 100644 --- a/compiler/rustc_mir_transform/src/match_branches.rs +++ b/compiler/rustc_mir_transform/src/match_branches.rs @@ -51,7 +51,7 @@ impl<'tcx> MirPass<'tcx> for MatchBranchSimplification { let bbs = body.basic_blocks.as_mut(); let mut should_cleanup = false; 'outer: for bb_idx in bbs.indices() { - if !tcx.consider_optimizing(|| format!("MatchBranchSimplification {:?} ", def_id)) { + if !tcx.consider_optimizing(|| format!("MatchBranchSimplification {def_id:?} ")) { continue; } diff --git a/compiler/rustc_mir_transform/src/multiple_return_terminators.rs b/compiler/rustc_mir_transform/src/multiple_return_terminators.rs index 3957cd92c4e39..c97d034544a81 100644 --- a/compiler/rustc_mir_transform/src/multiple_return_terminators.rs +++ b/compiler/rustc_mir_transform/src/multiple_return_terminators.rs @@ -27,7 +27,7 @@ impl<'tcx> MirPass<'tcx> for MultipleReturnTerminators { } for bb in bbs { - if !tcx.consider_optimizing(|| format!("MultipleReturnTerminators {:?} ", def_id)) { + if !tcx.consider_optimizing(|| format!("MultipleReturnTerminators {def_id:?} ")) { break; } diff --git a/compiler/rustc_mir_transform/src/nrvo.rs b/compiler/rustc_mir_transform/src/nrvo.rs index 5ce96012b9086..e1298b0654f2c 100644 --- a/compiler/rustc_mir_transform/src/nrvo.rs +++ b/compiler/rustc_mir_transform/src/nrvo.rs @@ -45,7 +45,7 @@ impl<'tcx> MirPass<'tcx> for RenameReturnPlace { return; }; - if !tcx.consider_optimizing(|| format!("RenameReturnPlace {:?}", def_id)) { + if !tcx.consider_optimizing(|| format!("RenameReturnPlace {def_id:?}")) { return; } diff --git a/compiler/rustc_mir_transform/src/pass_manager.rs b/compiler/rustc_mir_transform/src/pass_manager.rs index 710eed3ed3808..057f5fe82931b 100644 --- a/compiler/rustc_mir_transform/src/pass_manager.rs +++ b/compiler/rustc_mir_transform/src/pass_manager.rs @@ -118,7 +118,7 @@ fn run_passes_inner<'tcx>( dump_mir_for_pass(tcx, body, &name, false); } if validate { - validate_body(tcx, body, format!("before pass {}", name)); + validate_body(tcx, body, format!("before pass {name}")); } tcx.sess.time(name, || pass.run_pass(tcx, body)); @@ -127,7 +127,7 @@ fn run_passes_inner<'tcx>( dump_mir_for_pass(tcx, body, &name, true); } if validate { - validate_body(tcx, body, format!("after pass {}", name)); + validate_body(tcx, body, format!("after pass {name}")); } body.pass_count += 1; diff --git a/compiler/rustc_mir_transform/src/remove_unneeded_drops.rs b/compiler/rustc_mir_transform/src/remove_unneeded_drops.rs index 84ccf6e1f61d4..08b2a6537e93e 100644 --- a/compiler/rustc_mir_transform/src/remove_unneeded_drops.rs +++ b/compiler/rustc_mir_transform/src/remove_unneeded_drops.rs @@ -27,7 +27,7 @@ impl<'tcx> MirPass<'tcx> for RemoveUnneededDrops { if ty.ty.needs_drop(tcx, param_env) { continue; } - if !tcx.consider_optimizing(|| format!("RemoveUnneededDrops {:?} ", did)) { + if !tcx.consider_optimizing(|| format!("RemoveUnneededDrops {did:?} ")) { continue; } debug!("SUCCESS: replacing `drop` with goto({:?})", target); diff --git a/compiler/rustc_mir_transform/src/remove_zsts.rs b/compiler/rustc_mir_transform/src/remove_zsts.rs index 1ba9ad8753751..9c6c55b0811f7 100644 --- a/compiler/rustc_mir_transform/src/remove_zsts.rs +++ b/compiler/rustc_mir_transform/src/remove_zsts.rs @@ -102,7 +102,7 @@ impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> { let op_ty = operand.ty(self.local_decls, self.tcx); if self.known_to_be_zst(op_ty) && self.tcx.consider_optimizing(|| { - format!("RemoveZsts - Operand: {:?} Location: {:?}", operand, loc) + format!("RemoveZsts - Operand: {operand:?} Location: {loc:?}") }) { *operand = Operand::Constant(Box::new(self.make_zst(op_ty))) diff --git a/compiler/rustc_parse/src/lexer/diagnostics.rs b/compiler/rustc_parse/src/lexer/diagnostics.rs index 9e6d27bf036fc..b50bb47f2972d 100644 --- a/compiler/rustc_parse/src/lexer/diagnostics.rs +++ b/compiler/rustc_parse/src/lexer/diagnostics.rs @@ -46,7 +46,7 @@ pub fn report_missing_open_delim( }; err.span_label( unmatch_brace.found_span.shrink_to_lo(), - format!("missing open `{}` for this delimiter", missed_open), + format!("missing open `{missed_open}` for this delimiter"), ); reported_missing_open = true; } diff --git a/compiler/rustc_parse/src/lexer/tokentrees.rs b/compiler/rustc_parse/src/lexer/tokentrees.rs index 318a299850902..07910113dee7f 100644 --- a/compiler/rustc_parse/src/lexer/tokentrees.rs +++ b/compiler/rustc_parse/src/lexer/tokentrees.rs @@ -198,7 +198,7 @@ impl<'a> TokenTreesReader<'a> { // An unexpected closing delimiter (i.e., there is no // matching opening delimiter). let token_str = token_to_string(&self.token); - let msg = format!("unexpected closing delimiter: `{}`", token_str); + let msg = format!("unexpected closing delimiter: `{token_str}`"); let mut err = self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, msg); report_suspicious_mismatch_block( diff --git a/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs b/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs index d1f852b1a4053..446472d129452 100644 --- a/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs +++ b/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs @@ -135,7 +135,7 @@ pub(crate) fn emit_unescape_error( "unknown character escape" }; let ec = escaped_char(c); - let mut diag = handler.struct_span_err(span, format!("{}: `{}`", label, ec)); + let mut diag = handler.struct_span_err(span, format!("{label}: `{ec}`")); diag.span_label(span, label); if c == '{' || c == '}' && matches!(mode, Mode::Str | Mode::RawStr) { diag.help( @@ -151,7 +151,7 @@ pub(crate) fn emit_unescape_error( diag.span_suggestion( span_with_quotes, "if you meant to write a literal backslash (perhaps escaping in a regular expression), consider a raw string literal", - format!("r\"{}\"", lit), + format!("r\"{lit}\""), Applicability::MaybeIncorrect, ); } @@ -180,21 +180,20 @@ pub(crate) fn emit_unescape_error( Mode::RawByteStr => "raw byte string literal", _ => panic!("non-is_byte literal paired with NonAsciiCharInByte"), }; - let mut err = handler.struct_span_err(span, format!("non-ASCII character in {}", desc)); + let mut err = handler.struct_span_err(span, format!("non-ASCII character in {desc}")); let postfix = if unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) == 0 { - format!(" but is {:?}", c) + format!(" but is {c:?}") } else { String::new() }; - err.span_label(span, format!("must be ASCII{}", postfix)); + err.span_label(span, format!("must be ASCII{postfix}")); // Note: the \\xHH suggestions are not given for raw byte string // literals, because they are araw and so cannot use any escapes. if (c as u32) <= 0xFF && mode != Mode::RawByteStr { err.span_suggestion( span, format!( - "if you meant to use the unicode code point for {:?}, use a \\xHH escape", - c + "if you meant to use the unicode code point for {c:?}, use a \\xHH escape" ), format!("\\x{:X}", c as u32), Applicability::MaybeIncorrect, @@ -206,7 +205,7 @@ pub(crate) fn emit_unescape_error( utf8.push(c); err.span_suggestion( span, - format!("if you meant to use the UTF-8 encoding of {:?}, use \\xHH escapes", c), + format!("if you meant to use the UTF-8 encoding of {c:?}, use \\xHH escapes"), utf8.as_bytes() .iter() .map(|b: &u8| format!("\\x{:X}", *b)) diff --git a/compiler/rustc_parse/src/lexer/unicode_chars.rs b/compiler/rustc_parse/src/lexer/unicode_chars.rs index 829d9693e55a6..bbfb160ebf7cb 100644 --- a/compiler/rustc_parse/src/lexer/unicode_chars.rs +++ b/compiler/rustc_parse/src/lexer/unicode_chars.rs @@ -349,7 +349,7 @@ pub(super) fn check_for_substitution( let span = Span::with_root_ctxt(pos, pos + Pos::from_usize(ch.len_utf8() * count)); let Some((_, ascii_name, token)) = ASCII_ARRAY.iter().find(|&&(s, _, _)| s == ascii_str) else { - let msg = format!("substitution character not found for '{}'", ch); + let msg = format!("substitution character not found for '{ch}'"); reader.sess.span_diagnostic.span_bug_no_panic(span, msg); return (None, None); }; diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index 25de780853291..47233d0615ca4 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -247,7 +247,7 @@ pub fn parse_cfg_attr( match parse_in(parse_sess, tokens.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) { Ok(r) => return Some(r), Err(mut e) => { - e.help(format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP)) + e.help(format!("the valid syntax is `{CFG_ATTR_GRAMMAR_HELP}`")) .note(CFG_ATTR_NOTE_REF) .emit(); } diff --git a/compiler/rustc_parse/src/parser/attr_wrapper.rs b/compiler/rustc_parse/src/parser/attr_wrapper.rs index b579da098d8a1..d1f29b603b6f0 100644 --- a/compiler/rustc_parse/src/parser/attr_wrapper.rs +++ b/compiler/rustc_parse/src/parser/attr_wrapper.rs @@ -145,13 +145,11 @@ impl ToAttrTokenStream for LazyAttrTokenStreamImpl { // another replace range will capture the *replaced* tokens for the inner // range, not the original tokens. for (range, new_tokens) in replace_ranges.into_iter().rev() { - assert!(!range.is_empty(), "Cannot replace an empty range: {:?}", range); + assert!(!range.is_empty(), "Cannot replace an empty range: {range:?}"); // Replace ranges are only allowed to decrease the number of tokens. assert!( range.len() >= new_tokens.len(), - "Range {:?} has greater len than {:?}", - range, - new_tokens + "Range {range:?} has greater len than {new_tokens:?}" ); // Replace any removed tokens with `FlatToken::Empty`. @@ -409,22 +407,19 @@ fn make_token_stream( FlatToken::Token(Token { kind: TokenKind::CloseDelim(delim), span }) => { let frame_data = stack .pop() - .unwrap_or_else(|| panic!("Token stack was empty for token: {:?}", token)); + .unwrap_or_else(|| panic!("Token stack was empty for token: {token:?}")); let (open_delim, open_sp) = frame_data.open_delim_sp.unwrap(); assert_eq!( open_delim, delim, - "Mismatched open/close delims: open={:?} close={:?}", - open_delim, span + "Mismatched open/close delims: open={open_delim:?} close={span:?}" ); let dspan = DelimSpan::from_pair(open_sp, span); let stream = AttrTokenStream::new(frame_data.inner); let delimited = AttrTokenTree::Delimited(dspan, delim, stream); stack .last_mut() - .unwrap_or_else(|| { - panic!("Bottom token frame is missing for token: {:?}", token) - }) + .unwrap_or_else(|| panic!("Bottom token frame is missing for token: {token:?}")) .inner .push(delimited); } @@ -456,7 +451,7 @@ fn make_token_stream( .inner .push(AttrTokenTree::Token(Token::new(unglued_first, first_span), spacing)); } else { - panic!("Unexpected last token {:?}", last_token) + panic!("Unexpected last token {last_token:?}") } } AttrTokenStream::new(final_buf.inner) diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index c3cf6437afa07..9eed5fdccc03a 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -608,13 +608,13 @@ impl<'a> Parser<'a> { if let TokenKind::Ident(prev, _) = &self.prev_token.kind && let TokenKind::Ident(cur, _) = &self.token.kind { - let concat = Symbol::intern(&format!("{}{}", prev, cur)); + let concat = Symbol::intern(&format!("{prev}{cur}")); let ident = Ident::new(concat, DUMMY_SP); if ident.is_used_keyword() || ident.is_reserved() || ident.is_raw_guess() { let span = self.prev_token.span.to(self.token.span); err.span_suggestion_verbose( span, - format!("consider removing the space to spell keyword `{}`", concat), + format!("consider removing the space to spell keyword `{concat}`"), concat, Applicability::MachineApplicable, ); diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 769415b614b08..6f0a8d8919855 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -1052,7 +1052,7 @@ impl<'a> Parser<'a> { } components.push(Punct(c)); } else { - panic!("unexpected character in a float token: {:?}", c) + panic!("unexpected character in a float token: {c:?}") } } if !ident_like.is_empty() { @@ -1113,7 +1113,7 @@ impl<'a> Parser<'a> { self.error_unexpected_after_dot(); DestructuredFloat::Error } - _ => panic!("unexpected components in a float token: {:?}", components), + _ => panic!("unexpected components in a float token: {components:?}"), } } diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 2e1a61e634e62..7d076a2b7a0fa 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -368,7 +368,7 @@ impl TokenType { fn to_string(&self) -> String { match self { TokenType::Token(t) => format!("`{}`", pprust::token_kind_to_string(t)), - TokenType::Keyword(kw) => format!("`{}`", kw), + TokenType::Keyword(kw) => format!("`{kw}`"), TokenType::Operator => "an operator".to_string(), TokenType::Lifetime => "lifetime".to_string(), TokenType::Ident => "identifier".to_string(), @@ -438,7 +438,7 @@ pub(super) fn token_descr(token: &Token) -> String { TokenDescription::DocComment => "doc comment", }); - if let Some(kind) = kind { format!("{} `{}`", kind, name) } else { format!("`{}`", name) } + if let Some(kind) = kind { format!("{kind} `{name}`") } else { format!("`{name}`") } } impl<'a> Parser<'a> { @@ -923,7 +923,7 @@ impl<'a> Parser<'a> { expect_err .span_suggestion_short( sp, - format!("missing `{}`", token_str), + format!("missing `{token_str}`"), token_str, Applicability::MaybeIncorrect, ) diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index 14891c45d81a2..fed16278db57e 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -428,7 +428,7 @@ impl<'a> Parser<'a> { ); let mut err = self_.struct_span_err(self_.token.span, msg); - err.span_label(self_.token.span, format!("expected {}", expected)); + err.span_label(self_.token.span, format!("expected {expected}")); err }); PatKind::Lit(self.mk_expr(lo, ExprKind::Lit(lit))) @@ -664,7 +664,7 @@ impl<'a> Parser<'a> { let msg = format!("expected {}, found {}", expected, super::token_descr(&self.token)); let mut err = self.struct_span_err(self.token.span, msg); - err.span_label(self.token.span, format!("expected {}", expected)); + err.span_label(self.token.span, format!("expected {expected}")); let sp = self.sess.source_map().start_point(self.token.span); if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) { @@ -977,7 +977,7 @@ impl<'a> Parser<'a> { break; } let token_str = super::token_descr(&self.token); - let msg = format!("expected `}}`, found {}", token_str); + let msg = format!("expected `}}`, found {token_str}"); let mut err = self.struct_span_err(self.token.span, msg); err.span_label(self.token.span, "expected `}`"); diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index feb7e829caf68..445516c03a15e 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -679,7 +679,7 @@ impl<'a> Parser<'a> { ); err.span_suggestion( eq.to(before_next), - format!("remove the `=` if `{}` is a type", ident), + format!("remove the `=` if `{ident}` is a type"), "", Applicability::MaybeIncorrect, ) diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index 9fcf51a04ec05..1cdf2efa76445 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -300,7 +300,7 @@ impl<'a> Parser<'a> { Ok(ty) => (None, Some(ty)), Err(mut err) => { if let Ok(snip) = self.span_to_snippet(pat.span) { - err.span_label(pat.span, format!("while parsing the type for `{}`", snip)); + err.span_label(pat.span, format!("while parsing the type for `{snip}`")); } // we use noexpect here because we don't actually expect Eq to be here // but we are still checking for it in order to be able to handle it if @@ -502,7 +502,7 @@ impl<'a> Parser<'a> { fn error_block_no_opening_brace(&mut self) -> PResult<'a, T> { let tok = super::token_descr(&self.token); - let msg = format!("expected `{{`, found {}", tok); + let msg = format!("expected `{{`, found {tok}"); Err(self.error_block_no_opening_brace_msg(Cow::from(msg))) } @@ -638,10 +638,9 @@ impl<'a> Parser<'a> { e.span_suggestion( sp.with_hi(sp.lo() + BytePos(marker.len() as u32)), format!( - "add a space before `{}` to use a regular comment", - doc_comment_marker, + "add a space before `{doc_comment_marker}` to use a regular comment", ), - format!("{} {}", comment_marker, doc_comment_marker), + format!("{comment_marker} {doc_comment_marker}"), Applicability::MaybeIncorrect, ); } diff --git a/compiler/rustc_parse/src/validate_attr.rs b/compiler/rustc_parse/src/validate_attr.rs index 928fdce313d91..39e797397a65f 100644 --- a/compiler/rustc_parse/src/validate_attr.rs +++ b/compiler/rustc_parse/src/validate_attr.rs @@ -157,14 +157,14 @@ fn emit_malformed_attribute( matches!(name, sym::doc | sym::ignore | sym::inline | sym::link | sym::test | sym::bench) }; - let error_msg = format!("malformed `{}` attribute input", name); + let error_msg = format!("malformed `{name}` attribute input"); let mut msg = "attribute must be of the form ".to_owned(); let mut suggestions = vec![]; let mut first = true; let inner = if style == ast::AttrStyle::Inner { "!" } else { "" }; if template.word { first = false; - let code = format!("#{}[{}]", inner, name); + let code = format!("#{inner}[{name}]"); msg.push_str(&format!("`{}`", &code)); suggestions.push(code); } @@ -173,7 +173,7 @@ fn emit_malformed_attribute( msg.push_str(" or "); } first = false; - let code = format!("#{}[{}({})]", inner, name, descr); + let code = format!("#{inner}[{name}({descr})]"); msg.push_str(&format!("`{}`", &code)); suggestions.push(code); } @@ -181,7 +181,7 @@ fn emit_malformed_attribute( if !first { msg.push_str(" or "); } - let code = format!("#{}[{} = \"{}\"]", inner, name, descr); + let code = format!("#{inner}[{name} = \"{descr}\"]"); msg.push_str(&format!("`{}`", &code)); suggestions.push(code); } diff --git a/compiler/rustc_passes/src/check_const.rs b/compiler/rustc_passes/src/check_const.rs index fc437c429fbeb..e70817d7b7c55 100644 --- a/compiler/rustc_passes/src/check_const.rs +++ b/compiler/rustc_passes/src/check_const.rs @@ -157,10 +157,8 @@ impl<'tcx> CheckConstVisitor<'tcx> { // is a pretty narrow case, however. if tcx.sess.is_nightly_build() { for gate in missing_secondary { - let note = format!( - "add `#![feature({})]` to the crate attributes to enable", - gate, - ); + let note = + format!("add `#![feature({gate})]` to the crate attributes to enable",); err.help(note); } } diff --git a/compiler/rustc_passes/src/hir_id_validator.rs b/compiler/rustc_passes/src/hir_id_validator.rs index 363e1743677ad..f825363ae39a1 100644 --- a/compiler/rustc_passes/src/hir_id_validator.rs +++ b/compiler/rustc_passes/src/hir_id_validator.rs @@ -89,9 +89,8 @@ impl<'a, 'hir> HirIdValidator<'a, 'hir> { self.error(|| { format!( - "ItemLocalIds not assigned densely in {}. \ - Max ItemLocalId = {}, missing IDs = {:#?}; seen IDs = {:#?}", - pretty_owner, max, missing_items, seen_items + "ItemLocalIds not assigned densely in {pretty_owner}. \ + Max ItemLocalId = {max}, missing IDs = {missing_items:#?}; seen IDs = {seen_items:#?}" ) }); } diff --git a/compiler/rustc_passes/src/hir_stats.rs b/compiler/rustc_passes/src/hir_stats.rs index 6c748147abe07..5aa8aef6a859a 100644 --- a/compiler/rustc_passes/src/hir_stats.rs +++ b/compiler/rustc_passes/src/hir_stats.rs @@ -126,12 +126,12 @@ impl<'k> StatCollector<'k> { let total_size = nodes.iter().map(|(_, node)| node.stats.count * node.stats.size).sum(); - eprintln!("{} {}", prefix, title); + eprintln!("{prefix} {title}"); eprintln!( "{} {:<18}{:>18}{:>14}{:>14}", prefix, "Name", "Accumulated Size", "Count", "Item Size" ); - eprintln!("{} ----------------------------------------------------------------", prefix); + eprintln!("{prefix} ----------------------------------------------------------------"); let percent = |m, n| (m * 100) as f64 / n as f64; @@ -163,9 +163,9 @@ impl<'k> StatCollector<'k> { } } } - eprintln!("{} ----------------------------------------------------------------", prefix); + eprintln!("{prefix} ----------------------------------------------------------------"); eprintln!("{} {:<18}{:>10}", prefix, "Total", to_readable_str(total_size)); - eprintln!("{}", prefix); + eprintln!("{prefix}"); } } diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index 89c6704e4169a..15757a0f1adaf 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -605,7 +605,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { for var_idx in 0..self.ir.var_kinds.len() { let var = Variable::from(var_idx); if test(var) { - write!(wr, " {:?}", var)?; + write!(wr, " {var:?}")?; } } Ok(()) diff --git a/compiler/rustc_query_system/src/dep_graph/graph.rs b/compiler/rustc_query_system/src/dep_graph/graph.rs index c9e80a6d9bc13..b87757a3e1ad6 100644 --- a/compiler/rustc_query_system/src/dep_graph/graph.rs +++ b/compiler/rustc_query_system/src/dep_graph/graph.rs @@ -557,7 +557,7 @@ impl DepGraph { result, prev_index, hash_result, - |value| format!("{:?}", value), + |value| format!("{value:?}"), ); #[cfg(debug_assertions)] @@ -1433,7 +1433,7 @@ pub(crate) fn print_markframe_trace( let mut current = frame; while let Some(frame) = current { let node = data.previous.index_to_node(frame.index); - eprintln!("#{i} {:?}", node); + eprintln!("#{i} {node:?}"); current = frame.parent; i += 1; } diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index ff63e4e33cb9d..b69974a47dab7 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -999,7 +999,7 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> { allow_shadowing: bool, ) { 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 = "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(); diff --git a/compiler/rustc_resolve/src/check_unused.rs b/compiler/rustc_resolve/src/check_unused.rs index 3228e8d52f06a..7dbbd4c34ea7d 100644 --- a/compiler/rustc_resolve/src/check_unused.rs +++ b/compiler/rustc_resolve/src/check_unused.rs @@ -362,7 +362,7 @@ impl Resolver<'_, '_> { let mut span_snippets = spans .iter() .filter_map(|s| match tcx.sess.source_map().span_to_snippet(*s) { - Ok(s) => Some(format!("`{}`", s)), + Ok(s) => Some(format!("`{s}`")), _ => None, }) .collect::>(); diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 73cd596c07693..d007b672d417f 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -228,7 +228,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { (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()) { (true, true) => struct_span_err!(self.tcx.sess, span, E0259, "{}", msg), @@ -250,11 +250,11 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { 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 { err.span_label( 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"), ); } @@ -343,15 +343,15 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { binding_span: Span, ) { let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() { - format!("Other{}", name) + format!("Other{name}") } else { - format!("other_{}", name) + format!("other_{name}") }; let mut suggestion = None; match import.kind { ImportKind::Single { type_ns_only: true, .. } => { - suggestion = Some(format!("self as {}", suggested_name)) + suggestion = Some(format!("self as {suggested_name}")) } ImportKind::Single { source, .. } => { if let Some(pos) = @@ -587,11 +587,11 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let sugg_msg = "try using a local generic parameter instead"; let name = self.tcx.item_name(def_id); let (span, snippet) = if span.is_empty() { - let snippet = format!("<{}>", name); + let snippet = format!("<{name}>"); (span, snippet) } else { let span = sm.span_through_char(span, '<').shrink_to_hi(); - let snippet = format!("{}, ", name); + let snippet = format!("{name}, "); (span, snippet) }; // Suggest the modification to the user @@ -652,7 +652,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { name, ); 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 { err.span_label(sp, "variable not in all patterns"); @@ -679,8 +679,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if import_suggestions.is_empty() { let help_msg = format!( "if you meant to match on a variant or a `const` item, consider \ - making the path in the pattern qualified: `path::to::ModOrType::{}`", - name, + making the path in the pattern qualified: `path::to::ModOrType::{name}`", ); err.span_help(span, help_msg); } @@ -938,8 +937,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let mut err = self.tcx.sess.struct_span_err_with_code( span, format!( - "item `{}` is an associated {}, which doesn't match its trait `{}`", - name, kind, trait_path, + "item `{name}` is an associated {kind}, which doesn't match its trait `{trait_path}`", ), code, ); @@ -1412,10 +1410,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { "a function-like macro".to_string() } Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => { - format!("an attribute: `#[{}]`", ident) + format!("an attribute: `#[{ident}]`") } Res::Def(DefKind::Macro(MacroKind::Derive), _) => { - format!("a derive macro: `#[derive({})]`", ident) + format!("a derive macro: `#[derive({ident})]`") } Res::ToolMod => { // Don't confuse the user with tool modules. @@ -1436,7 +1434,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if !import.span.is_dummy() { err.span_note( 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, // since this diagnostic already covers that import. @@ -1444,7 +1442,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { return; } } - err.note(format!("`{}` is in scope, but it is {}", ident, desc)); + err.note(format!("`{ident}` is in scope, but it is {desc}")); return; } } @@ -1582,7 +1580,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { err.span_note(b.span, note_msg); for (i, help_msg) in help_msgs.iter().enumerate() { let or = if i == 0 { "" } else { "or " }; - err.help(format!("{}{}", or, help_msg)); + err.help(format!("{or}{help_msg}")); } }; @@ -1626,7 +1624,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let descr = get_descr(binding); let mut err = 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 { let import_suggestions = self.lookup_import_candidates( @@ -1811,7 +1809,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { _ => 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 { let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS }; let binding = if let Some(module) = module { @@ -1926,12 +1924,12 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let suggestion = match_span.map(|span| { ( 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, ) }); - (format!("use of undeclared type `{}`", ident), suggestion) + (format!("use of undeclared type `{ident}`"), suggestion) } else { let mut suggestion = None; if ident.name == sym::alloc { @@ -1953,7 +1951,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) } } @@ -2137,16 +2135,16 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let module_name = crate_module.kind.name().unwrap(); let import_snippet = match import.kind { 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(); if !import.is_nested() { // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove // intermediate segments. - corrections.push((import.span, format!("{}::{}", module_name, import_snippet))); + corrections.push((import.span, format!("{module_name}::{import_snippet}"))); } else { // Find the binding span (and any trailing commas and spaces). // ie. `use a::b::{c, d, e};` @@ -2213,11 +2211,11 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { start_point, if has_nested { // In this case, `start_snippet` must equal '{'. - format!("{}{}, ", start_snippet, import_snippet) + format!("{start_snippet}{import_snippet}, ") } else { // In this case, add a `{`, then the moved import, then whatever // was there before. - format!("{{{}, {}", import_snippet, start_snippet) + format!("{{{import_snippet}, {start_snippet}") }, )); @@ -2634,9 +2632,9 @@ fn show_candidates( "item" }; 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 spans = Vec::new(); @@ -2657,7 +2655,7 @@ fn show_candidates( let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect()); 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()) { diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs index de4314447698a..b7634064863ff 100644 --- a/compiler/rustc_resolve/src/ident.rs +++ b/compiler/rustc_resolve/src/ident.rs @@ -1443,12 +1443,12 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let name_str = if name == kw::PathRoot { "crate root".to_string() } else { - format!("`{}`", name) + format!("`{name}`") }; 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 { - 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) }); diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index 526fc9c3aa511..76d25eefe8d83 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -1087,18 +1087,18 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { ModuleOrUniformRoot::Module(module) => { let module_str = module_to_string(module); if let Some(module_str) = module_str { - format!("no `{}` in `{}`", ident, module_str) + format!("no `{ident}` in `{module_str}`") } else { - format!("no `{}` in the root", ident) + format!("no `{ident}` in the root") } } _ => { if !ident.is_path_segment_keyword() { - format!("no external crate `{}`", ident) + format!("no external crate `{ident}`") } else { // HACK(eddyb) this shows up for `self` & `super`, which // should work instead - for now keep the same error message. - format!("no `{}` in the root", ident) + format!("no `{ident}` in the root") } } }; @@ -1146,10 +1146,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let (ns, binding) = reexport_error.unwrap(); if pub_use_of_private_extern_crate_hack(import, binding) { 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 \ - `pub`", - ident + `pub`" ); self.lint_buffer.buffer_lint( PUB_USE_OF_PRIVATE_EXTERN_CRATE, @@ -1289,7 +1288,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { UNUSED_IMPORTS, id, import.span, - format!("the item `{}` is imported redundantly", ident), + format!("the item `{ident}` is imported redundantly"), BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident), ); } diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index be7ef92d17537..44b13818af0ec 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -1913,10 +1913,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { candidate: LifetimeElisionCandidate, ) { if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) { - panic!( - "lifetime {:?} resolved multiple times ({:?} before, {:?} now)", - id, prev_res, res - ) + panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)") } match res { LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static => { @@ -1932,8 +1929,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) { if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) { panic!( - "lifetime parameter {:?} resolved multiple times ({:?} before, {:?} now)", - id, prev_res, res + "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)" ) } } diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 753a1adc66d72..a89ced9ea3bc3 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -585,13 +585,13 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { let others = match enum_candidates.len() { 1 => String::new(), 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) } else { 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( span, @@ -696,7 +696,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { ident.name == path[0].ident.name { err.span_help( 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); } @@ -858,7 +858,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { for label_rib in &self.label_ribs { for (label_ident, node_id) in &label_rib.bindings { 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"); if let PathSource::Expr(Some(Expr { 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() { err.span_label( 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( *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), Applicability::MaybeIncorrect, ); @@ -1338,8 +1338,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { span, // Note the parentheses surrounding the suggestion below format!( "you might want to surround a struct literal with parentheses: \ - `({} {{ /* fields */ }})`?", - path_str + `({path_str} {{ /* fields */ }})`?" ), ); } @@ -1373,7 +1372,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { .map(|(idx, new)| (new, old_fields.get(idx))) .map(|(new, old)| { 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::>() } else { @@ -1390,7 +1389,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { }; err.span_suggestion( span, - format!("use struct {} syntax instead", descr), + format!("use struct {descr} syntax instead"), format!("{path_str} {{{pad}{fields}{pad}}}"), applicability, ); @@ -1584,7 +1583,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { err.span_suggestion( span, "use the tuple variant pattern syntax instead", - format!("{}({})", path_str, fields), + format!("{path_str}({fields})"), Applicability::HasPlaceholders, ); } @@ -1994,9 +1993,9 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { if !suggestable_variants.is_empty() { 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 { - format!("try {} one of the enum's variants", source_msg) + format!("try {source_msg} one of the enum's variants") }; err.span_suggestions( @@ -2009,19 +2008,15 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { // If the enum has no tuple variants.. 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 non_suggestable_variant_count == 1 { - err.help(format!( - "you might have meant {} the enum's non-tuple variant", - source_msg - )); + err.help(format!("you might have meant {source_msg} the enum's non-tuple variant")); } else if non_suggestable_variant_count >= 1 { err.help(format!( - "you might have meant {} one of the enum's non-tuple variants", - source_msg + "you might have meant {source_msg} one of the enum's non-tuple variants" )); } } 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)| match kind { CtorKind::Const => variant, - CtorKind::Fn => format!("({}())", variant), + CtorKind::Fn => format!("({variant}())"), }) .collect::>(); 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)) .map(|(variant, _, kind)| (path_names_to_string(variant), kind)) .filter_map(|(variant, kind)| match kind { - CtorKind::Fn => Some(format!("({}(/* fields */))", variant)), + CtorKind::Fn => Some(format!("({variant}(/* fields */))")), _ => None, }) .collect::>(); @@ -2353,8 +2348,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { err.span_label( span, format!( - "lifetime `{}` is missing in item created through this procedural macro", - name, + "lifetime `{name}` is missing in item created through this procedural macro", ), ); continue; @@ -2398,7 +2392,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { ); } else if let Some(name) = name { 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); } else { let message = Cow::from("consider introducing a named lifetime parameter"); @@ -2542,7 +2536,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { } let help_name = if let Some(ident) = ident { - format!("`{}`", ident) + format!("`{ident}`") } else { format!("argument {}", index + 1) }; @@ -2550,7 +2544,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { if lifetime_count == 1 { m.push_str(&help_name[..]) } 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")[..]) } } @@ -2580,14 +2574,12 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { } else if num_params == 1 { err.help(format!( "this function's return type contains a borrowed value, \ - but the signature does not say which {} it is borrowed from", - m + but the signature does not say which {m} it is borrowed from" )); } else { err.help(format!( "this function's return type contains a borrowed value, \ - but the signature does not say whether it is borrowed from {}", - m + but the signature does not say whether it is borrowed from {m}" )); } } @@ -2606,7 +2598,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { } MissingLifetimeKind::Ampersand => { debug_assert_eq!(lt.count, 1); - (lt.span.shrink_to_hi(), format!("{} ", existing_name)) + (lt.span.shrink_to_hi(), format!("{existing_name} ")) } MissingLifetimeKind::Comma => { let sugg: String = std::iter::repeat([existing_name.as_str(), ", "]) @@ -2653,7 +2645,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { } 1 => { err.multipart_suggestion_verbose( - format!("consider using the `{}` lifetime", existing_name), + format!("consider using the `{existing_name}` lifetime"), spans_suggs, Applicability::MaybeIncorrect, ); @@ -2770,9 +2762,9 @@ pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident let shadower = shadower.span; let mut err = sess.struct_span_warn( 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(shadower, format!("label `{}` already in scope", name)); + err.span_label(shadower, format!("label `{name}` already in scope")); err.emit(); } diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index faa672db59ccf..e21a683d842a5 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1158,7 +1158,7 @@ impl<'tcx> Resolver<'_, 'tcx> { } 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. @@ -1812,7 +1812,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) { debug!("(recording res) recording {:?} for {}", resolution, node_id); 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)"); } } diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 266e37e4cef9a..b6cdc3920d9ae 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -205,7 +205,7 @@ impl<'a, 'tcx> ResolverExpand for Resolver<'a, 'tcx> { self.tcx .sess .diagnostic() - .bug(format!("built-in macro `{}` was already registered", name)); + .bug(format!("built-in macro `{name}` was already registered")); } } @@ -568,7 +568,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } 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(); @@ -892,7 +892,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) { self.tcx.sess.span_err( ident.span, - format!("name `{}` is reserved in attribute namespace", ident), + format!("name `{ident}` is reserved in attribute namespace"), ); } } diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 36b5c385ab193..4168d68af848e 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -1538,9 +1538,8 @@ pub(super) fn build_target_config( ); let (target, target_warnings) = target_result.unwrap_or_else(|e| { handler.early_error(format!( - "Error loading target specification: {}. \ - Run `rustc --print target-list` for a list of built-in targets", - e + "Error loading target specification: {e}. \ + Run `rustc --print target-list` for a list of built-in targets" )) }); for warning in target_warnings.warning_messages() { @@ -1977,8 +1976,7 @@ pub fn parse_crate_edition(handler: &EarlyErrorHandler, matches: &getopts::Match let is_nightly = nightly_options::match_is_nightly_build(matches); let msg = if !is_nightly { format!( - "the crate requires edition {}, but the latest edition supported by this Rust version is {}", - edition, LATEST_STABLE_EDITION + "the crate requires edition {edition}, but the latest edition supported by this Rust version is {LATEST_STABLE_EDITION}" ) } else { format!("edition {edition} is unstable and only available with -Z unstable-options") diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index ff433fdf16dc4..4155d718fd237 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -330,8 +330,7 @@ fn build_options( match value { None => handler.early_error( format!( - "{0} option `{1}` requires {2} ({3} {1}=)", - outputname, key, type_desc, prefix + "{outputname} option `{key}` requires {type_desc} ({prefix} {key}=)" ), ), Some(value) => handler.early_error( diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index 97bde5c3c1919..f0f1a9a4d531f 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -444,7 +444,7 @@ impl<'tcx> Stable<'tcx> for mir::InlineAsmOperand<'tcx> { | 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:?}") } } } @@ -493,10 +493,10 @@ impl<'tcx> Stable<'tcx> for mir::Terminator<'tcx> { }, InlineAsm { template, operands, options, line_spans, destination, unwind } => { Terminator::InlineAsm { - template: format!("{:?}", template), + template: format!("{template:?}"), operands: operands.iter().map(|operand| operand.stable(tables)).collect(), - options: format!("{:?}", options), - line_spans: format!("{:?}", line_spans), + options: format!("{options:?}"), + line_spans: format!("{line_spans:?}"), destination: destination.map(|d| d.as_usize()), unwind: unwind.stable(tables), } diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index 27cd0f99f34bc..1aa520bde3cb2 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -161,7 +161,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { let (full_env, full_user_env) = self .evaluate_predicates(&infcx, trait_did, ty, new_env, user_env, &mut fresh_preds) .unwrap_or_else(|| { - panic!("Failed to fully process: {:?} {:?} {:?}", ty, trait_did, orig_env) + panic!("Failed to fully process: {ty:?} {trait_did:?} {orig_env:?}") }); debug!( @@ -178,7 +178,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { ocx.register_bound(ObligationCause::dummy(), full_env, ty, trait_did); let errors = ocx.select_all_or_error(); 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); @@ -339,7 +339,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { return None; } } - _ => panic!("Unexpected error for '{:?}': {:?}", ty, result), + _ => panic!("Unexpected error for '{ty:?}': {result:?}"), }; let normalized_preds = @@ -749,7 +749,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { // subobligations or getting an error) when we started off with // inference variables if p.term().skip_binder().has_infer_types() { - panic!("Unexpected result when selecting {:?} {:?}", ty, obligation) + panic!("Unexpected result when selecting {ty:?} {obligation:?}") } } } diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 039e4ec9afdfc..19d5baa30ec6b 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -357,7 +357,7 @@ fn impl_intersection_has_negative_obligation( Err(err) => { tcx.sess.delay_span_bug( 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; } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index c14839fe9be08..d2cb8182425fa 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -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)); (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, ); - 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 { - 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 // 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{}", pluralize!(expected_args.len()) ), - format!("|{}|", underscores), + format!("|{underscores}|"), Applicability::MachineApplicable, ); } @@ -304,7 +304,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { err.span_suggestion_verbose( found_span, "change the closure to take multiple arguments instead of a single tuple", - format!("|{}|", sugg), + format!("|{sugg}|"), Applicability::MachineApplicable, ); } @@ -704,9 +704,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { .get_parent_trait_ref(obligation.cause.code()) .map(|(t, s)| { ( - format!(" in `{}`", t), - format!("within `{}`, ", t), - s.map(|s| (format!("within this `{}`", t), s)), + format!(" in `{t}`"), + format!("within `{t}`, "), + s.map(|s| (format!("within this `{t}`"), s)), ) }) .unwrap_or_default(); @@ -1071,7 +1071,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // which bounds actually failed to hold. self.tcx.sess.struct_span_err( span, - format!("the type `{}` is not well-formed", ty), + format!("the type `{ty}` is not well-formed"), ) } } @@ -1109,7 +1109,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => { let mut diag = self.tcx.sess.struct_span_err( span, - format!("the constant `{}` is not of type `{}`", ct, ty), + format!("the constant `{ct}` is not of type `{ty}`"), ); self.note_type_err( &mut diag, @@ -1981,7 +1981,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if all_traits_equal { format!("\n {}", c.self_ty()) } else { - format!("\n {}", c) + format!("\n {c}") } }) .collect(); @@ -2179,10 +2179,8 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { format!("trait impl{} with same name found", pluralize!(trait_impls.len())), ); let trait_crate = self.tcx.crate_name(trait_with_same_path.krate); - let crate_msg = format!( - "perhaps two different versions of crate `{}` are being used?", - trait_crate - ); + let crate_msg = + format!("perhaps two different versions of crate `{trait_crate}` are being used?"); err.note(crate_msg); suggested = true; } @@ -2310,7 +2308,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err.cancel(); return; } - err.note(format!("cannot satisfy `{}`", predicate)); + err.note(format!("cannot satisfy `{predicate}`")); let impl_candidates = self .find_similar_impl_candidates(predicate.to_opt_poly_trait_pred().unwrap()); if impl_candidates.len() < 10 { @@ -2374,7 +2372,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { 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(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")); @@ -2475,7 +2473,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ErrorCode::E0284, true, ); - err.note(format!("cannot satisfy `{}`", predicate)); + err.note(format!("cannot satisfy `{predicate}`")); err } else { // If we can't find a substitution, just print a generic error @@ -2486,7 +2484,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { "type annotations needed: cannot satisfy `{}`", predicate, ); - err.span_label(span, format!("cannot satisfy `{}`", predicate)); + err.span_label(span, format!("cannot satisfy `{predicate}`")); err } } @@ -2514,7 +2512,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { "type annotations needed: cannot satisfy `{}`", predicate, ); - err.span_label(span, format!("cannot satisfy `{}`", predicate)); + err.span_label(span, format!("cannot satisfy `{predicate}`")); err } } @@ -2529,7 +2527,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { "type annotations needed: cannot satisfy `{}`", predicate, ); - err.span_label(span, format!("cannot satisfy `{}`", predicate)); + err.span_label(span, format!("cannot satisfy `{predicate}`")); err } }; @@ -2566,7 +2564,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.dedup(); post.sort(); @@ -2593,7 +2591,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { predicate ); let post = if post.len() > 1 || (post.len() == 1 && post[0].contains('\n')) { - format!(":\n{}", post.iter().map(|p| format!("- {}", p)).collect::>().join("\n"),) + format!(":\n{}", post.iter().map(|p| format!("- {p}")).collect::>().join("\n"),) } else if post.len() == 1 { format!(": `{}`", post[0]) } else { @@ -2602,7 +2600,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { match (spans.len(), crates.len(), crate_names.len()) { (0, 0, 0) => { - err.note(format!("cannot satisfy `{}`", predicate)); + err.note(format!("cannot satisfy `{predicate}`")); } (0, _, 1) => { err.note(format!("{} in the `{}` crate{}", msg, crates[0], post,)); @@ -2773,7 +2771,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err.span_suggestion_verbose( span, "consider relaxing the implicit `Sized` restriction", - format!("{} ?Sized", separator), + format!("{separator} ?Sized"), Applicability::MachineApplicable, ); } @@ -2864,7 +2862,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } }) .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}") }) } @@ -3152,11 +3150,11 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err.span_label( closure_span, - format!("this closure implements `{}`, not `{}`", found_kind, kind), + format!("this closure implements `{found_kind}`, not `{kind}`"), ); err.span_label( 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 @@ -3383,8 +3381,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let const_span = self.tcx.def_span(uv.def); match self.tcx.sess.source_map().span_to_snippet(const_span) { Ok(snippet) => err.help(format!( - "try adding a `where` bound using this expression: `where [(); {}]:`", - snippet + "try adding a `where` bound using this expression: `where [(); {snippet}]:`" )), _ => err.help("consider adding a `where` bound using this expression"), }; diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs index a530b27bc9187..0e73bad19185b 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs @@ -170,7 +170,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if let Some(k) = obligation.cause.span.desugaring_kind() { 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() { @@ -258,9 +258,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if let ty::Array(aty, len) = self_ty.kind() { flags.push((sym::_Self, Some("[]".to_string()))); 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 { - flags.push((sym::_Self, Some(format!("[{}; {}]", aty, n)))); + flags.push((sym::_Self, Some(format!("[{aty}; {n}]")))); } if let Some(def) = aty.ty_adt_def() { // 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 {}", s, if trait_def_id == item_def_id { - format!("trait `{}`", trait_name) + format!("trait `{trait_name}`") } else { "impl".to_string() } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 9c51de1814b31..3a85df4596428 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -480,13 +480,13 @@ fn suggest_restriction<'tcx>( .visit_ty(input); } // 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![ if let Some(span) = hir_generics.span_for_param_suggestion() { - (span, format!(", {}", type_param)) + (span, format!(", {type_param}")) } else { - (hir_generics.span, format!("<{}>", type_param)) + (hir_generics.span, format!("<{type_param}>")) }, // `fn foo(t: impl Trait)` // ^ suggest `where ::A: Bound` @@ -531,7 +531,7 @@ fn suggest_restriction<'tcx>( err.span_suggestion_verbose( sp, - format!("consider further restricting {}", msg), + format!("consider further restricting {msg}"), suggestion, Applicability::MachineApplicable, ); @@ -694,7 +694,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { term ); } else { - constraint.push_str(&format!("<{} = {}>", name, term)); + constraint.push_str(&format!("<{name} = {term}>")); } } @@ -1019,7 +1019,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let name = self.tcx.def_path_str(def_id); err.span_label( self.tcx.def_span(def_id), - format!("consider calling the constructor for `{}`", name), + format!("consider calling the constructor for `{name}`"), ); name } @@ -1398,7 +1398,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // Because of this, we modify the error to refer to the original obligation and // 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 { err.note(msg); } else { @@ -1438,7 +1438,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err.multipart_suggestion_verbose( sugg_msg, vec![ - (span.shrink_to_lo(), format!("({}", sugg_prefix)), + (span.shrink_to_lo(), format!("({sugg_prefix}")), (span.shrink_to_hi(), ")".to_string()), ], Applicability::MaybeIncorrect, @@ -1474,7 +1474,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { vec![(span.shrink_to_lo(), sugg_prefix)] } else { vec![ - (span.shrink_to_lo(), format!("{}(", sugg_prefix)), + (span.shrink_to_lo(), format!("{sugg_prefix}(")), (span.shrink_to_hi(), ")".to_string()), ] }; @@ -1705,8 +1705,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { hir.get_if_local(*def_id) { let msg = format!( - "alternatively, consider making `fn {}` asynchronous", - ident + "alternatively, consider making `fn {ident}` asynchronous" ); if vis_span.is_empty() { err.span_suggestion_verbose( @@ -1957,10 +1956,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // don't print out the [type error] here err.delay_as_bug(); } else { - err.span_label( - expr.span, - format!("this returned value is of type `{}`", ty), - ); + err.span_label(expr.span, format!("this returned value is of type `{ty}`")); } } } @@ -2461,8 +2457,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err.clear_code(); err.set_primary_message(format!( - "{} cannot be {} between threads safely", - future_or_generator, trait_verb + "{future_or_generator} cannot be {trait_verb} between threads safely" )); let original_span = err.span.primary_span().unwrap(); @@ -2471,7 +2466,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let message = outer_generator .and_then(|generator_did| { 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 .tcx .parent(generator_did) @@ -2479,73 +2474,73 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { .map(|parent_did| hir.local_def_id_to_hir_id(parent_did)) .and_then(|parent_hir_id| hir.opt_name(parent_hir_id)) .map(|name| { - format!("future returned by `{}` is not {}", name, trait_name) + format!("future returned by `{name}` is not {trait_name}") })?, 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) => { - 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); err.set_span(span); - format!("is not {}", trait_name) + format!("is not {trait_name}") } else { format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path()) }; - let mut explain_yield = - |interior_span: Span, yield_span: Span, scope_span: Option| { - let mut span = MultiSpan::from_span(yield_span); - let snippet = match source_map.span_to_snippet(interior_span) { - // #70935: If snippet contains newlines, display "the value" instead - // so that we do not emit complex diagnostics. - 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 - // | - // LL | baz(|| async { - // | ______________- - // | | - // | | - // LL | | foo(tx.clone()); - // LL | | }).await; - // | | - ^^^^^^ await occurs here, with value maybe used later - // | |__________| - // | has type `closure` which is not `Send` - // note: value is later dropped here - // LL | | }).await; - // | | ^ - // - span.push_span_label( - yield_span, - format!("{} occurs here, with {} maybe used later", await_or_yield, snippet), - ); - span.push_span_label( - interior_span, - format!("has type `{}` which {}", target_ty, trait_explanation), - ); - if let Some(scope_span) = scope_span { - let scope_span = source_map.end_point(scope_span); + let mut explain_yield = |interior_span: Span, + yield_span: Span, + scope_span: Option| { + let mut span = MultiSpan::from_span(yield_span); + let snippet = match source_map.span_to_snippet(interior_span) { + // #70935: If snippet contains newlines, display "the value" instead + // so that we do not emit complex diagnostics. + 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 + // | + // LL | baz(|| async { + // | ______________- + // | | + // | | + // LL | | foo(tx.clone()); + // LL | | }).await; + // | | - ^^^^^^ await occurs here, with value maybe used later + // | |__________| + // | has type `closure` which is not `Send` + // note: value is later dropped here + // LL | | }).await; + // | | ^ + // + span.push_span_label( + yield_span, + format!("{await_or_yield} occurs here, with {snippet} maybe used later"), + ); + span.push_span_label( + 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); - let msg = format!("{} is later dropped here", snippet); - span.push_span_label(scope_span, msg); - } - err.span_note( + let msg = format!("{snippet} is later dropped here"); + span.push_span_label(scope_span, msg); + } + err.span_note( span, format!( - "{} {} as this value is used across {}", - future_or_generator, trait_explanation, an_await_or_yield + "{future_or_generator} {trait_explanation} as this value is used across {an_await_or_yield}" ), ); - }; + }; match interior_or_upvar_span { GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => { if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info { @@ -2555,15 +2550,13 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { span.push_span_label( await_span, format!( - "await occurs here on type `{}`, which {}", - target_ty, trait_explanation + "await occurs here on type `{target_ty}`, which {trait_explanation}" ), ); err.span_note( span, format!( - "future {not_trait} as it awaits another future which {not_trait}", - not_trait = trait_explanation + "future {trait_explanation} as it awaits another future which {trait_explanation}" ), ); } else { @@ -2646,18 +2639,16 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let ref_kind = if is_mut { "&mut" } else { "&" }; ( format!( - "has type `{}` which {}, because `{}` is not `{}`", - target_ty, trait_explanation, ref_ty, ref_ty_trait + "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`" ), format!( - "captured value {} because `{}` references cannot be sent unless their referent is `{}`", - trait_explanation, ref_kind, ref_ty_trait + "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`" ), ) } None => ( - format!("has type `{}` which {}", target_ty, trait_explanation), - format!("captured value {}", trait_explanation), + format!("has type `{target_ty}` which {trait_explanation}"), + format!("captured value {trait_explanation}"), ), }; @@ -2746,8 +2737,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } ObligationCauseCode::ObjectTypeBound(object_ty, region) => { err.note(format!( - "required so that the lifetime bound of `{}` for `{}` is satisfied", - region, object_ty, + "required so that the lifetime bound of `{region}` for `{object_ty}` is satisfied", )); } ObligationCauseCode::ItemObligation(_) @@ -3067,7 +3057,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let mut msg = "required because it captures the following types: ".to_owned(); 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()) } @@ -3081,7 +3071,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { "required because it captures the following types: ".to_owned(); for bty in tcx.generator_hidden_types(*def_id) { let ty = bty.instantiate(tcx, args); - write!(msg, "`{}`, ", ty).unwrap(); + write!(msg, "`{ty}`, ").unwrap(); } err.note(msg.trim_end_matches(", ").to_string()) } @@ -3517,7 +3507,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { trait_pred.skip_binder().self_ty(), diagnostic_name, ), - format!("#[derive({})]\n", diagnostic_name), + format!("#[derive({diagnostic_name})]\n"), Applicability::MaybeIncorrect, ); } @@ -4003,7 +3993,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { .map(|trait_ref| trait_ref.trait_ref.self_ty()) .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) { let mut suggestions = vec![]; diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index 143e8412967e0..08eb9757c36bf 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -517,8 +517,7 @@ fn virtual_call_violation_for_method<'tcx>( tcx.sess.delay_span_bug( tcx.def_span(method.def_id), format!( - "receiver when `Self = ()` should have a Scalar ABI; found {:?}", - abi + "receiver when `Self = ()` should have a Scalar ABI; found {abi:?}" ), ); } @@ -536,8 +535,7 @@ fn virtual_call_violation_for_method<'tcx>( tcx.sess.delay_span_bug( tcx.def_span(method.def_id), format!( - "receiver when `Self = {}` should have a ScalarPair ABI; found {:?}", - trait_object_ty, abi + "receiver when `Self = {trait_object_ty}` should have a ScalarPair ABI; found {abi:?}" ), ); } diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index a39fc1f177185..fb2ee9bcde278 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -481,8 +481,7 @@ impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> { assert!( !value.has_escaping_bound_vars(), - "Normalizing {:?} without wrapping in a `Binder`", - value + "Normalizing {value:?} without wrapping in a `Binder`" ); if !needs_normalization(&value, self.param_env.reveal()) { @@ -1929,7 +1928,7 @@ fn assemble_candidates_from_impls<'cx, 'tcx>( // These traits have no associated types. selcx.tcx().sess.delay_span_bug( obligation.cause.span, - format!("Cannot project an associated type from `{:?}`", impl_source), + format!("Cannot project an associated type from `{impl_source:?}`"), ); return Err(()); } @@ -2299,8 +2298,7 @@ fn confirm_param_env_candidate<'cx, 'tcx>( } Err(e) => { let msg = format!( - "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}", - obligation, poly_cache_entry, e, + "Failed to unify obligation `{obligation:?}` with poly_projection `{poly_cache_entry:?}`: {e:?}", ); debug!("confirm_param_env_candidate: {}", msg); let err = Ty::new_error_with_message(infcx.tcx, obligation.cause.span, msg); diff --git a/compiler/rustc_trait_selection/src/traits/query/normalize.rs b/compiler/rustc_trait_selection/src/traits/query/normalize.rs index d45cf94f731f8..87beaddc6c200 100644 --- a/compiler/rustc_trait_selection/src/traits/query/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/query/normalize.rs @@ -299,7 +299,7 @@ impl<'cx, 'tcx> FallibleTypeFolder> for QueryNormalizer<'cx, 'tcx> if !tcx.sess.opts.actually_rustdoc { tcx.sess.delay_span_bug( DUMMY_SP, - format!("unexpected ambiguity: {:?} {:?}", c_data, result), + format!("unexpected ambiguity: {c_data:?} {result:?}"), ); } return Err(NoSolution); diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs index 5420caee32993..c99e018e9aee3 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs @@ -77,8 +77,7 @@ where let pre_obligations = infcx.take_registered_region_obligations(); assert!( pre_obligations.is_empty(), - "scrape_region_constraints: incoming region obligations = {:#?}", - pre_obligations, + "scrape_region_constraints: incoming region obligations = {pre_obligations:#?}", ); let value = infcx.commit_if_ok(|_| { @@ -92,7 +91,7 @@ where } else { Err(infcx.tcx.sess.delay_span_bug( DUMMY_SP, - format!("errors selecting obligation during MIR typeck: {:?}", errors), + format!("errors selecting obligation during MIR typeck: {errors:?}"), )) } })?; diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index e086489b1bcb6..bb009453c4ecb 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -74,22 +74,21 @@ impl IntercrateAmbiguityCause { match self { IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } => { let self_desc = if let Some(ty) = self_desc { - format!(" for type `{}`", ty) + format!(" for type `{ty}`") } else { 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 } => { let self_desc = if let Some(ty) = self_desc { - format!(" for type `{}`", ty) + format!(" for type `{ty}`") } else { String::new() }; format!( - "upstream crates may add a new impl of trait `{}`{} \ - in future versions", - trait_desc, self_desc + "upstream crates may add a new impl of trait `{trait_desc}`{self_desc} \ + in future versions" ) } IntercrateAmbiguityCause::ReservationImpl { message } => message.clone(), @@ -2443,8 +2442,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { let guar = self.infcx.tcx.sess.delay_span_bug( obligation.cause.span, format!( - "Impl {:?} was matchable against {:?} but now is not", - impl_def_id, obligation + "Impl {impl_def_id:?} was matchable against {obligation:?} but now is not" ), ); let value = self.infcx.fresh_args_for_item(obligation.cause.span, impl_def_id); diff --git a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs index b61b209654c1d..61e631c438db6 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs @@ -388,16 +388,16 @@ fn report_conflicting_impls<'tcx>( impl_span, format!( "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) => { let msg = match to_pretty_impl_header(tcx, overlap.with_impl) { 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); } @@ -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 - .extend(types_without_default_bounds.iter().map(|ty| format!("{}: ?Sized", ty))); + pretty_predicates.extend(types_without_default_bounds.iter().map(|ty| format!("{ty}: ?Sized"))); if !pretty_predicates.is_empty() { write!(w, "\n where {}", pretty_predicates.join(", ")).unwrap(); diff --git a/compiler/rustc_trait_selection/src/traits/util.rs b/compiler/rustc_trait_selection/src/traits/util.rs index 7b34908c4bed4..aa9a9b6b40a18 100644 --- a/compiler/rustc_trait_selection/src/traits/util.rs +++ b/compiler/rustc_trait_selection/src/traits/util.rs @@ -50,7 +50,7 @@ impl<'tcx> TraitAliasExpansionInfo<'tcx> { diag.span_label(self.top().1, top_label); if self.path.len() > 1 { 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 { @@ -58,7 +58,7 @@ impl<'tcx> TraitAliasExpansionInfo<'tcx> { // redundant labels. diag.span_label( self.bottom().1, - format!("trait alias used in trait object type ({})", use_desc), + format!("trait alias used in trait object type ({use_desc})"), ); } } diff --git a/compiler/rustc_trait_selection/src/traits/vtable.rs b/compiler/rustc_trait_selection/src/traits/vtable.rs index b4f614e3e2202..6a944e8316643 100644 --- a/compiler/rustc_trait_selection/src/traits/vtable.rs +++ b/compiler/rustc_trait_selection/src/traits/vtable.rs @@ -194,11 +194,7 @@ fn dump_vtable_entries<'tcx>( trait_ref: ty::PolyTraitRef<'tcx>, entries: &[VtblEntry<'tcx>], ) { - tcx.sess.emit_err(DumpVTableEntries { - span: sp, - trait_ref, - entries: format!("{:#?}", entries), - }); + tcx.sess.emit_err(DumpVTableEntries { span: sp, trait_ref, entries: format!("{entries:#?}") }); } fn has_own_existential_vtable_entries(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool { diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index e173bba49be0b..f89558a45999f 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -133,7 +133,7 @@ where _ => { tcx.sess.delay_span_bug( tcx.hir().span_if_local(def_id).unwrap_or(DUMMY_SP), - format!("unexpected generator witness type {:?}", witness), + format!("unexpected generator witness type {witness:?}"), ); return Some(Err(AlwaysRequiresDrop)); } diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index a7cd7aa2c4fb6..c2655d68b795f 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -408,7 +408,7 @@ pub fn debug_bound_var( var: impl std::fmt::Debug, ) -> Result<(), std::fmt::Error> { if debruijn == INNERMOST { - write!(fmt, "^{:?}", var) + write!(fmt, "^{var:?}") } else { write!(fmt, "^{}_{:?}", debruijn.index(), var) } diff --git a/library/core/src/net/ip_addr.rs b/library/core/src/net/ip_addr.rs index 56460c75eba9d..b902540b9f346 100644 --- a/library/core/src/net/ip_addr.rs +++ b/library/core/src/net/ip_addr.rs @@ -1863,7 +1863,7 @@ impl fmt::Display for Ipv6Addr { } else if self.is_loopback() { f.write_str("::1") } else if let Some(ipv4) = self.to_ipv4_mapped() { - write!(f, "::ffff:{}", ipv4) + write!(f, "::ffff:{ipv4}") } else { #[derive(Copy, Clone, Default)] struct Span { @@ -1899,10 +1899,10 @@ impl fmt::Display for Ipv6Addr { #[inline] fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result { if let Some((first, tail)) = chunk.split_first() { - write!(f, "{:x}", first)?; + write!(f, "{first:x}")?; for segment in tail { f.write_char(':')?; - write!(f, "{:x}", segment)?; + write!(f, "{segment:x}")?; } } Ok(()) @@ -1921,7 +1921,7 @@ impl fmt::Display for Ipv6Addr { let mut buf = DisplayBuffer::<{ LONGEST_IPV6_ADDR.len() }>::new(); // Buffer is long enough for the longest possible IPv6 address, so this should never fail. - write!(buf, "{}", self).unwrap(); + write!(buf, "{self}").unwrap(); f.pad(buf.as_str()) } diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index 95dcaf5dd7397..6cb9dd38c1d98 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -1434,8 +1434,7 @@ fn from_str_radix(src: &str, radix: u32) -> Result { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("panicked at ")?; if let Some(message) = self.message { - write!(formatter, "'{}', ", message)? + write!(formatter, "'{message}', ")? } else if let Some(payload) = self.payload.downcast_ref::<&'static str>() { - write!(formatter, "'{}', ", payload)? + write!(formatter, "'{payload}', ")? } // NOTE: we cannot use downcast_ref::() here // since String is not available in core! diff --git a/library/core/src/str/lossy.rs b/library/core/src/str/lossy.rs index 59f873d1268ce..b9b24b3865046 100644 --- a/library/core/src/str/lossy.rs +++ b/library/core/src/str/lossy.rs @@ -100,7 +100,7 @@ impl fmt::Debug for Debug<'_> { // Broken parts of string as hex escape. for &b in chunk.invalid() { - write!(f, "\\x{:02X}", b)?; + write!(f, "\\x{b:02X}")?; } } diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index 9a93bb72903f2..3b9005d97b475 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -111,14 +111,7 @@ fn slice_error_fail_rt(s: &str, begin: usize, end: usize) -> ! { } // 2. begin <= end - assert!( - begin <= end, - "begin <= end ({} <= {}) when slicing `{}`{}", - begin, - end, - s_trunc, - ellipsis - ); + assert!(begin <= end, "begin <= end ({begin} <= {end}) when slicing `{s_trunc}`{ellipsis}"); // 3. character boundary let index = if !s.is_char_boundary(begin) { begin } else { end }; diff --git a/library/core/src/time.rs b/library/core/src/time.rs index b08d5782ab6f4..7395a93d1e9aa 100644 --- a/library/core/src/time.rs +++ b/library/core/src/time.rs @@ -1115,10 +1115,10 @@ impl fmt::Debug for Duration { // padding (padding is calculated below). let emit_without_padding = |f: &mut fmt::Formatter<'_>| { if let Some(integer_part) = integer_part { - write!(f, "{}{}", prefix, integer_part)?; + write!(f, "{prefix}{integer_part}")?; } else { // u64::MAX + 1 == 18446744073709551616 - write!(f, "{}18446744073709551616", prefix)?; + write!(f, "{prefix}18446744073709551616")?; } // Write the decimal point and the fractional part (if any). @@ -1128,11 +1128,11 @@ impl fmt::Debug for Duration { let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) }; // If the user request a precision > 9, we pad '0's at the end. - let w = f.precision().unwrap_or(pos); - write!(f, ".{:0 Literal { - let quoted = format!("{:?}", string); + let quoted = format!("{string:?}"); assert!(quoted.starts_with('"') && quoted.ends_with('"')); let symbol = "ed[1..quoted.len() - 1]; Literal::new(bridge::LitKind::Str, symbol, None) @@ -1316,7 +1316,7 @@ impl Literal { /// Character literal. #[stable(feature = "proc_macro_lib2", since = "1.29.0")] pub fn character(ch: char) -> Literal { - let quoted = format!("{:?}", ch); + let quoted = format!("{ch:?}"); assert!(quoted.starts_with('\'') && quoted.ends_with('\'')); let symbol = "ed[1..quoted.len() - 1]; Literal::new(bridge::LitKind::Char, symbol, None) diff --git a/library/std/src/backtrace.rs b/library/std/src/backtrace.rs index 7543ffadd4140..7668ff418ad2c 100644 --- a/library/std/src/backtrace.rs +++ b/library/std/src/backtrace.rs @@ -218,17 +218,17 @@ impl fmt::Debug for BacktraceSymbol { write!(fmt, "{{ ")?; if let Some(fn_name) = self.name.as_ref().map(|b| backtrace_rs::SymbolName::new(b)) { - write!(fmt, "fn: \"{:#}\"", fn_name)?; + write!(fmt, "fn: \"{fn_name:#}\"")?; } else { write!(fmt, "fn: ")?; } if let Some(fname) = self.filename.as_ref() { - write!(fmt, ", file: \"{:?}\"", fname)?; + write!(fmt, ", file: \"{fname:?}\"")?; } if let Some(line) = self.lineno { - write!(fmt, ", line: {:?}", line)?; + write!(fmt, ", line: {line:?}")?; } write!(fmt, " }}") diff --git a/library/std/src/env.rs b/library/std/src/env.rs index d372fa64065f5..32a079cb809f8 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -291,7 +291,7 @@ impl fmt::Display for VarError { match *self { VarError::NotPresent => write!(f, "environment variable not found"), VarError::NotUnicode(ref s) => { - write!(f, "environment variable was not valid unicode: {:?}", s) + write!(f, "environment variable was not valid unicode: {s:?}") } } } diff --git a/library/std/src/io/error/repr_bitpacked.rs b/library/std/src/io/error/repr_bitpacked.rs index f94f88bac417e..361b4183c5648 100644 --- a/library/std/src/io/error/repr_bitpacked.rs +++ b/library/std/src/io/error/repr_bitpacked.rs @@ -194,8 +194,7 @@ impl Repr { // only run in std's tests, unless the user uses -Zbuild-std) debug_assert!( matches!(res.data(), ErrorData::Simple(k) if k == kind), - "repr(simple) encoding failed {:?}", - kind, + "repr(simple) encoding failed {kind:?}", ); res } @@ -256,7 +255,7 @@ where TAG_SIMPLE => { let kind_bits = (bits >> 32) as u32; let kind = kind_from_prim(kind_bits).unwrap_or_else(|| { - debug_assert!(false, "Invalid io::error::Repr bits: `Repr({:#018x})`", bits); + debug_assert!(false, "Invalid io::error::Repr bits: `Repr({bits:#018x})`"); // This means the `ptr` passed in was not valid, which violates // the unsafe contract of `decode_repr`. // diff --git a/library/std/src/sys/unix/process/process_common.rs b/library/std/src/sys/unix/process/process_common.rs index 640648e870748..e4d1f4f5664e8 100644 --- a/library/std/src/sys/unix/process/process_common.rs +++ b/library/std/src/sys/unix/process/process_common.rs @@ -569,7 +569,7 @@ impl fmt::Debug for Command { write!(f, "{:?}", self.args[0])?; for arg in &self.args[1..] { - write!(f, " {:?}", arg)?; + write!(f, " {arg:?}")?; } Ok(()) } diff --git a/library/std/src/sys/unix/process/process_unix.rs b/library/std/src/sys/unix/process/process_unix.rs index 0ce93af66ac0f..6bb443b54343e 100644 --- a/library/std/src/sys/unix/process/process_unix.rs +++ b/library/std/src/sys/unix/process/process_unix.rs @@ -146,8 +146,7 @@ impl Command { let (errno, footer) = bytes.split_at(4); assert_eq!( CLOEXEC_MSG_FOOTER, footer, - "Validation on the CLOEXEC pipe failed: {:?}", - bytes + "Validation on the CLOEXEC pipe failed: {bytes:?}" ); let errno = i32::from_be_bytes(errno.try_into().unwrap()); assert!(p.wait().is_ok(), "wait() should either return Ok or panic"); diff --git a/library/std/src/sys_common/wtf8.rs b/library/std/src/sys_common/wtf8.rs index 195d175cc9bde..e282ade7b7bee 100644 --- a/library/std/src/sys_common/wtf8.rs +++ b/library/std/src/sys_common/wtf8.rs @@ -541,7 +541,7 @@ impl fmt::Debug for Wtf8 { write_str_escaped(formatter, unsafe { str::from_utf8_unchecked(&self.bytes[pos..surrogate_pos]) })?; - write!(formatter, "\\u{{{:x}}}", surrogate)?; + write!(formatter, "\\u{{{surrogate:x}}}")?; pos = surrogate_pos + 3; } write_str_escaped(formatter, unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) })?; diff --git a/library/test/src/formatters/junit.rs b/library/test/src/formatters/junit.rs index a211ebf1ded16..755275580e2b0 100644 --- a/library/test/src/formatters/junit.rs +++ b/library/test/src/formatters/junit.rs @@ -35,7 +35,7 @@ fn str_to_cdata(s: &str) -> String { let escaped_output = escaped_output.replace('\n', "]]> ", ""); - format!("", escaped_output) + format!("") } impl OutputFormatter for JunitFormatter {