diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 1cfdc5b9e7f57..b4424f367449d 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -1650,10 +1650,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { augment_error(&mut err); - let is_insufficiently_polymorphic = - matches!(coercion_error, TypeError::RegionsInsufficientlyPolymorphic(..)); - - if !is_insufficiently_polymorphic && let Some(expr) = expression { + if let Some(expr) = expression { fcx.emit_coerce_suggestions( &mut err, expr, diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index b05cef56ad211..5b06088c34814 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -84,6 +84,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.annotate_expected_due_to_let_ty(err, expr, error); + // FIXME(#73154): For now, we do leak check when coercing function + // pointers in typeck, instead of only during borrowck. This can lead + // to these `RegionsInsufficientlyPolymorphic` errors that aren't helpful. + if matches!(error, Some(TypeError::RegionsInsufficientlyPolymorphic(..))) { + return; + } + if self.is_destruct_assignment_desugaring(expr) { return; } @@ -263,22 +270,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let expr_ty = self.resolve_vars_if_possible(checked_ty); let mut err = self.err_ctxt().report_mismatched_types(&cause, expected, expr_ty, e); - let is_insufficiently_polymorphic = - matches!(e, TypeError::RegionsInsufficientlyPolymorphic(..)); - - // FIXME(#73154): For now, we do leak check when coercing function - // pointers in typeck, instead of only during borrowck. This can lead - // to these `RegionsInsufficientlyPolymorphic` errors that aren't helpful. - if !is_insufficiently_polymorphic { - self.emit_coerce_suggestions( - &mut err, - expr, - expr_ty, - expected, - expected_ty_expr, - Some(e), - ); - } + self.emit_coerce_suggestions(&mut err, expr, expr_ty, expected, expected_ty_expr, Some(e)); (expected, Some(err)) } diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 75cca9733060d..15ed7fab65be2 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -1927,7 +1927,12 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { true }; - if should_suggest_fixes { + // FIXME(#73154): For now, we do leak check when coercing function + // pointers in typeck, instead of only during borrowck. This can lead + // to these `RegionsInsufficientlyPolymorphic` errors that aren't helpful. + if should_suggest_fixes + && !matches!(terr, TypeError::RegionsInsufficientlyPolymorphic(..)) + { self.suggest_tuple_pattern(cause, &exp_found, diag); self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag); self.suggest_await_on_expect_found(cause, span, &exp_found, diag); diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index cb8691aac138f..41aac02eaa97a 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -58,7 +58,7 @@ // To run alloc tests without x.py without ending up with two copies of alloc, Miri needs to be // able to "empty" this crate. See . -// rustc itself never sets the feature, so this line has no affect there. +// rustc itself never sets the feature, so this line has no effect there. #![cfg(any(not(feature = "miri-test-libstd"), test, doctest))] // #![allow(unused_attributes)] diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index faf48ae570fdd..3c127efb390ae 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -1406,6 +1406,22 @@ mod impls { _ => unsafe { unreachable_unchecked() }, } } + + #[inline] + fn min(self, other: bool) -> bool { + self & other + } + + #[inline] + fn max(self, other: bool) -> bool { + self | other + } + + #[inline] + fn clamp(self, min: bool, max: bool) -> bool { + assert!(min <= max); + self.max(min).min(max) + } } ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } diff --git a/library/core/src/error.rs b/library/core/src/error.rs index c32a54b77ef8e..1170221c10c43 100644 --- a/library/core/src/error.rs +++ b/library/core/src/error.rs @@ -130,6 +130,7 @@ pub trait Error: Debug + Display { /// /// ```rust /// #![feature(error_generic_member_access)] + /// #![feature(error_in_core)] /// use core::fmt; /// use core::error::{request_ref, Request}; /// @@ -360,6 +361,7 @@ impl dyn Error { /// /// ```rust /// # #![feature(error_generic_member_access)] +/// # #![feature(error_in_core)] /// use std::error::Error; /// use core::error::request_value; /// @@ -383,6 +385,7 @@ where /// /// ```rust /// # #![feature(error_generic_member_access)] +/// # #![feature(error_in_core)] /// use core::error::Error; /// use core::error::request_ref; /// @@ -454,6 +457,7 @@ where /// /// ``` /// #![feature(error_generic_member_access)] +/// #![feature(error_in_core)] /// use core::fmt; /// use core::error::Request; /// use core::error::request_ref; @@ -524,6 +528,7 @@ impl<'a> Request<'a> { /// /// ```rust /// #![feature(error_generic_member_access)] + /// #![feature(error_in_core)] /// /// use core::error::Request; /// @@ -558,6 +563,7 @@ impl<'a> Request<'a> { /// /// ```rust /// #![feature(error_generic_member_access)] + /// #![feature(error_in_core)] /// /// use core::error::Request; /// @@ -593,6 +599,7 @@ impl<'a> Request<'a> { /// /// ```rust /// #![feature(error_generic_member_access)] + /// #![feature(error_in_core)] /// /// use core::error::Request; /// @@ -625,6 +632,7 @@ impl<'a> Request<'a> { /// /// ```rust /// #![feature(error_generic_member_access)] + /// #![feature(error_in_core)] /// /// use core::error::Request; /// @@ -691,6 +699,7 @@ impl<'a> Request<'a> { /// /// ```rust /// #![feature(error_generic_member_access)] + /// #![feature(error_in_core)] /// /// use core::error::Request; /// use core::error::request_value; @@ -778,6 +787,7 @@ impl<'a> Request<'a> { /// /// ```rust /// #![feature(error_generic_member_access)] + /// #![feature(error_in_core)] /// /// use core::error::Request; /// use core::error::request_ref; diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index ded799160bf89..48c3c1f212344 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -51,7 +51,7 @@ #![cfg(not(test))] // To run core tests without x.py without ending up with two copies of core, Miri needs to be // able to "empty" this crate. See . -// rustc itself never sets the feature, so this line has no affect there. +// rustc itself never sets the feature, so this line has no effect there. #![cfg(any(not(feature = "miri-test-libstd"), test, doctest))] #![stable(feature = "core", since = "1.6.0")] #![doc( diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index c07aa5cd91fee..ac4ce222fbaac 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -190,7 +190,7 @@ // To run std tests without x.py without ending up with two copies of std, Miri needs to be // able to "empty" this crate. See . -// rustc itself never sets the feature, so this line has no affect there. +// rustc itself never sets the feature, so this line has no effect there. #![cfg(any(not(feature = "miri-test-libstd"), test, doctest))] // miri-test-libstd also prefers to make std use the sysroot versions of the dependencies. #![cfg_attr(feature = "miri-test-libstd", feature(rustc_private))] diff --git a/library/std/src/process.rs b/library/std/src/process.rs index f25ad2ece7144..f54d593417502 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -1530,10 +1530,19 @@ impl From for Stdio { // vs `_exit`. Naming of Unix system calls is not standardised across Unices, so terminology is a // matter of convention and tradition. For clarity we usually speak of `exit`, even when we might // mean an underlying system call such as `_exit`. -#[derive(PartialEq, Eq, Clone, Copy, Debug, Default)] +#[derive(PartialEq, Eq, Clone, Copy, Debug)] #[stable(feature = "process", since = "1.0.0")] pub struct ExitStatus(imp::ExitStatus); +/// The default value is one which indicates successful completion. +#[stable(feature = "process-exitcode-default", since = "CURRENT_RUSTC_VERSION")] +impl Default for ExitStatus { + fn default() -> Self { + // Ideally this would be done by ExitCode::default().into() but that is complicated. + ExitStatus::from_inner(imp::ExitStatus::default()) + } +} + /// Allows extension traits within `std`. #[unstable(feature = "sealed", issue = "none")] impl crate::sealed::Sealed for ExitStatus {} diff --git a/library/std/src/sys/wasi/thread.rs b/library/std/src/sys/wasi/thread.rs index d27b7a2e0f519..dbad425976a3b 100644 --- a/library/std/src/sys/wasi/thread.rs +++ b/library/std/src/sys/wasi/thread.rs @@ -20,9 +20,9 @@ cfg_if::cfg_if! { // https://github.com/WebAssembly/wasi-libc/blob/a6f871343313220b76009827ed0153586361c0d5/libc-top-half/musl/include/alltypes.h.in#L108 #[repr(C)] union pthread_attr_union { - __i: [ffi::c_int; if mem::size_of::() == 8 { 14 } else { 9 }], - __vi: [ffi::c_int; if mem::size_of::() == 8 { 14 } else { 9 }], - __s: [ffi::c_ulong; if mem::size_of::() == 8 { 7 } else { 9 }], + __i: [ffi::c_int; if mem::size_of::() == 8 { 14 } else { 9 }], + __vi: [ffi::c_int; if mem::size_of::() == 8 { 14 } else { 9 }], + __s: [ffi::c_ulong; if mem::size_of::() == 8 { 7 } else { 9 }], } #[repr(C)] diff --git a/src/doc/rustc/src/codegen-options/index.md b/src/doc/rustc/src/codegen-options/index.md index 4622148e86925..f882a31de5a8b 100644 --- a/src/doc/rustc/src/codegen-options/index.md +++ b/src/doc/rustc/src/codegen-options/index.md @@ -584,7 +584,7 @@ See the [Symbol Mangling] chapter for details on symbol mangling and the manglin This instructs `rustc` to generate code specifically for a particular processor. You can run `rustc --print target-cpus` to see the valid options to pass -and the default target CPU for the current buid target. +and the default target CPU for the current build target. Each target has a default base CPU. Special values include: * `native` can be passed to use the processor of the host machine. diff --git a/src/doc/rustc/src/platform-support/aarch64-unknown-teeos.md b/src/doc/rustc/src/platform-support/aarch64-unknown-teeos.md index 8fc5e6dd92b42..8bc9381342dd6 100644 --- a/src/doc/rustc/src/platform-support/aarch64-unknown-teeos.md +++ b/src/doc/rustc/src/platform-support/aarch64-unknown-teeos.md @@ -10,7 +10,7 @@ It's very small that there is no RwLock, no network, no stdin, and no file syste Some abbreviation: | Abbreviation | The full text | Description | | ---- | ---- | ---- | -| TEE | Trusted Execution Environment | ARM TrustZone devide the system into two worlds/modes -- the secure world/mode and the normal world/mode. TEE is in the secure world/mode. | +| TEE | Trusted Execution Environment | ARM TrustZone divides the system into two worlds/modes -- the secure world/mode and the normal world/mode. TEE is in the secure world/mode. | | REE | Rich Execution Environment | The normal world. for example, Linux for Android phone is in REE side. | | TA | Trusted Application | The app run in TEE side system. | | CA | Client Application | The progress run in REE side system. | diff --git a/src/doc/rustc/src/platform-support/loongarch-linux.md b/src/doc/rustc/src/platform-support/loongarch-linux.md index 17e85590f2c1f..e8f55b8bfce10 100644 --- a/src/doc/rustc/src/platform-support/loongarch-linux.md +++ b/src/doc/rustc/src/platform-support/loongarch-linux.md @@ -71,7 +71,7 @@ CXX_loongarch64_unknown_linux_gnu=/TOOLCHAIN_PATH/bin/loongarch64-unknown-linux- AR_loongarch64_unknown_linux_gnu=/TOOLCHAIN_PATH/bin/loongarch64-unknown-linux-gnu-gcc-ar \ CARGO_TARGET_LOONGARCH64_UNKNOWN_LINUX_GNUN_LINKER=/TOOLCHAIN_PATH/bin/loongarch64-unknown-linux-gnu-gcc \ # SET TARGET SYSTEM LIBRARY PATH -CARGO_TARGET_LOONGARCH64_UNKNOWN_LINUX_GNUN_RUNNER="qemu-loongarch64 -L /TOOLCHAIN_PATH/TARGET_LIBRAY_PATH" \ +CARGO_TARGET_LOONGARCH64_UNKNOWN_LINUX_GNUN_RUNNER="qemu-loongarch64 -L /TOOLCHAIN_PATH/TARGET_LIBRARY_PATH" \ cargo run --target loongarch64-unknown-linux-gnu --release ``` Tested on x86 architecture, other architectures not tested. diff --git a/src/doc/rustc/src/platform-support/netbsd.md b/src/doc/rustc/src/platform-support/netbsd.md index 23f4488de6e7f..3891d6d3148da 100644 --- a/src/doc/rustc/src/platform-support/netbsd.md +++ b/src/doc/rustc/src/platform-support/netbsd.md @@ -86,7 +86,7 @@ The Rust testsuite could presumably be run natively. For the systems where the maintainer can build natively, the rust compiler itself is re-built natively. This involves the rust compiler -being re-built with the newly self-built rust compiler, so excercises +being re-built with the newly self-built rust compiler, so exercises the result quite extensively. Additionally, for some systems we build `librsvg`, and for the more diff --git a/src/doc/rustc/src/platform-support/x86_64h-apple-darwin.md b/src/doc/rustc/src/platform-support/x86_64h-apple-darwin.md index 1a6f7bb834cf5..0fe9d4edaca10 100644 --- a/src/doc/rustc/src/platform-support/x86_64h-apple-darwin.md +++ b/src/doc/rustc/src/platform-support/x86_64h-apple-darwin.md @@ -20,7 +20,7 @@ will fail to load on machines that do not support this. It should support the full standard library (`std` and `alloc` either with default or user-defined allocators). This target is probably most useful when -targetted via cross-compilation (including from `x86_64-apple-darwin`), but if +targeted via cross-compilation (including from `x86_64-apple-darwin`), but if built manually, the host tools work. It is similar to `x86_64-apple-darwin` in nearly all respects, although the @@ -49,7 +49,7 @@ suite seems to work. Cross-compilation to this target from Apple hosts should generally work without much configuration, so long as XCode and the CommandLineTools are installed. -Targetting it from non-Apple hosts is difficult, but no moreso than targetting +Targeting it from non-Apple hosts is difficult, but no more so than targeting `x86_64-apple-darwin`. When compiling C code for this target, either the "`x86_64h-apple-macosx*`" LLVM diff --git a/src/doc/unstable-book/src/compiler-flags/path-options.md b/src/doc/unstable-book/src/compiler-flags/path-options.md index 0f2437020dd9f..0786ef1f16612 100644 --- a/src/doc/unstable-book/src/compiler-flags/path-options.md +++ b/src/doc/unstable-book/src/compiler-flags/path-options.md @@ -1,6 +1,6 @@ # `--print` Options -The behavior of the `--print` flag can be modified by optionally be specifiying a filepath +The behavior of the `--print` flag can be modified by optionally be specifying a filepath for each requested information kind, in the format `--print KIND=PATH`, just like for `--emit`. When a path is specified, information will be written there instead of to stdout. diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 68d636b360ac7..a06f31a932919 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -46,7 +46,7 @@ where let tcx = self.cx.tcx; let trait_ref = ty::Binder::dummy(ty::TraitRef::new(tcx, trait_def_id, [ty])); if !self.cx.generated_synthetics.insert((ty, trait_def_id)) { - debug!("get_auto_trait_impl_for({:?}): already generated, aborting", trait_ref); + debug!("get_auto_trait_impl_for({trait_ref:?}): already generated, aborting"); return None; } @@ -140,7 +140,7 @@ where let ty = tcx.type_of(item_def_id).instantiate_identity(); let f = auto_trait::AutoTraitFinder::new(tcx); - debug!("get_auto_trait_impls({:?})", ty); + debug!("get_auto_trait_impls({ty:?})"); let auto_traits: Vec<_> = self.cx.auto_traits.to_vec(); let mut auto_traits: Vec = auto_traits .into_iter() @@ -163,9 +163,9 @@ where fn get_lifetime(region: Region<'_>, names_map: &FxHashMap) -> Lifetime { region_name(region) .map(|name| { - names_map.get(&name).unwrap_or_else(|| { - panic!("Missing lifetime with name {:?} for {:?}", name.as_str(), region) - }) + names_map + .get(&name) + .unwrap_or_else(|| panic!("Missing lifetime with name {name:?} for {region:?}")) }) .unwrap_or(&Lifetime::statik()) .clone() @@ -372,7 +372,7 @@ where let output = output.as_ref().cloned().map(Box::new); if old_output.is_some() && old_output != output { - panic!("Output mismatch for {:?} {:?} {:?}", ty, old_output, output); + panic!("Output mismatch for {ty:?} {old_output:?} {output:?}"); } let new_params = GenericArgs::Parenthesized { inputs: old_input, output }; @@ -462,7 +462,7 @@ where ); let mut generic_params = raw_generics.params; - debug!("param_env_to_generics({:?}): generic_params={:?}", item_def_id, generic_params); + debug!("param_env_to_generics({item_def_id:?}): generic_params={generic_params:?}"); let mut has_sized = FxHashSet::default(); let mut ty_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default(); @@ -623,7 +623,7 @@ where // loop ty_to_traits.entry(ty.clone()).or_default().insert(trait_.clone()); } - _ => panic!("Unexpected LHS {:?} for {:?}", lhs, item_def_id), + _ => panic!("Unexpected LHS {lhs:?} for {item_def_id:?}"), } } }; @@ -710,7 +710,7 @@ where /// involved (impls rarely have more than a few bounds) means that it /// shouldn't matter in practice. fn unstable_debug_sort(&self, vec: &mut [T]) { - vec.sort_by_cached_key(|x| format!("{:?}", x)) + vec.sort_by_cached_key(|x| format!("{x:?}")) } fn is_fn_trait(&self, path: &Path) -> bool { diff --git a/src/librustdoc/clean/blanket_impl.rs b/src/librustdoc/clean/blanket_impl.rs index 9d744237b577a..dad2aa4061d6c 100644 --- a/src/librustdoc/clean/blanket_impl.rs +++ b/src/librustdoc/clean/blanket_impl.rs @@ -17,7 +17,7 @@ impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> { let param_env = cx.tcx.param_env(item_def_id); let ty = cx.tcx.type_of(item_def_id); - trace!("get_blanket_impls({:?})", ty); + trace!("get_blanket_impls({ty:?})"); let mut impls = Vec::new(); for trait_def_id in cx.tcx.all_traits() { if !cx.cache.effective_visibilities.is_reachable(cx.tcx, trait_def_id) @@ -72,7 +72,7 @@ impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> { .into_iter() .chain(Some(ty::Binder::dummy(impl_trait_ref).to_predicate(infcx.tcx))); for predicate in predicates { - debug!("testing predicate {:?}", predicate); + debug!("testing predicate {predicate:?}"); let obligation = traits::Obligation::new( infcx.tcx, traits::ObligationCause::dummy(), diff --git a/src/librustdoc/clean/cfg.rs b/src/librustdoc/clean/cfg.rs index 7652f27e51c57..ab5aec12fe7cb 100644 --- a/src/librustdoc/clean/cfg.rs +++ b/src/librustdoc/clean/cfg.rs @@ -434,9 +434,9 @@ impl<'a> fmt::Display for Display<'a> { } if let (true, Cfg::Cfg(_, Some(feat))) = (short_longhand, sub_cfg) { if self.1.is_html() { - write!(fmt, "{}", feat)?; + write!(fmt, "{feat}")?; } else { - write!(fmt, "`{}`", feat)?; + write!(fmt, "`{feat}`")?; } } else { write_with_opt_paren(fmt, !sub_cfg.is_all(), Display(sub_cfg, self.1))?; @@ -471,9 +471,9 @@ impl<'a> fmt::Display for Display<'a> { } if let (true, Cfg::Cfg(_, Some(feat))) = (short_longhand, sub_cfg) { if self.1.is_html() { - write!(fmt, "{}", feat)?; + write!(fmt, "{feat}")?; } else { - write!(fmt, "`{}`", feat)?; + write!(fmt, "`{feat}`")?; } } else { write_with_opt_paren(fmt, !sub_cfg.is_simple(), Display(sub_cfg, self.1))?; @@ -552,21 +552,21 @@ impl<'a> fmt::Display for Display<'a> { "sgx" => "SGX", _ => "", }, - (sym::target_endian, Some(endian)) => return write!(fmt, "{}-endian", endian), - (sym::target_pointer_width, Some(bits)) => return write!(fmt, "{}-bit", bits), + (sym::target_endian, Some(endian)) => return write!(fmt, "{endian}-endian"), + (sym::target_pointer_width, Some(bits)) => return write!(fmt, "{bits}-bit"), (sym::target_feature, Some(feat)) => match self.1 { Format::LongHtml => { - return write!(fmt, "target feature {}", feat); + return write!(fmt, "target feature {feat}"); } - Format::LongPlain => return write!(fmt, "target feature `{}`", feat), - Format::ShortHtml => return write!(fmt, "{}", feat), + Format::LongPlain => return write!(fmt, "target feature `{feat}`"), + Format::ShortHtml => return write!(fmt, "{feat}"), }, (sym::feature, Some(feat)) => match self.1 { Format::LongHtml => { - return write!(fmt, "crate feature {}", feat); + return write!(fmt, "crate feature {feat}"); } - Format::LongPlain => return write!(fmt, "crate feature `{}`", feat), - Format::ShortHtml => return write!(fmt, "{}", feat), + Format::LongPlain => return write!(fmt, "crate feature `{feat}`"), + Format::ShortHtml => return write!(fmt, "{feat}"), }, _ => "", }; @@ -581,12 +581,12 @@ impl<'a> fmt::Display for Display<'a> { Escape(v.as_str()) ) } else { - write!(fmt, r#"`{}="{}"`"#, name, v) + write!(fmt, r#"`{name}="{v}"`"#) } } else if self.1.is_html() { write!(fmt, "{}", Escape(name.as_str())) } else { - write!(fmt, "`{}`", name) + write!(fmt, "`{name}`") } } } diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 2456e8818eba5..cac2113074042 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -50,7 +50,7 @@ pub(crate) fn try_inline( } let mut ret = Vec::new(); - debug!("attrs={:?}", attrs); + debug!("attrs={attrs:?}"); let attrs_without_docs = attrs.map(|(attrs, def_id)| { (attrs.into_iter().filter(|a| a.doc_str().is_none()).cloned().collect::>(), def_id) @@ -529,7 +529,7 @@ pub(crate) fn build_impl( } let (merged_attrs, cfg) = merge_attrs(cx, load_attrs(cx, did), attrs); - trace!("merged_attrs={:?}", merged_attrs); + trace!("merged_attrs={merged_attrs:?}"); trace!( "build_impl: impl {:?} for {:?}", @@ -781,7 +781,7 @@ pub(crate) fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) { cx.active_extern_traits.insert(did); } - debug!("record_extern_trait: {:?}", did); + debug!("record_extern_trait: {did:?}"); let trait_ = build_external_trait(cx, did); cx.external_traits.borrow_mut().insert(did, trait_); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 624f1620f2cb8..ee1d0be27bfda 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -215,7 +215,7 @@ pub(crate) fn clean_trait_ref_with_bindings<'tcx>( ) -> Path { let kind = cx.tcx.def_kind(trait_ref.def_id()).into(); if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) { - span_bug!(cx.tcx.def_span(trait_ref.def_id()), "`TraitRef` had unexpected kind {:?}", kind); + span_bug!(cx.tcx.def_span(trait_ref.def_id()), "`TraitRef` had unexpected kind {kind:?}"); } inline::record_extern_fqn(cx, trait_ref.def_id(), kind); let path = @@ -304,7 +304,7 @@ pub(crate) fn clean_middle_region<'tcx>(region: ty::Region<'tcx>) -> Option { - debug!("cannot clean region {:?}", region); + debug!("cannot clean region {region:?}"); None } } @@ -1867,11 +1867,11 @@ fn normalize<'tcx>( .map(|resolved| infcx.resolve_vars_if_possible(resolved.value)); match normalized { Ok(normalized_value) => { - debug!("normalized {:?} to {:?}", ty, normalized_value); + debug!("normalized {ty:?} to {normalized_value:?}"); Some(normalized_value) } Err(err) => { - debug!("failed to normalize {:?}: {:?}", ty, err); + debug!("failed to normalize {ty:?}: {err:?}"); None } } diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index cb089ddd09a39..49bde1d315266 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -78,7 +78,7 @@ impl ItemId { #[track_caller] pub(crate) fn expect_def_id(self) -> DefId { self.as_def_id() - .unwrap_or_else(|| panic!("ItemId::expect_def_id: `{:?}` isn't a DefId", self)) + .unwrap_or_else(|| panic!("ItemId::expect_def_id: `{self:?}` isn't a DefId")) } #[inline] @@ -352,7 +352,7 @@ fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool { match tcx.def_kind(parent) { DefKind::Struct | DefKind::Union => false, DefKind::Variant => true, - parent_kind => panic!("unexpected parent kind: {:?}", parent_kind), + parent_kind => panic!("unexpected parent kind: {parent_kind:?}"), } } @@ -436,7 +436,7 @@ impl Item { attrs: Box, cfg: Option>, ) -> Item { - trace!("name={:?}, def_id={:?} cfg={:?}", name, def_id, cfg); + trace!("name={name:?}, def_id={def_id:?} cfg={cfg:?}"); Item { item_id: def_id.into(), diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 3c79ce5778222..80a7a33d2bda2 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -218,7 +218,7 @@ pub(crate) fn build_deref_target_impls( pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol { use rustc_hir::*; - debug!("trying to get a name from pattern: {:?}", p); + debug!("trying to get a name from pattern: {p:?}"); Symbol::intern(&match p.kind { PatKind::Wild | PatKind::Struct(..) => return kw::Underscore, @@ -461,7 +461,7 @@ pub(crate) fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String { /// Given a type Path, resolve it to a Type using the TyCtxt pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type { - debug!("resolve_type({:?})", path); + debug!("resolve_type({path:?})"); match path.res { Res::PrimTy(p) => Primitive(PrimitiveType::from(p)), @@ -500,7 +500,7 @@ pub(crate) fn get_auto_trait_and_blanket_impls( /// [`href()`]: crate::html::format::href pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId { use DefKind::*; - debug!("register_res({:?})", res); + debug!("register_res({res:?})"); let (kind, did) = match res { Res::Def( @@ -523,7 +523,7 @@ pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId { did, ) => (kind.into(), did), - _ => panic!("register_res: unexpected {:?}", res), + _ => panic!("register_res: unexpected {res:?}"), }; if did.is_local() { return did; @@ -601,8 +601,12 @@ pub(super) fn render_macro_arms<'a>( ) -> String { let mut out = String::new(); for matcher in matchers { - writeln!(out, " {} => {{ ... }}{}", render_macro_matcher(tcx, matcher), arm_delim) - .unwrap(); + writeln!( + out, + " {matcher} => {{ ... }}{arm_delim}", + matcher = render_macro_matcher(tcx, matcher), + ) + .unwrap(); } out } @@ -618,21 +622,21 @@ pub(super) fn display_macro_source( let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]); if def.macro_rules { - format!("macro_rules! {} {{\n{}}}", name, render_macro_arms(cx.tcx, matchers, ";")) + format!("macro_rules! {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ";")) } else { if matchers.len() <= 1 { format!( - "{}macro {}{} {{\n ...\n}}", - visibility_to_src_with_space(Some(vis), cx.tcx, def_id), - name, - matchers.map(|matcher| render_macro_matcher(cx.tcx, matcher)).collect::(), + "{vis}macro {name}{matchers} {{\n ...\n}}", + vis = visibility_to_src_with_space(Some(vis), cx.tcx, def_id), + matchers = matchers + .map(|matcher| render_macro_matcher(cx.tcx, matcher)) + .collect::(), ) } else { format!( - "{}macro {} {{\n{}}}", - visibility_to_src_with_space(Some(vis), cx.tcx, def_id), - name, - render_macro_arms(cx.tcx, matchers, ","), + "{vis}macro {name} {{\n{arms}}}", + vis = visibility_to_src_with_space(Some(vis), cx.tcx, def_id), + arms = render_macro_arms(cx.tcx, matchers, ","), ) } } diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 217f1a6ee6b66..81fb13f4166bc 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -50,7 +50,7 @@ impl TryFrom<&str> for OutputFormat { match value { "json" => Ok(OutputFormat::Json), "html" => Ok(OutputFormat::Html), - _ => Err(format!("unknown output format `{}`", value)), + _ => Err(format!("unknown output format `{value}`")), } } } @@ -383,7 +383,7 @@ impl Options { match kind.parse() { Ok(kind) => emit.push(kind), Err(()) => { - diag.err(format!("unrecognized emission type: {}", kind)); + diag.err(format!("unrecognized emission type: {kind}")); return Err(1); } } @@ -415,7 +415,7 @@ impl Options { println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)"); for theme_file in to_check.iter() { - print!(" - Checking \"{}\"...", theme_file); + print!(" - Checking \"{theme_file}\"..."); let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag); if !differences.is_empty() || !success { println!(" FAILED"); @@ -556,30 +556,28 @@ impl Options { matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned())) { if !theme_file.is_file() { - diag.struct_err(format!("invalid argument: \"{}\"", theme_s)) + diag.struct_err(format!("invalid argument: \"{theme_s}\"")) .help("arguments to --theme must be files") .emit(); return Err(1); } if theme_file.extension() != Some(OsStr::new("css")) { - diag.struct_err(format!("invalid argument: \"{}\"", theme_s)) + diag.struct_err(format!("invalid argument: \"{theme_s}\"")) .help("arguments to --theme must have a .css extension") .emit(); return Err(1); } let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag); if !success { - diag.struct_err(format!("error loading theme file: \"{}\"", theme_s)).emit(); + diag.struct_err(format!("error loading theme file: \"{theme_s}\"")).emit(); return Err(1); } else if !ret.is_empty() { diag.struct_warn(format!( - "theme file \"{}\" is missing CSS rules from the default theme", - theme_s + "theme file \"{theme_s}\" is missing CSS rules from the default theme", )) .warn("the theme may appear incorrect when loaded") .help(format!( - "to see what rules are missing, call `rustdoc --check-theme \"{}\"`", - theme_s + "to see what rules are missing, call `rustdoc --check-theme \"{theme_s}\"`", )) .emit(); } @@ -608,7 +606,7 @@ impl Options { match matches.opt_str("r").as_deref() { Some("rust") | None => {} Some(s) => { - diag.struct_err(format!("unknown input format: {}", s)).emit(); + diag.struct_err(format!("unknown input format: {s}")).emit(); return Err(1); } } @@ -628,7 +626,7 @@ impl Options { let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) { Ok(types) => types, Err(e) => { - diag.struct_err(format!("unknown crate type: {}", e)).emit(); + diag.struct_err(format!("unknown crate type: {e}")).emit(); return Err(1); } }; @@ -787,7 +785,7 @@ fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Han for &flag in deprecated_flags.iter() { if matches.opt_present(flag) { - diag.struct_warn(format!("the `{}` flag is deprecated", flag)) + diag.struct_warn(format!("the `{flag}` flag is deprecated")) .note( "see issue #44136 \ for more information", @@ -800,7 +798,7 @@ fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Han for &flag in removed_flags.iter() { if matches.opt_present(flag) { - let mut err = diag.struct_warn(format!("the `{}` flag no longer functions", flag)); + let mut err = diag.struct_warn(format!("the `{flag}` flag no longer functions")); err.note( "see issue #44136 \ for more information", diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index d7da812099697..4c8dab61f0cbf 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -283,7 +283,7 @@ pub(crate) fn create_config( let hir = tcx.hir(); let body = hir.body(hir.body_owned_by(def_id)); - debug!("visiting body for {:?}", def_id); + debug!("visiting body for {def_id:?}"); EmitIgnoredResolutionErrors::new(tcx).visit_body(body); (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id) }; @@ -377,7 +377,7 @@ pub(crate) fn run_global_ctxt( fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler, sp: Span) { let mut msg = - diag.struct_span_warn(sp, format!("the `#![doc({})]` attribute is deprecated", name)); + diag.struct_span_warn(sp, format!("the `#![doc({name})]` attribute is deprecated")); msg.note( "see issue #44136 \ for more information", @@ -470,7 +470,7 @@ impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> { } fn visit_path(&mut self, path: &Path<'tcx>, _id: HirId) { - debug!("visiting path {:?}", path); + debug!("visiting path {path:?}"); if path.res == Res::Err { // We have less context here than in rustc_resolve, // so we can only emit the name and span. @@ -487,8 +487,7 @@ impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> { self.tcx.sess, path.span, E0433, - "failed to resolve: {}", - label + "failed to resolve: {label}", ); err.span_label(path.span, label); err.note("this error was originally ignored because you are running `rustdoc`"); diff --git a/src/librustdoc/docfs.rs b/src/librustdoc/docfs.rs index d58b8dc6ad4a4..82c1a503924c0 100644 --- a/src/librustdoc/docfs.rs +++ b/src/librustdoc/docfs.rs @@ -72,9 +72,9 @@ impl DocFS { let sender = self.errors.clone().expect("can't write after closing"); self.pool.execute(move || { fs::write(&path, contents).unwrap_or_else(|e| { - sender.send(format!("\"{}\": {}", path.display(), e)).unwrap_or_else(|_| { - panic!("failed to send error on \"{}\"", path.display()) - }) + sender.send(format!("\"{path}\": {e}", path = path.display())).unwrap_or_else( + |_| panic!("failed to send error on \"{}\"", path.display()), + ) }); }); } else { diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 3315ccad4d367..24333a21dd622 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -192,7 +192,7 @@ pub(crate) fn run(options: RustdocOptions) -> Result<(), ErrorGuaranteed> { // The allow lint level is not expected, // as if allow is specified, no message // is to be emitted. - v => unreachable!("Invalid lint level '{}'", v), + v => unreachable!("Invalid lint level '{v}'"), }) .unwrap_or("warn") .to_string(); @@ -404,7 +404,7 @@ fn run_test( compiler.stdin(Stdio::piped()); compiler.stderr(Stdio::piped()); - debug!("compiler invocation for doctest: {:?}", compiler); + debug!("compiler invocation for doctest: {compiler:?}"); let mut child = compiler.spawn().expect("Failed to spawn rustc process"); { @@ -933,7 +933,7 @@ impl Collector { if !item_path.is_empty() { item_path.push(' '); } - format!("{} - {}(line {})", filename.prefer_local(), item_path, line) + format!("{} - {item_path}(line {line})", filename.prefer_local()) } pub(crate) fn set_position(&mut self, position: Span) { @@ -1010,7 +1010,7 @@ impl Tester for Collector { path.push(&test_id); if let Err(err) = std::fs::create_dir_all(&path) { - eprintln!("Couldn't create directory for doctest executables: {}", err); + eprintln!("Couldn't create directory for doctest executables: {err}"); panic::resume_unwind(Box::new(())); } @@ -1079,7 +1079,7 @@ impl Tester for Collector { eprint!("Test executable succeeded, but it's marked `should_panic`."); } TestFailure::MissingErrorCodes(codes) => { - eprint!("Some expected error codes were not found: {:?}", codes); + eprint!("Some expected error codes were not found: {codes:?}"); } TestFailure::ExecutionError(err) => { eprint!("Couldn't run the test: {err}"); diff --git a/src/librustdoc/externalfiles.rs b/src/librustdoc/externalfiles.rs index 88049c4ca0051..f0ebb8e5a3905 100644 --- a/src/librustdoc/externalfiles.rs +++ b/src/librustdoc/externalfiles.rs @@ -37,8 +37,7 @@ impl ExternalHtml { let bc = load_external_files(before_content, diag)?; let m_bc = load_external_files(md_before_content, diag)?; let bc = format!( - "{}{}", - bc, + "{bc}{}", Markdown { content: &m_bc, links: &[], @@ -53,8 +52,7 @@ impl ExternalHtml { let ac = load_external_files(after_content, diag)?; let m_ac = load_external_files(md_after_content, diag)?; let ac = format!( - "{}{}", - ac, + "{ac}{}", Markdown { content: &m_ac, links: &[], @@ -83,7 +81,11 @@ pub(crate) fn load_string>( let contents = match fs::read(file_path) { Ok(bytes) => bytes, Err(e) => { - diag.struct_err(format!("error reading `{}`: {}", file_path.display(), e)).emit(); + diag.struct_err(format!( + "error reading `{file_path}`: {e}", + file_path = file_path.display() + )) + .emit(); return Err(LoadStringError::ReadFail); } }; diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 58022046294be..2f611c31a0746 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -109,6 +109,10 @@ impl Buffer { self.buffer } + pub(crate) fn push(&mut self, c: char) { + self.buffer.push(c); + } + pub(crate) fn push_str(&mut self, s: &str) { self.buffer.push_str(s); } @@ -228,9 +232,9 @@ impl clean::GenericParamDef { if let Some(default) = default { if f.alternate() { - write!(f, " = {:#}", default)?; + write!(f, " = {default:#}")?; } else { - write!(f, " = {}", default)?; + write!(f, " = {default}")?; } } @@ -451,9 +455,9 @@ impl clean::GenericBound { hir::TraitBoundModifier::MaybeConst => "", }; if f.alternate() { - write!(f, "{}{:#}", modifier_str, ty.print(cx)) + write!(f, "{modifier_str}{ty:#}", ty = ty.print(cx)) } else { - write!(f, "{}{}", modifier_str, ty.print(cx)) + write!(f, "{modifier_str}{ty}", ty = ty.print(cx)) } } }) @@ -599,7 +603,7 @@ fn generate_macro_def_id_path( let cstore = CStore::from_tcx(tcx); // We need this to prevent a `panic` when this function is used from intra doc links... if !cstore.has_crate_data(def_id.krate) { - debug!("No data for crate {}", crate_name); + debug!("No data for crate {crate_name}"); return Err(HrefError::NotInExternalCache); } // Check to see if it is a macro 2.0 or built-in macro. @@ -631,19 +635,18 @@ fn generate_macro_def_id_path( let url = match cache.extern_locations[&def_id.krate] { ExternalLocation::Remote(ref s) => { // `ExternalLocation::Remote` always end with a `/`. - format!("{}{}", s, path.iter().map(|p| p.as_str()).join("/")) + format!("{s}{path}", path = path.iter().map(|p| p.as_str()).join("/")) } ExternalLocation::Local => { // `root_path` always end with a `/`. format!( - "{}{}/{}", - root_path.unwrap_or(""), - crate_name, - path.iter().map(|p| p.as_str()).join("/") + "{root_path}{crate_name}/{path}", + root_path = root_path.unwrap_or(""), + path = path.iter().map(|p| p.as_str()).join("/") ) } ExternalLocation::Unknown => { - debug!("crate {} not in cache when linkifying macros", crate_name); + debug!("crate {crate_name} not in cache when linkifying macros"); return Err(HrefError::NotInExternalCache); } }; @@ -732,7 +735,7 @@ pub(crate) fn href_with_root_path( _ => { let prefix = shortty.as_str(); let last = fqp.last().unwrap(); - url_parts.push_fmt(format_args!("{}.{}.html", prefix, last)); + url_parts.push_fmt(format_args!("{prefix}.{last}.html")); } } Ok((url_parts.finish(), shortty, fqp.to_vec())) @@ -828,9 +831,9 @@ fn resolved_path<'cx>( let path = if use_absolute { if let Ok((_, _, fqp)) = href(did, cx) { format!( - "{}::{}", - join_with_double_colon(&fqp[..fqp.len() - 1]), - anchor(did, *fqp.last().unwrap(), cx) + "{path}::{anchor}", + path = join_with_double_colon(&fqp[..fqp.len() - 1]), + anchor = anchor(did, *fqp.last().unwrap(), cx) ) } else { last.name.to_string() @@ -838,7 +841,7 @@ fn resolved_path<'cx>( } else { anchor(did, last.name, cx).to_string() }; - write!(w, "{}{}", path, last.args.print(cx))?; + write!(w, "{path}{args}", args = last.args.print(cx))?; } Ok(()) } @@ -906,7 +909,7 @@ fn primitive_link_fragment( None => {} } } - write!(f, "{}", name)?; + f.write_str(name)?; if needs_termination { write!(f, "")?; } @@ -946,15 +949,11 @@ pub(crate) fn anchor<'a, 'cx: 'a>( if let Ok((url, short_ty, fqp)) = parts { write!( f, - r#"{}"#, - short_ty, - url, - short_ty, - join_with_double_colon(&fqp), - text.as_str() + r#"{text}"#, + path = join_with_double_colon(&fqp), ) } else { - write!(f, "{}", text) + f.write_str(text.as_str()) } }) } @@ -965,10 +964,10 @@ fn fmt_type<'cx>( use_absolute: bool, cx: &'cx Context<'_>, ) -> fmt::Result { - trace!("fmt_type(t = {:?})", t); + trace!("fmt_type(t = {t:?})"); match *t { - clean::Generic(name) => write!(f, "{}", name), + clean::Generic(name) => f.write_str(name.as_str()), clean::Type::Path { ref path } => { // Paths like `T::Output` and `Self::Output` should be rendered with all segments. let did = path.def_id(); @@ -1085,13 +1084,13 @@ fn fmt_type<'cx>( if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() { let text = if f.alternate() { - format!("*{} {:#}", m, t.print(cx)) + format!("*{m} {ty:#}", ty = t.print(cx)) } else { - format!("*{} {}", m, t.print(cx)) + format!("*{m} {ty}", ty = t.print(cx)) }; primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx) } else { - primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?; + primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{m} "), cx)?; fmt::Display::fmt(&t.print(cx), f) } } @@ -1445,11 +1444,20 @@ impl clean::FnDecl { clean::SelfValue => { write!(f, "self")?; } - clean::SelfBorrowed(Some(ref lt), mtbl) => { - write!(f, "{}{} {}self", amp, lt.print(), mtbl.print_with_space())?; + clean::SelfBorrowed(Some(ref lt), mutability) => { + write!( + f, + "{amp}{lifetime} {mutability}self", + lifetime = lt.print(), + mutability = mutability.print_with_space(), + )?; } - clean::SelfBorrowed(None, mtbl) => { - write!(f, "{}{}self", amp, mtbl.print_with_space())?; + clean::SelfBorrowed(None, mutability) => { + write!( + f, + "{amp}{mutability}self", + mutability = mutability.print_with_space(), + )?; } clean::SelfExplicit(ref typ) => { write!(f, "self: ")?; @@ -1523,7 +1531,7 @@ pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>( "pub(super) ".into() } else { let path = cx.tcx().def_path(vis_did); - debug!("path={:?}", path); + debug!("path={path:?}"); // modified from `resolved_path()` to work with `DefPathData` let last_name = path.data.last().unwrap().data.get_opt_name().unwrap(); let anchor = anchor(vis_did, last_name, cx); @@ -1532,12 +1540,12 @@ pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>( for seg in &path.data[..path.data.len() - 1] { let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap()); } - let _ = write!(s, "{}) ", anchor); + let _ = write!(s, "{anchor}) "); s.into() } } }; - display_fn(move |f| write!(f, "{}", to_print)) + display_fn(move |f| f.write_str(&to_print)) } /// This function is the same as print_with_space, except that it renders no links. @@ -1632,7 +1640,7 @@ impl clean::Import { if name == self.source.path.last() { write!(f, "use {};", self.source.print(cx)) } else { - write!(f, "use {} as {};", self.source.print(cx), name) + write!(f, "use {source} as {name};", source = self.source.print(cx)) } } clean::ImportKind::Glob => { @@ -1661,7 +1669,7 @@ impl clean::ImportSource { if let hir::def::Res::PrimTy(p) = self.path.res { primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?; } else { - write!(f, "{}", name)?; + f.write_str(name.as_str())?; } Ok(()) } diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index a99ac0f4e052a..039e8cdb98738 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -929,15 +929,15 @@ fn string_without_closing_tag( open_tag: bool, ) -> Option<&'static str> { let Some(klass) = klass else { - write!(out, "{}", text).unwrap(); + write!(out, "{text}").unwrap(); return None; }; let Some(def_span) = klass.get_span() else { if !open_tag { - write!(out, "{}", text).unwrap(); + write!(out, "{text}").unwrap(); return None; } - write!(out, "{}", klass.as_html(), text).unwrap(); + write!(out, "{text}", klass = klass.as_html()).unwrap(); return Some(""); }; @@ -947,14 +947,17 @@ fn string_without_closing_tag( match t { "self" | "Self" => write!( &mut path, - "{}", - Class::Self_(DUMMY_SP).as_html(), - t + "{t}", + klass = Class::Self_(DUMMY_SP).as_html(), ), "crate" | "super" => { - write!(&mut path, "{}", Class::KeyWord.as_html(), t) + write!( + &mut path, + "{t}", + klass = Class::KeyWord.as_html(), + ) } - t => write!(&mut path, "{}", t), + t => write!(&mut path, "{t}"), } .expect("Failed to build source HTML path"); path @@ -997,13 +1000,13 @@ fn string_without_closing_tag( if !open_tag { // We're already inside an element which has the same klass, no need to give it // again. - write!(out, "{}", href, text_s).unwrap(); + write!(out, "{text_s}").unwrap(); } else { let klass_s = klass.as_html(); if klass_s.is_empty() { - write!(out, "{}", href, text_s).unwrap(); + write!(out, "{text_s}").unwrap(); } else { - write!(out, "{}", klass_s, href, text_s).unwrap(); + write!(out, "{text_s}").unwrap(); } } return Some(""); @@ -1018,7 +1021,7 @@ fn string_without_closing_tag( out.write_str(&text_s).unwrap(); Some("") } else { - write!(out, "{}", klass_s, text_s).unwrap(); + write!(out, "{text_s}").unwrap(); Some("") } } diff --git a/src/librustdoc/html/highlight/tests.rs b/src/librustdoc/html/highlight/tests.rs index 2c93b9a097f40..4c0874a686fe9 100644 --- a/src/librustdoc/html/highlight/tests.rs +++ b/src/librustdoc/html/highlight/tests.rs @@ -23,7 +23,7 @@ fn test_html_highlighting() { let html = { let mut out = Buffer::new(); write_code(&mut out, src, None, None); - format!("{}
{}
\n", STYLE, out.into_inner()) + format!("{STYLE}
{}
\n", out.into_inner()) }; expect_file!["fixtures/sample.html"].assert_eq(&html); }); diff --git a/src/librustdoc/html/length_limit.rs b/src/librustdoc/html/length_limit.rs index 4c8db2c6784a5..8562e103dc17e 100644 --- a/src/librustdoc/html/length_limit.rs +++ b/src/librustdoc/html/length_limit.rs @@ -78,8 +78,7 @@ impl HtmlWithLimit { pub(super) fn open_tag(&mut self, tag_name: &'static str) { assert!( tag_name.chars().all(|c| ('a'..='z').contains(&c)), - "tag_name contained non-alphabetic chars: {:?}", - tag_name + "tag_name contained non-alphabetic chars: {tag_name:?}", ); self.queued_tags.push(tag_name); } @@ -88,7 +87,7 @@ impl HtmlWithLimit { pub(super) fn close_tag(&mut self) { match self.unclosed_tags.pop() { // Close the most recently opened tag. - Some(tag_name) => write!(self.buf, "", tag_name).unwrap(), + Some(tag_name) => write!(self.buf, "").unwrap(), // There are valid cases where `close_tag()` is called without // there being any tags to close. For example, this occurs when // a tag is opened after the length limit is exceeded; @@ -101,7 +100,7 @@ impl HtmlWithLimit { /// Write all queued tags and add them to the `unclosed_tags` list. fn flush_queue(&mut self) { for tag_name in self.queued_tags.drain(..) { - write!(self.buf, "<{}>", tag_name).unwrap(); + write!(self.buf, "<{tag_name}>").unwrap(); self.unclosed_tags.push(tag_name); } diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 3fb7122fad35c..84c382a48ff6f 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -246,10 +246,9 @@ impl<'a, I: Iterator>> Iterator for CodeBlocks<'_, 'a, I> { return Some(Event::Html( format!( "
\ -
{}
\ +
{text}
\
", - lang, - Escape(&original_text), + text = Escape(&original_text), ) .into(), )); @@ -288,8 +287,9 @@ impl<'a, I: Iterator>> Iterator for CodeBlocks<'_, 'a, I> { let test_escaped = small_url_encode(test); Some(format!( - r#"Run"#, - url, test_escaped, channel, edition, + r#"Run"#, )) }); @@ -308,7 +308,7 @@ impl<'a, I: Iterator>> Iterator for CodeBlocks<'_, 'a, I> { // insert newline to clearly separate it from the // previous block so we can shorten the html output let mut s = Buffer::new(); - s.push_str("\n"); + s.push('\n'); highlight::render_example_with_highlighting( &text, @@ -349,7 +349,7 @@ impl<'a, I: Iterator>> Iterator for LinkReplacer<'a, I> { dest, title, ))) => { - debug!("saw start of shortcut link to {} with title {}", dest, title); + debug!("saw start of shortcut link to {dest} with title {title}"); // If this is a shortcut link, it was resolved by the broken_link_callback. // So the URL will already be updated properly. let link = self.links.iter().find(|&link| *link.href == **dest); @@ -370,7 +370,7 @@ impl<'a, I: Iterator>> Iterator for LinkReplacer<'a, I> { dest, _, ))) => { - debug!("saw end of shortcut link to {}", dest); + debug!("saw end of shortcut link to {dest}"); if self.links.iter().any(|link| *link.href == **dest) { assert!(self.shortcut_link.is_some(), "saw closing link without opening tag"); self.shortcut_link = None; @@ -379,7 +379,7 @@ impl<'a, I: Iterator>> Iterator for LinkReplacer<'a, I> { // Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link. // [`fn@f`] Some(Event::Code(text)) => { - trace!("saw code {}", text); + trace!("saw code {text}"); if let Some(link) = self.shortcut_link { // NOTE: this only replaces if the code block is the *entire* text. // If only part of the link has code highlighting, the disambiguator will not be removed. @@ -394,7 +394,7 @@ impl<'a, I: Iterator>> Iterator for LinkReplacer<'a, I> { l.href == link.href && Some(&**text) == l.original_text.get(1..l.original_text.len() - 1) }) { - debug!("replacing {} with {}", text, link.new_text); + debug!("replacing {text} with {new_text}", new_text = link.new_text); *text = CowStr::Borrowed(&link.new_text); } } @@ -402,7 +402,7 @@ impl<'a, I: Iterator>> Iterator for LinkReplacer<'a, I> { // Replace plain text in links, but only in the middle of a shortcut link. // [fn@f] Some(Event::Text(text)) => { - trace!("saw text {}", text); + trace!("saw text {text}"); if let Some(link) = self.shortcut_link { // NOTE: same limitations as `Event::Code` if let Some(link) = self @@ -410,7 +410,7 @@ impl<'a, I: Iterator>> Iterator for LinkReplacer<'a, I> { .iter() .find(|l| l.href == link.href && **text == *l.original_text) { - debug!("replacing {} with {}", text, link.new_text); + debug!("replacing {text} with {new_text}", new_text = link.new_text); *text = CowStr::Borrowed(&link.new_text); } } @@ -522,12 +522,12 @@ impl<'a, 'b, 'ids, I: Iterator>> Iterator let mut html_header = String::new(); html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone())); let sec = builder.push(level as u32, html_header, id.clone()); - self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0)); + self.buf.push_front((Event::Html(format!("{sec} ").into()), 0..0)); } let level = std::cmp::min(level as u32 + (self.heading_offset as u32), MAX_HEADER_LEVEL); - self.buf.push_back((Event::Html(format!("", level).into()), 0..0)); + self.buf.push_back((Event::Html(format!("").into()), 0..0)); let start_tags = format!( "\ @@ -681,14 +681,14 @@ impl<'a, I: Iterator>> Iterator for Footnotes<'a, I> { v.sort_by(|a, b| a.1.cmp(&b.1)); let mut ret = String::from("

    "); for (mut content, id) in v { - write!(ret, "
  1. ", id).unwrap(); + write!(ret, "
  2. ").unwrap(); let mut is_paragraph = false; if let Some(&Event::End(Tag::Paragraph)) = content.last() { content.pop(); is_paragraph = true; } html::push_html(&mut ret, content.into_iter()); - write!(ret, " ", id).unwrap(); + write!(ret, " ").unwrap(); if is_paragraph { ret.push_str("

    "); } @@ -959,7 +959,7 @@ impl LangString { } { if let Some(extra) = extra { extra.error_invalid_codeblock_attr( - format!("unknown attribute `{}`. Did you mean `{}`?", x, flag), + format!("unknown attribute `{x}`. Did you mean `{flag}`?"), help, ); } @@ -1038,7 +1038,7 @@ impl MarkdownWithToc<'_> { html::push_html(&mut s, p); } - format!("{}", toc.into_toc().print(), s) + format!("{s}", toc = toc.into_toc().print()) } } diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index 991edbddc6f45..d7ff248a9bff5 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -206,15 +206,14 @@ impl<'tcx> Context<'tcx> { format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate) } else { format!( - "API documentation for the Rust `{}` {} in crate `{}`.", - it.name.as_ref().unwrap(), - tyname, - self.shared.layout.krate + "API documentation for the Rust `{name}` {tyname} in crate `{krate}`.", + name = it.name.as_ref().unwrap(), + krate = self.shared.layout.krate, ) }; let name; let tyname_s = if it.is_crate() { - name = format!("{} crate", tyname); + name = format!("{tyname} crate"); name.as_str() } else { tyname.as_str() @@ -264,7 +263,12 @@ impl<'tcx> Context<'tcx> { current_path.push_str(&item_path(ty, names.last().unwrap().as_str())); redirections.borrow_mut().insert(current_path, path); } - None => return layout::redirect(&format!("{}{}", self.root_path(), path)), + None => { + return layout::redirect(&format!( + "{root}{path}", + root = self.root_path() + )); + } } } } @@ -382,11 +386,7 @@ impl<'tcx> Context<'tcx> { let hiline = span.hi(self.sess()).line; format!( "#{}", - if loline == hiline { - loline.to_string() - } else { - format!("{}-{}", loline, hiline) - } + if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") } ) } else { "".to_string() @@ -855,12 +855,12 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { // If the item is a macro, redirect from the old macro URL (with !) // to the new one (without). if item_type == ItemType::Macro { - let redir_name = format!("{}.{}!.html", item_type, name); + let redir_name = format!("{item_type}.{name}!.html"); if let Some(ref redirections) = self.shared.redirections { let crate_name = &self.shared.layout.krate; redirections.borrow_mut().insert( - format!("{}/{}", crate_name, redir_name), - format!("{}/{}", crate_name, file_name), + format!("{crate_name}/{redir_name}"), + format!("{crate_name}/{file_name}"), ); } else { let v = layout::redirect(file_name); diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 8a6e0b1ed51f1..ac9c180a6a867 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -85,7 +85,7 @@ use crate::DOC_RUST_LANG_ORG_CHANNEL; pub(crate) fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ { crate::html::format::display_fn(move |f| { - if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) } + if !v.ends_with('/') && !v.is_empty() { write!(f, "{v}/") } else { f.write_str(v) } }) } @@ -416,7 +416,7 @@ fn document<'a, 'cx: 'a>( heading_offset: HeadingOffset, ) -> impl fmt::Display + 'a + Captures<'cx> { if let Some(ref name) = item.name { - info!("Documenting {}", name); + info!("Documenting {name}"); } display_fn(move |f| { @@ -513,7 +513,7 @@ fn document_full_inner<'a, 'cx: 'a>( ) -> impl fmt::Display + 'a + Captures<'cx> { display_fn(move |f| { if let Some(s) = item.opt_doc_value() { - debug!("Doc block: =====\n{}\n=====", s); + debug!("Doc block: =====\n{s}\n====="); if is_collapsible { write!( f, @@ -565,12 +565,10 @@ fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option( ) -> impl fmt::Display + Captures<'a> + Captures<'b> { crate::html::format::display_fn(move |f| { for a in it.attributes(tcx, false) { - writeln!(f, "{}{}", prefix, a)?; + writeln!(f, "{prefix}{a}")?; } Ok(()) }) @@ -1245,7 +1243,10 @@ fn render_deref_methods( _ => None, }) .expect("Expected associated type binding"); - debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target); + debug!( + "Render deref methods for {for_:#?}, target {target:#?}", + for_ = impl_.inner_impl().for_ + ); let what = AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut }; if let Some(did) = target.def_id(cache) { diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index cfced799f1ec6..6cab349862233 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -310,9 +310,8 @@ fn toggle_open(mut w: impl fmt::Write, text: impl fmt::Display) { w, "
    \ \ - Show {}\ + Show {text}\ ", - text ) .unwrap(); } @@ -412,7 +411,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: ) }); - debug!("{:?}", indices); + debug!("{indices:?}"); let mut last_section = None; for &idx in &indices { @@ -431,8 +430,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: w, "

    \ {name}\ -

    {}", - ITEM_TABLE_OPEN, + {ITEM_TABLE_OPEN}", id = cx.derive_id(my_section.id()), name = my_section.name(), ); @@ -485,7 +483,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: w.write_str(ITEM_TABLE_ROW_OPEN); let id = match import.kind { clean::ImportKind::Simple(s) => { - format!(" id=\"{}\"", cx.derive_id(format!("reexport.{}", s))) + format!(" id=\"{}\"", cx.derive_id(format!("reexport.{s}"))) } clean::ImportKind::Glob => String::new(), }; @@ -583,10 +581,8 @@ fn extra_info_tags<'a, 'tcx: 'a>( display_fn(move |f| { write!( f, - r#"{}"#, - class, - Escape(title), - contents + r#"{contents}"#, + title = Escape(title), ) }) } @@ -614,7 +610,12 @@ fn extra_info_tags<'a, 'tcx: 'a>( (cfg, _) => cfg.as_deref().cloned(), }; - debug!("Portability name={:?} {:?} - {:?} = {:?}", item.name, item.cfg, parent.cfg, cfg); + debug!( + "Portability name={name:?} {cfg:?} - {parent_cfg:?} = {cfg:?}", + name = item.name, + cfg = item.cfg, + parent_cfg = parent.cfg + ); if let Some(ref cfg) = cfg { write!( f, @@ -689,14 +690,13 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean: wrap_item(w, |mut w| { write!( w, - "{attrs}{}{}{}trait {}{}{}", - visibility_print_with_space(it.visibility(tcx), it.item_id, cx), - t.unsafety(tcx).print_with_space(), - if t.is_auto(tcx) { "auto " } else { "" }, - it.name.unwrap(), - t.generics.print(cx), - bounds, + "{attrs}{vis}{unsafety}{is_auto}trait {name}{generics}{bounds}", attrs = render_attributes_in_pre(it, "", tcx), + vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx), + unsafety = t.unsafety(tcx).print_with_space(), + is_auto = if t.is_auto(tcx) { "auto " } else { "" }, + name = it.name.unwrap(), + generics = t.generics.print(cx), ); if !t.generics.where_predicates.is_empty() { @@ -742,11 +742,10 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean: toggle_open( &mut w, format_args!( - "{} associated constant{} and {} method{}", - count_consts, - pluralize(count_consts), - count_methods, - pluralize(count_methods), + "{count_consts} associated constant{plural_const} and \ + {count_methods} method{plural_method}", + plural_const = pluralize(count_consts), + plural_method = pluralize(count_methods), ), ); } @@ -768,7 +767,7 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean: } if !toggle && should_hide_fields(count_methods) { toggle = true; - toggle_open(&mut w, format_args!("{} methods", count_methods)); + toggle_open(&mut w, format_args!("{count_methods} methods")); } if count_consts != 0 && count_methods != 0 { w.write_str("\n"); @@ -837,9 +836,9 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean: fn trait_item(w: &mut Buffer, cx: &mut Context<'_>, m: &clean::Item, t: &clean::Item) { let name = m.name.unwrap(); - info!("Documenting {} on {:?}", name, t.name); + info!("Documenting {name} on {ty_name:?}", ty_name = t.name); let item_type = m.type_(); - let id = cx.derive_id(format!("{}.{}", item_type, name)); + let id = cx.derive_id(format!("{item_type}.{name}")); let mut content = Buffer::empty_from(w); write!(&mut content, "{}", document(cx, m, Some(t), HeadingOffset::H5)); let toggled = !content.is_empty(); @@ -847,7 +846,7 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean: let method_toggle_class = if item_type.is_method() { " method-toggle" } else { "" }; write!(w, "
    "); } - write!(w, "
    ", id); + write!(w, "
    "); render_rightside(w, cx, m, t, RenderMode::Normal); write!(w, "

    "); render_assoc_item( @@ -1170,12 +1169,12 @@ fn item_trait_alias( wrap_item(w, |w| { write!( w, - "{attrs}trait {}{}{} = {};", - it.name.unwrap(), - t.generics.print(cx), - print_where_clause(&t.generics, cx, 0, Ending::Newline), - bounds(&t.bounds, true, cx), + "{attrs}trait {name}{generics}{where_b} = {bounds};", attrs = render_attributes_in_pre(it, "", cx.tcx()), + name = it.name.unwrap(), + generics = t.generics.print(cx), + where_b = print_where_clause(&t.generics, cx, 0, Ending::Newline), + bounds = bounds(&t.bounds, true, cx), ) .unwrap(); }); @@ -1198,12 +1197,12 @@ fn item_opaque_ty( wrap_item(w, |w| { write!( w, - "{attrs}type {}{}{where_clause} = impl {bounds};", - it.name.unwrap(), - t.generics.print(cx), + "{attrs}type {name}{generics}{where_clause} = impl {bounds};", + attrs = render_attributes_in_pre(it, "", cx.tcx()), + name = it.name.unwrap(), + generics = t.generics.print(cx), where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline), bounds = bounds(&t.bounds, false, cx), - attrs = render_attributes_in_pre(it, "", cx.tcx()), ) .unwrap(); }); @@ -1223,13 +1222,13 @@ fn item_typedef(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clea wrap_item(w, |w| { write!( w, - "{attrs}{}type {}{}{where_clause} = {type_};", - visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx), - it.name.unwrap(), - t.generics.print(cx), + "{attrs}{vis}type {name}{generics}{where_clause} = {type_};", + attrs = render_attributes_in_pre(it, "", cx.tcx()), + vis = visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx), + name = it.name.unwrap(), + generics = t.generics.print(cx), where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline), type_ = t.type_.print(cx), - attrs = render_attributes_in_pre(it, "", cx.tcx()), ); }); } @@ -1354,7 +1353,7 @@ fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean:: w.write_str("{\n"); let toggle = should_hide_fields(count_variants); if toggle { - toggle_open(&mut w, format_args!("{} variants", count_variants)); + toggle_open(&mut w, format_args!("{count_variants} variants")); } for v in e.variants() { w.write_str(" "); @@ -1362,7 +1361,7 @@ fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean:: match *v.kind { // FIXME(#101337): Show discriminant clean::VariantItem(ref var) => match var.kind { - clean::VariantKind::CLike => write!(w, "{}", name), + clean::VariantKind::CLike => w.write_str(name.as_str()), clean::VariantKind::Tuple(ref s) => { write!(w, "{name}({})", print_tuple_struct_fields(cx, s),); } @@ -1418,7 +1417,7 @@ fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean:: let clean::VariantItem(variant_data) = &*variant.kind else { unreachable!() }; if let clean::VariantKind::Tuple(ref s) = variant_data.kind { - write!(w, "({})", print_tuple_struct_fields(cx, s),); + write!(w, "({})", print_tuple_struct_fields(cx, s)); } w.write_str("

    "); @@ -1617,7 +1616,7 @@ fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean for (index, (field, ty)) in fields.enumerate() { let field_name = field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string()); - let id = cx.derive_id(format!("{}.{}", ItemType::StructField, field_name)); + let id = cx.derive_id(format!("{typ}.{field_name}", typ = ItemType::StructField)); write!( w, "\ @@ -1722,7 +1721,7 @@ pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String { pub(super) fn item_path(ty: ItemType, name: &str) -> String { match ty { ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)), - _ => format!("{}.{}.html", ty, name), + _ => format!("{ty}.{name}.html"), } } @@ -1845,7 +1844,7 @@ fn render_union<'a, 'cx: 'a>( fields.iter().filter(|field| matches!(*field.kind, clean::StructFieldItem(..))).count(); let toggle = should_hide_fields(count_fields); if toggle { - toggle_open(&mut f, format_args!("{} fields", count_fields)); + toggle_open(&mut f, format_args!("{count_fields} fields")); } for field in fields { @@ -1908,26 +1907,25 @@ fn render_struct( let has_visible_fields = count_fields > 0; let toggle = should_hide_fields(count_fields); if toggle { - toggle_open(&mut w, format_args!("{} fields", count_fields)); + toggle_open(&mut w, format_args!("{count_fields} fields")); } for field in fields { if let clean::StructFieldItem(ref ty) = *field.kind { write!( w, - "\n{} {}{}: {},", - tab, - visibility_print_with_space(field.visibility(tcx), field.item_id, cx), - field.name.unwrap(), - ty.print(cx), + "\n{tab} {vis}{name}: {ty},", + vis = visibility_print_with_space(field.visibility(tcx), field.item_id, cx), + name = field.name.unwrap(), + ty = ty.print(cx), ); } } if has_visible_fields { if it.has_stripped_entries().unwrap() { - write!(w, "\n{} /* private fields */", tab); + write!(w, "\n{tab} /* private fields */"); } - write!(w, "\n{}", tab); + write!(w, "\n{tab}"); } else if it.has_stripped_entries().unwrap() { write!(w, " /* private fields */ "); } diff --git a/src/librustdoc/html/render/sidebar.rs b/src/librustdoc/html/render/sidebar.rs index 455b4e9aefe55..f3da610565c44 100644 --- a/src/librustdoc/html/render/sidebar.rs +++ b/src/librustdoc/html/render/sidebar.rs @@ -330,7 +330,7 @@ fn sidebar_deref_methods<'a>( ) { let c = cx.cache(); - debug!("found Deref: {:?}", impl_); + debug!("found Deref: {impl_:?}"); if let Some((target, real_target)) = impl_.inner_impl().items.iter().find_map(|item| match *item.kind { clean::AssocTypeItem(box ref t, _) => Some(match *t { @@ -340,7 +340,7 @@ fn sidebar_deref_methods<'a>( _ => None, }) { - debug!("found target, real_target: {:?} {:?}", target, real_target); + debug!("found target, real_target: {target:?} {real_target:?}"); if let Some(did) = target.def_id(c) && let Some(type_did) = impl_.inner_impl().for_.def_id(c) && // `impl Deref for S` @@ -357,7 +357,7 @@ fn sidebar_deref_methods<'a>( }) .and_then(|did| c.impls.get(&did)); if let Some(impls) = inner_impl { - debug!("found inner_impl: {:?}", impls); + debug!("found inner_impl: {impls:?}"); let mut ret = impls .iter() .filter(|i| i.inner_impl().trait_.is_none()) @@ -510,10 +510,10 @@ fn get_next_url(used_links: &mut FxHashSet, url: String) -> String { return url; } let mut add = 1; - while !used_links.insert(format!("{}-{}", url, add)) { + while !used_links.insert(format!("{url}-{add}")) { add += 1; } - format!("{}-{}", url, add) + format!("{url}-{add}") } fn get_methods<'a>( @@ -529,7 +529,7 @@ fn get_methods<'a>( Some(ref name) if !name.is_empty() && item.is_method() => { if !for_deref || super::should_render_item(item, deref_mut, tcx) { Some(Link::new( - get_next_url(used_links, format!("{}.{}", ItemType::Method, name)), + get_next_url(used_links, format!("{typ}.{name}", typ = ItemType::Method)), name.as_str(), )) } else { @@ -549,7 +549,7 @@ fn get_associated_constants<'a>( .iter() .filter_map(|item| match item.name { Some(ref name) if !name.is_empty() && item.is_associated_const() => Some(Link::new( - get_next_url(used_links, format!("{}.{}", ItemType::AssocConst, name)), + get_next_url(used_links, format!("{typ}.{name}", typ = ItemType::AssocConst)), name.as_str(), )), _ => None, diff --git a/src/librustdoc/html/render/write_shared.rs b/src/librustdoc/html/render/write_shared.rs index 3f41765a5afba..e824651e727df 100644 --- a/src/librustdoc/html/render/write_shared.rs +++ b/src/librustdoc/html/render/write_shared.rs @@ -73,7 +73,7 @@ pub(super) fn write_shared( } let bytes = try_err!(fs::read(&entry.path), &entry.path); - let filename = format!("{}{}.{}", theme, cx.shared.resource_suffix, extension); + let filename = format!("{theme}{suffix}.{extension}", suffix = cx.shared.resource_suffix); cx.shared.fs.write(cx.dst.join(filename), bytes)?; } @@ -112,7 +112,7 @@ pub(super) fn write_shared( let mut krates = Vec::new(); if path.exists() { - let prefix = format!("\"{}\"", krate); + let prefix = format!("\"{krate}\""); for line in BufReader::new(File::open(path)?).lines() { let line = line?; if !line.starts_with('"') { @@ -157,7 +157,7 @@ pub(super) fn write_shared( let mut krates = Vec::new(); if path.exists() { - let prefix = format!("\"{}\"", krate); + let prefix = format!("\"{krate}\""); for line in BufReader::new(File::open(path)?).lines() { let line = line?; if !line.starts_with('"') { @@ -213,10 +213,10 @@ pub(super) fn write_shared( let dirs = if subs.is_empty() && files.is_empty() { String::new() } else { - format!(",[{}]", subs) + format!(",[{subs}]") }; let files = files.join(","); - let files = if files.is_empty() { String::new() } else { format!(",[{}]", files) }; + let files = if files.is_empty() { String::new() } else { format!(",[{files}]") }; format!( "[\"{name}\"{dirs}{files}]", name = self.elem.to_str().expect("invalid osstring conversion"), @@ -319,8 +319,8 @@ if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex}; })?; write_invocation_specific("crates.js", &|| { - let krates = krates.iter().map(|k| format!("\"{}\"", k)).join(","); - Ok(format!("window.ALL_CRATES = [{}];", krates).into_bytes()) + let krates = krates.iter().map(|k| format!("\"{k}\"")).join(","); + Ok(format!("window.ALL_CRATES = [{krates}];").into_bytes()) })?; if options.enable_index_page { @@ -349,9 +349,8 @@ if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex}; .iter() .map(|s| { format!( - "
  3. {}
  4. ", - ensure_trailing_slash(s), - s + "
  5. {s}
  6. ", + trailing_slash = ensure_trailing_slash(s), ) }) .collect::() @@ -444,7 +443,7 @@ if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex}; mydst.push(part.to_string()); } cx.shared.ensure_dir(&mydst)?; - mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1])); + mydst.push(&format!("{remote_item_type}.{}.js", remote_path[remote_path.len() - 1])); let (mut all_implementors, _) = try_err!(collect(&mydst, krate.name(cx.tcx()).as_str()), &mydst); diff --git a/src/librustdoc/html/sources.rs b/src/librustdoc/html/sources.rs index 3e3fc8a0e720a..c4a1ebbec02ea 100644 --- a/src/librustdoc/html/sources.rs +++ b/src/librustdoc/html/sources.rs @@ -146,9 +146,8 @@ impl DocVisitor for SourceCollector<'_, '_> { self.cx.shared.tcx.sess.span_err( span, format!( - "failed to render source code for `{}`: {}", - filename.prefer_local(), - e, + "failed to render source code for `{filename}`: {e}", + filename = filename.prefer_local(), ), ); false diff --git a/src/librustdoc/html/static_files.rs b/src/librustdoc/html/static_files.rs index 5d2e4b073c1fe..a27aa2b58d245 100644 --- a/src/librustdoc/html/static_files.rs +++ b/src/librustdoc/html/static_files.rs @@ -53,7 +53,7 @@ pub(crate) fn suffix_path(filename: &str, suffix: &str) -> PathBuf { // which would result in `style.min-suffix.css` which isn't what we // want. let (base, ext) = filename.split_once('.').unwrap(); - let filename = format!("{}{}.{}", base, suffix, ext); + let filename = format!("{base}{suffix}.{ext}"); filename.into() } diff --git a/src/librustdoc/json/mod.rs b/src/librustdoc/json/mod.rs index 9392dd4d08825..cd791ce000bff 100644 --- a/src/librustdoc/json/mod.rs +++ b/src/librustdoc/json/mod.rs @@ -139,7 +139,7 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> { fn item(&mut self, item: clean::Item) -> Result<(), Error> { let item_type = item.type_(); let item_name = item.name; - trace!("rendering {} {:?}", item_type, item_name); + trace!("rendering {item_type} {item_name:?}"); // Flatten items that recursively store other items. We include orphaned items from // stripped modules and etc that are otherwise reachable. @@ -203,11 +203,11 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> { if !can_be_ignored { assert_eq!(old_item, new_item); } - trace!("replaced {:?}\nwith {:?}", old_item, new_item); + trace!("replaced {old_item:?}\nwith {new_item:?}"); } } - trace!("done rendering {} {:?}", item_type, item_name); + trace!("done rendering {item_type} {item_name:?}"); Ok(()) } diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 36d087a7d5be6..8220df5d4f373 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -192,8 +192,7 @@ fn init_logging(handler: &EarlyErrorHandler) { Ok("never") => false, Ok("auto") | Err(VarError::NotPresent) => io::stdout().is_terminal(), Ok(value) => handler.early_error(format!( - "invalid log color value '{}': expected one of always, never, or auto", - value + "invalid log color value '{value}': expected one of always, never, or auto", )), Err(VarError::NotUnicode(value)) => handler.early_error(format!( "invalid log color value '{}': expected one of always, never, or auto", @@ -224,7 +223,7 @@ fn get_args(handler: &EarlyErrorHandler) -> Option> { .map(|(i, arg)| { arg.into_string() .map_err(|arg| { - handler.early_warn(format!("Argument {} is not valid Unicode: {:?}", i, arg)); + handler.early_warn(format!("Argument {i} is not valid Unicode: {arg:?}")); }) .ok() }) @@ -665,11 +664,10 @@ fn usage(argv0: &str) { for option in opts() { (option.apply)(&mut options); } - println!("{}", options.usage(&format!("{} [options] ", argv0))); + println!("{}", options.usage(&format!("{argv0} [options] "))); println!(" @path Read newline separated options from `path`\n"); println!( - "More information available at {}/rustdoc/what-is-rustdoc.html", - DOC_RUST_LANG_ORG_CHANNEL + "More information available at {DOC_RUST_LANG_ORG_CHANNEL}/rustdoc/what-is-rustdoc.html", ); } @@ -699,7 +697,7 @@ fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>( tcx.sess.struct_err(format!("couldn't generate documentation: {}", e.error)); let file = e.file.display().to_string(); if !file.is_empty() { - msg.note(format!("failed to create or modify \"{}\"", file)); + msg.note(format!("failed to create or modify \"{file}\"")); } Err(msg.emit()) } diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index 4321d4aa343dc..526eea30478ab 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -43,7 +43,7 @@ pub(crate) fn render>( edition: Edition, ) -> Result<(), String> { if let Err(e) = create_dir_all(&options.output) { - return Err(format!("{}: {}", options.output.display(), e)); + return Err(format!("{output}: {e}", output = options.output.display())); } let input = input.as_ref(); @@ -57,11 +57,13 @@ pub(crate) fn render>( .expect("Writing to a String can't fail"); } - let input_str = read_to_string(input).map_err(|err| format!("{}: {}", input.display(), err))?; + let input_str = + read_to_string(input).map_err(|err| format!("{input}: {err}", input = input.display()))?; let playground_url = options.markdown_playground_url.or(options.playground_url); let playground = playground_url.map(|url| markdown::Playground { crate_name: None, url }); - let mut out = File::create(&output).map_err(|e| format!("{}: {}", output.display(), e))?; + let mut out = + File::create(&output).map_err(|e| format!("{output}: {e}", output = output.display()))?; let (metadata, text) = extract_leading_metadata(&input_str); if metadata.is_empty() { @@ -129,7 +131,7 @@ pub(crate) fn render>( ); match err { - Err(e) => Err(format!("cannot write to `{}`: {}", output.display(), e)), + Err(e) => Err(format!("cannot write to `{output}`: {e}", output = output.display())), Ok(_) => Ok(()), } } @@ -137,7 +139,7 @@ pub(crate) fn render>( /// Runs any tests/code examples in the markdown file `input`. pub(crate) fn test(options: Options) -> Result<(), String> { let input_str = read_to_string(&options.input) - .map_err(|err| format!("{}: {}", options.input.display(), err))?; + .map_err(|err| format!("{input}: {err}", input = options.input.display()))?; let mut opts = GlobalTestOptions::default(); opts.no_crate_inject = true; let mut collector = Collector::new( diff --git a/src/librustdoc/passes/calculate_doc_coverage.rs b/src/librustdoc/passes/calculate_doc_coverage.rs index 6ead0cd961a31..592dd0a145cf5 100644 --- a/src/librustdoc/passes/calculate_doc_coverage.rs +++ b/src/librustdoc/passes/calculate_doc_coverage.rs @@ -146,8 +146,10 @@ impl<'a, 'b> CoverageCalculator<'a, 'b> { examples_percentage: f64, ) { println!( - "| {:<35} | {:>10} | {:>9.1}% | {:>10} | {:>9.1}% |", - name, count.with_docs, percentage, count.with_examples, examples_percentage, + "| {name:<35} | {with_docs:>10} | {percentage:>9.1}% | {with_examples:>10} | \ + {examples_percentage:>9.1}% |", + with_docs = count.with_docs, + with_examples = count.with_examples, ); } @@ -249,7 +251,7 @@ impl<'a, 'b> DocVisitor for CoverageCalculator<'a, 'b> { if let Some(span) = i.span(self.ctx.tcx) { let filename = span.filename(self.ctx.sess()); - debug!("counting {:?} {:?} in {:?}", i.type_(), i.name, filename); + debug!("counting {:?} {:?} in {filename:?}", i.type_(), i.name); self.items.entry(filename).or_default().count_item( has_docs, has_doc_example, diff --git a/src/librustdoc/passes/check_doc_test_visibility.rs b/src/librustdoc/passes/check_doc_test_visibility.rs index e333a35e8ad29..e732a40576067 100644 --- a/src/librustdoc/passes/check_doc_test_visibility.rs +++ b/src/librustdoc/passes/check_doc_test_visibility.rs @@ -117,7 +117,7 @@ pub(crate) fn look_for_tests<'tcx>(cx: &DocContext<'tcx>, dox: &str, item: &Item if tests.found_tests == 0 && cx.tcx.features().rustdoc_missing_doc_code_examples { if should_have_doc_example(cx, item) { - debug!("reporting error for {:?} (hir_id={:?})", item, hir_id); + debug!("reporting error for {item:?} (hir_id={hir_id:?})"); let sp = item.attr_span(cx.tcx); cx.tcx.struct_span_lint_hir( crate::lint::MISSING_DOC_CODE_EXAMPLES, diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 1b8d999024c47..26ff64f06a321 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -150,7 +150,7 @@ impl TryFrom for Res { PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))), // e.g. `#[derive]` ToolMod | NonMacroAttr(..) | Err => Result::Err(()), - other => bug!("unrecognized res {:?}", other), + other => bug!("unrecognized res {other:?}"), } } } @@ -224,7 +224,7 @@ impl UrlFragment { "structfield." } } - kind => bug!("unexpected associated item kind: {:?}", kind), + kind => bug!("unexpected associated item kind: {kind:?}"), }; s.push_str(kind); s.push_str(tcx.item_name(def_id).as_str()); @@ -279,7 +279,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { unresolved: path_str.into(), }; - debug!("looking for enum variant {}", path_str); + debug!("looking for enum variant {path_str}"); let mut split = path_str.rsplitn(3, "::"); let variant_field_name = split .next() @@ -410,7 +410,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { }) .and_then(|res| res.try_into().ok()) .or_else(|| resolve_primitive(path_str, ns)); - debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns); + debug!("{path_str} resolved to {result:?} in namespace {ns:?}"); result } @@ -453,7 +453,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { // If there's no `::`, it's not an associated item. // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved. .ok_or_else(|| { - debug!("found no `::`, assuming {} was correctly not in scope", item_name); + debug!("found no `::`, assuming {item_name} was correctly not in scope"); UnresolvedPath { item_id, module_id, @@ -603,7 +603,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { def_kind @ (DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy), did, ) => { - debug!("looking for associated item named {} for item {:?}", item_name, did); + debug!("looking for associated item named {item_name} for item {did:?}"); // Checks if item_name is a variant of the `SomeItem` enum if ns == TypeNS && def_kind == DefKind::Enum { match tcx.type_of(did).instantiate_identity().kind() { @@ -651,7 +651,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { .collect::>(); } - debug!("got associated item {:?}", assoc_items); + debug!("got associated item {assoc_items:?}"); if !assoc_items.is_empty() { return assoc_items; @@ -660,7 +660,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { if ns != Namespace::ValueNS { return Vec::new(); } - debug!("looking for fields named {} for {:?}", item_name, did); + debug!("looking for fields named {item_name} for {did:?}"); // FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?) // NOTE: it's different from variant_field because it only resolves struct fields, // not variant fields (2 path segments, not 3). @@ -727,7 +727,7 @@ fn resolve_associated_trait_item<'a>( // Give precedence to inherent impls. let traits = trait_impls_for(cx, ty, module); let tcx = cx.tcx; - debug!("considering traits {:?}", traits); + debug!("considering traits {traits:?}"); let candidates = traits .iter() .flat_map(|&(impl_, trait_)| { @@ -744,7 +744,7 @@ fn resolve_associated_trait_item<'a>( }) .collect::>(); // FIXME(#74563): warn about ambiguity - debug!("the candidates were {:?}", candidates); + debug!("the candidates were {candidates:?}"); candidates } @@ -790,10 +790,8 @@ fn trait_impls_for<'a>( // Check if these are the same type. let impl_type = trait_ref.skip_binder().self_ty(); trace!( - "comparing type {} with kind {:?} against type {:?}", - impl_type, - impl_type.kind(), - ty + "comparing type {impl_type} with kind {kind:?} against type {ty:?}", + kind = impl_type.kind(), ); // Fast path: if this is a primitive simple `==` will work // NOTE: the `match` is necessary; see #92662. @@ -940,7 +938,7 @@ fn preprocess_link( let path_str = match strip_generics_from_path(path_str) { Ok(path) => path, Err(err) => { - debug!("link has malformed generics: {}", path_str); + debug!("link has malformed generics: {path_str}"); return Some(Err(PreprocessingError::MalformedGenerics(err, path_str.to_owned()))); } }; @@ -987,7 +985,7 @@ impl LinkCollector<'_, '_> { if !may_have_doc_links(&doc) { continue; } - debug!("combined_docs={}", doc); + debug!("combined_docs={doc}"); // NOTE: if there are links that start in one crate and end in another, this will not resolve them. // This is a degenerate case and it's not supported by rustdoc. let item_id = item_id.unwrap_or_else(|| item.item_id.expect_def_id()); @@ -1130,10 +1128,10 @@ impl LinkCollector<'_, '_> { item: &Item, diag_info: &DiagnosticInfo<'_>, ) -> Option<()> { - debug!("intra-doc link to {} resolved to {:?}", path_str, (kind, id)); + debug!("intra-doc link to {path_str} resolved to {:?}", (kind, id)); // Disallow e.g. linking to enums with `struct@` - debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator); + debug!("saw kind {kind:?} with disambiguator {disambiguator:?}"); match (kind, disambiguator) { | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const))) // NOTE: this allows 'method' to mean both normal functions and associated functions @@ -1174,7 +1172,7 @@ impl LinkCollector<'_, '_> { diag_info: &DiagnosticInfo<'_>, ) { // The resolved item did not match the disambiguator; give a better error than 'not found' - let msg = format!("incompatible link kind for `{}`", path_str); + let msg = format!("incompatible link kind for `{path_str}`"); let callback = |diag: &mut Diagnostic, sp: Option, link_range| { let note = format!( "this link resolved to {} {}, which is not {} {}", @@ -1459,7 +1457,7 @@ impl Disambiguator { "value" => NS(Namespace::ValueNS), "macro" => NS(Namespace::MacroNS), "prim" | "primitive" => Primitive, - _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)), + _ => return Err((format!("unknown disambiguator `{prefix}`"), 0..idx)), }; Ok(Some((d, &rest[1..], &rest[1..]))) } else { @@ -1527,7 +1525,7 @@ enum Suggestion { impl Suggestion { fn descr(&self) -> Cow<'static, str> { match self { - Self::Prefix(x) => format!("prefix with `{}@`", x).into(), + Self::Prefix(x) => format!("prefix with `{x}@`").into(), Self::Function => "add parentheses".into(), Self::Macro => "add an exclamation mark".into(), Self::RemoveDisambiguator => "remove the disambiguator".into(), @@ -1537,9 +1535,9 @@ impl Suggestion { fn as_help(&self, path_str: &str) -> String { // FIXME: if this is an implied shortcut link, it's bad style to suggest `@` match self { - Self::Prefix(prefix) => format!("{}@{}", prefix, path_str), - Self::Function => format!("{}()", path_str), - Self::Macro => format!("{}!", path_str), + Self::Prefix(prefix) => format!("{prefix}@{path_str}"), + Self::Function => format!("{path_str}()"), + Self::Macro => format!("{path_str}!"), Self::RemoveDisambiguator => path_str.into(), } } @@ -1574,7 +1572,7 @@ impl Suggestion { match self { Self::Prefix(prefix) => { // FIXME: if this is an implied shortcut link, it's bad style to suggest `@` - let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{}@", prefix))]; + let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{prefix}@"))]; if sp.hi() != inner_sp.hi() { sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new())); } @@ -1618,7 +1616,7 @@ fn report_diagnostic( ) { let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else { // If non-local, no need to check anything. - info!("ignoring warning from parent crate: {}", msg); + info!("ignoring warning from parent crate: {msg}"); return; }; @@ -1696,15 +1694,14 @@ fn resolution_failure( report_diagnostic( tcx, BROKEN_INTRA_DOC_LINKS, - format!("unresolved link to `{}`", path_str), + format!("unresolved link to `{path_str}`"), &diag_info, |diag, sp, link_range| { - let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),); + let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx)); let assoc_item_not_allowed = |res: Res| { let name = res.name(tcx); format!( - "`{}` is {} {}, not a module or type, and cannot have associated items", - name, + "`{name}` is {} {}, not a module or type, and cannot have associated items", res.article(), res.descr() ) @@ -1750,7 +1747,7 @@ fn resolution_failure( name = start; for ns in [TypeNS, ValueNS, MacroNS] { if let Ok(v_res) = collector.resolve(start, ns, item_id, module_id) { - debug!("found partial_res={:?}", v_res); + debug!("found partial_res={v_res:?}"); if !v_res.is_empty() { *partial_res = Some(full_res(tcx, v_res[0])); *unresolved = end.into(); @@ -1771,10 +1768,10 @@ fn resolution_failure( let note = if partial_res.is_some() { // Part of the link resolved; e.g. `std::io::nonexistent` let module_name = tcx.item_name(module); - format!("no item named `{}` in module `{}`", unresolved, module_name) + format!("no item named `{unresolved}` in module `{module_name}`") } else { // None of the link resolved; e.g. `Notimported` - format!("no item named `{}` in scope", unresolved) + format!("no item named `{unresolved}` in scope") }; if let Some(span) = sp { diag.span_label(span, note); @@ -1879,11 +1876,9 @@ fn resolution_failure( }; let name = res.name(tcx); let note = format!( - "the {} `{}` has no {} named `{}`", - res.descr(), - name, - disambiguator.map_or(path_description, |d| d.descr()), - unresolved, + "the {res} `{name}` has no {disamb_res} named `{unresolved}`", + res = res.descr(), + disamb_res = disambiguator.map_or(path_description, |d| d.descr()), ); if let Some(span) = sp { diag.span_label(span, note); @@ -1978,7 +1973,7 @@ fn report_malformed_generics( report_diagnostic( cx.tcx, BROKEN_INTRA_DOC_LINKS, - format!("unresolved link to `{}`", path_str), + format!("unresolved link to `{path_str}`"), &diag_info, |diag, sp, _link_range| { let note = match err { @@ -2030,7 +2025,7 @@ fn ambiguity_error( return false; } - let mut msg = format!("`{}` is ", path_str); + let mut msg = format!("`{path_str}` is "); match kinds.as_slice() { [res1, res2] => { msg += &format!( @@ -2094,7 +2089,7 @@ fn suggest_disambiguator( diag.span_suggestion_verbose(sp, help, suggestion_text, Applicability::MaybeIncorrect); } } else { - diag.help(format!("{}: {}", help, suggestion.as_help(path_str))); + diag.help(format!("{help}: {}", suggestion.as_help(path_str))); } } @@ -2108,8 +2103,7 @@ fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: } None => "", }; - let msg = - format!("public documentation for `{}` links to private item `{}`", item_name, path_str); + let msg = format!("public documentation for `{item_name}` links to private item `{path_str}`"); report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, _link_range| { if let Some(sp) = sp { @@ -2160,6 +2154,6 @@ fn resolve_primitive(path_str: &str, ns: Namespace) -> Option { "never" | "!" => Never, _ => return None, }; - debug!("resolved primitives {:?}", prim); + debug!("resolved primitives {prim:?}"); Some(Res::Primitive(prim)) } diff --git a/src/librustdoc/passes/lint/bare_urls.rs b/src/librustdoc/passes/lint/bare_urls.rs index 5658b31d9bb9c..97078a5cb1618 100644 --- a/src/librustdoc/passes/lint/bare_urls.rs +++ b/src/librustdoc/passes/lint/bare_urls.rs @@ -28,7 +28,7 @@ pub(super) fn visit_item(cx: &DocContext<'_>, item: &Item) { .span_suggestion( sp, "use an automatic link instead", - format!("<{}>", url), + format!("<{url}>"), Applicability::MachineApplicable, ) }); @@ -74,7 +74,7 @@ fn find_raw_urls( range: Range, f: &impl Fn(&DocContext<'_>, &'static str, &str, Range), ) { - trace!("looking for raw urls in {}", text); + trace!("looking for raw urls in {text}"); // For now, we only check "full" URLs (meaning, starting with "http://" or "https://"). for match_ in URL_REGEX.find_iter(text) { let url = match_.as_str(); diff --git a/src/librustdoc/passes/lint/check_code_block_syntax.rs b/src/librustdoc/passes/lint/check_code_block_syntax.rs index 8e5ee382c86d5..37e28e1fbcab9 100644 --- a/src/librustdoc/passes/lint/check_code_block_syntax.rs +++ b/src/librustdoc/passes/lint/check_code_block_syntax.rs @@ -107,7 +107,7 @@ fn check_rust_syntax( // just give a `help` instead. lint.span_help( sp.from_inner(InnerSpan::new(0, 3)), - format!("{}: ```text", explanation), + format!("{explanation}: ```text"), ); } else if empty_block { lint.span_suggestion( @@ -118,7 +118,7 @@ fn check_rust_syntax( ); } } else if empty_block || is_ignore { - lint.help(format!("{}: ```text", explanation)); + lint.help(format!("{explanation}: ```text")); } // FIXME(#67563): Provide more context for these errors by displaying the spans inline. @@ -160,7 +160,7 @@ impl Emitter for BufferEmitter { .translate_message(&diag.message[0].0, &fluent_args) .unwrap_or_else(|e| panic!("{e}")); - buffer.messages.push(format!("error from rustc: {}", translated_main_message)); + buffer.messages.push(format!("error from rustc: {translated_main_message}")); if diag.is_error() { buffer.has_errors = true; } diff --git a/src/librustdoc/passes/lint/html_tags.rs b/src/librustdoc/passes/lint/html_tags.rs index 24f452b216c25..c135c584cec44 100644 --- a/src/librustdoc/passes/lint/html_tags.rs +++ b/src/librustdoc/passes/lint/html_tags.rs @@ -155,7 +155,7 @@ pub(crate) fn visit_item(cx: &DocContext<'_>, item: &Item) { let t = t.to_lowercase(); !ALLOWED_UNCLOSED.contains(&t.as_str()) }) { - report_diag(format!("unclosed HTML tag `{}`", tag), range, true); + report_diag(format!("unclosed HTML tag `{tag}`"), range, true); } if let Some(range) = is_in_comment { @@ -194,14 +194,14 @@ fn drop_tag( // `tags` is used as a queue, meaning that everything after `pos` is included inside it. // So `

    ` will look like `["h2", "h3"]`. So when closing `h2`, we will still // have `h3`, meaning the tag wasn't closed as it should have. - f(format!("unclosed HTML tag `{}`", last_tag_name), &last_tag_span, true); + f(format!("unclosed HTML tag `{last_tag_name}`"), &last_tag_span, true); } // Remove the `tag_name` that was originally closed tags.pop(); } else { // It can happen for example in this case: `

    ` (the `h2` tag isn't required // but it helps for the visualization). - f(format!("unopened HTML tag `{}`", tag_name), &range, false); + f(format!("unopened HTML tag `{tag_name}`"), &range, false); } } @@ -355,7 +355,7 @@ fn extract_html_tag( if let Some(quote_pos) = quote_pos { let qr = Range { start: quote_pos, end: quote_pos }; f( - format!("unclosed quoted HTML attribute on tag `{}`", tag_name), + format!("unclosed quoted HTML attribute on tag `{tag_name}`"), &qr, false, ); @@ -368,7 +368,7 @@ fn extract_html_tag( at == "svg" || at == "math" }); if !valid { - f(format!("invalid self-closing HTML tag `{}`", tag_name), &r, false); + f(format!("invalid self-closing HTML tag `{tag_name}`"), &r, false); } } else { tags.push((tag_name, r)); diff --git a/src/librustdoc/scrape_examples.rs b/src/librustdoc/scrape_examples.rs index 647d835884015..534c6eebbdd57 100644 --- a/src/librustdoc/scrape_examples.rs +++ b/src/librustdoc/scrape_examples.rs @@ -255,7 +255,7 @@ where let fn_key = tcx.def_path_hash(*def_id); let fn_entries = self.calls.entry(fn_key).or_default(); - trace!("Including expr: {:?}", call_span); + trace!("Including expr: {call_span:?}"); let enclosing_item_span = source_map.span_extend_to_prev_char(enclosing_item_span, '\n', false); let location = @@ -345,7 +345,7 @@ pub(crate) fn load_call_locations( let inner = || { let mut all_calls: AllCallLocations = FxHashMap::default(); for path in with_examples { - let bytes = fs::read(&path).map_err(|e| format!("{} (for path {})", e, path))?; + let bytes = fs::read(&path).map_err(|e| format!("{e} (for path {path})"))?; let mut decoder = MemDecoder::new(&bytes, 0); let calls = AllCallLocations::decode(&mut decoder); @@ -358,7 +358,7 @@ pub(crate) fn load_call_locations( }; inner().map_err(|e: String| { - diag.err(format!("failed to load examples: {}", e)); + diag.err(format!("failed to load examples: {e}")); 1 }) } diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 3bad9ba4e4a72..549fd67e32ad1 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -180,7 +180,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { /// 1. The items which are not glob imports/reexports. /// 2. The glob imports/reexports. fn visit_mod_contents(&mut self, def_id: LocalDefId, m: &'tcx hir::Mod<'tcx>) { - debug!("Going through module {:?}", m); + debug!("Going through module {m:?}"); // Keep track of if there were any private modules in the path. let orig_inside_public_path = self.inside_public_path; self.inside_public_path &= self.cx.tcx.local_visibility(def_id).is_public(); @@ -203,7 +203,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { } } self.inside_public_path = orig_inside_public_path; - debug!("Leaving module {:?}", m); + debug!("Leaving module {m:?}"); } /// Tries to resolve the target of a `pub use` statement and inlines the @@ -394,7 +394,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { renamed: Option, import_id: Option, ) { - debug!("visiting item {:?}", item); + debug!("visiting item {item:?}"); if self.inside_body { // Only impls can be "seen" outside a body. For example: // diff --git a/tests/rustdoc-gui/unsafe-fn.goml b/tests/rustdoc-gui/unsafe-fn.goml index 51007b653d97d..8d26f15f37f1b 100644 --- a/tests/rustdoc-gui/unsafe-fn.goml +++ b/tests/rustdoc-gui/unsafe-fn.goml @@ -23,6 +23,6 @@ define-function: ( }, ) -call-function: ("sup-check", ("dark", "rgb(221, 221, 221)")) -call-function: ("sup-check", ("ayu", "rgb(197, 197, 197)")) -call-function: ("sup-check", ("light", "rgb(0, 0, 0)")) +call-function: ("sup-check", ("ayu", "#c5c5c5")) +call-function: ("sup-check", ("dark", "#ddd")) +call-function: ("sup-check", ("light", "black")) diff --git a/tests/ui/higher-ranked/subtype/placeholder-pattern-fail.stderr b/tests/ui/higher-ranked/subtype/placeholder-pattern-fail.stderr index 73b0a31736447..5241b475d5ca1 100644 --- a/tests/ui/higher-ranked/subtype/placeholder-pattern-fail.stderr +++ b/tests/ui/higher-ranked/subtype/placeholder-pattern-fail.stderr @@ -2,7 +2,9 @@ error[E0308]: mismatched types --> $DIR/placeholder-pattern-fail.rs:9:47 | LL | let _: for<'a, 'b> fn(Inv<'a>, Inv<'b>) = sub; - | ^^^ one type is more general than the other + | -------------------------------- ^^^ one type is more general than the other + | | + | expected due to this | = note: expected fn pointer `for<'a, 'b> fn(Inv<'a>, Inv<'b>)` found fn pointer `for<'a> fn(Inv<'a>, Inv<'a>)` diff --git a/tests/ui/higher-ranked/trait-bounds/hrtb-exists-forall-fn.stderr b/tests/ui/higher-ranked/trait-bounds/hrtb-exists-forall-fn.stderr index 9914783d9767d..db5fc4bf1baea 100644 --- a/tests/ui/higher-ranked/trait-bounds/hrtb-exists-forall-fn.stderr +++ b/tests/ui/higher-ranked/trait-bounds/hrtb-exists-forall-fn.stderr @@ -2,7 +2,9 @@ error[E0308]: mismatched types --> $DIR/hrtb-exists-forall-fn.rs:17:34 | LL | let _: for<'b> fn(&'b u32) = foo(); - | ^^^^^ one type is more general than the other + | ------------------- ^^^^^ one type is more general than the other + | | + | expected due to this | = note: expected fn pointer `for<'b> fn(&'b u32)` found fn pointer `fn(&u32)` diff --git a/tests/ui/regions/higher-ranked-implied.stderr b/tests/ui/regions/higher-ranked-implied.stderr index 9d80eacd7c320..8fa65f1166776 100644 --- a/tests/ui/regions/higher-ranked-implied.stderr +++ b/tests/ui/regions/higher-ranked-implied.stderr @@ -2,7 +2,9 @@ error[E0308]: mismatched types --> $DIR/higher-ranked-implied.rs:12:16 | LL | let y: B = x; - | ^ one type is more general than the other + | - ^ one type is more general than the other + | | + | expected due to this | = note: expected fn pointer `for<'a, 'b> fn(Inv<&'a &'b ()>, Inv<&'b &'a ()>, Inv<&'b ()>)` found fn pointer `for<'a, 'b> fn(Inv<&'a &'b ()>, Inv<&'b &'a ()>, Inv<&'a ()>)` @@ -11,7 +13,9 @@ error[E0308]: mismatched types --> $DIR/higher-ranked-implied.rs:13:16 | LL | let _: A = y; - | ^ one type is more general than the other + | - ^ one type is more general than the other + | | + | expected due to this | = note: expected fn pointer `for<'a, 'b> fn(Inv<&'a &'b ()>, Inv<&'b &'a ()>, Inv<&'a ()>)` found fn pointer `for<'a, 'b> fn(Inv<&'a &'b ()>, Inv<&'b &'a ()>, Inv<&'b ()>)` diff --git a/tests/ui/regions/region-lifetime-bounds-on-fns-where-clause.stderr b/tests/ui/regions/region-lifetime-bounds-on-fns-where-clause.stderr index bb5bc6f66a5f2..f2328cf3b24c6 100644 --- a/tests/ui/regions/region-lifetime-bounds-on-fns-where-clause.stderr +++ b/tests/ui/regions/region-lifetime-bounds-on-fns-where-clause.stderr @@ -2,7 +2,9 @@ error[E0308]: mismatched types --> $DIR/region-lifetime-bounds-on-fns-where-clause.rs:20:43 | LL | let _: fn(&mut &isize, &mut &isize) = a; - | ^ one type is more general than the other + | ---------------------------- ^ one type is more general than the other + | | + | expected due to this | = note: expected fn pointer `for<'a, 'b, 'c, 'd> fn(&'a mut &'b isize, &'c mut &'d isize)` found fn item `for<'a, 'b> fn(&'a mut &isize, &'b mut &isize) {a::<'_, '_>}` diff --git a/tests/ui/regions/region-multiple-lifetime-bounds-on-fns-where-clause.stderr b/tests/ui/regions/region-multiple-lifetime-bounds-on-fns-where-clause.stderr index dbe9e9b1a2e56..9c5004981d59b 100644 --- a/tests/ui/regions/region-multiple-lifetime-bounds-on-fns-where-clause.stderr +++ b/tests/ui/regions/region-multiple-lifetime-bounds-on-fns-where-clause.stderr @@ -2,7 +2,9 @@ error[E0308]: mismatched types --> $DIR/region-multiple-lifetime-bounds-on-fns-where-clause.rs:22:56 | LL | let _: fn(&mut &isize, &mut &isize, &mut &isize) = a; - | ^ one type is more general than the other + | ----------------------------------------- ^ one type is more general than the other + | | + | expected due to this | = note: expected fn pointer `for<'a, 'b, 'c, 'd, 'e, 'f> fn(&'a mut &'b isize, &'c mut &'d isize, &'e mut &'f isize)` found fn item `for<'a, 'b, 'c> fn(&'a mut &isize, &'b mut &isize, &'c mut &isize) {a::<'_, '_, '_>}` diff --git a/tests/ui/regions/regions-lifetime-bounds-on-fns.stderr b/tests/ui/regions/regions-lifetime-bounds-on-fns.stderr index df0fd069edcad..2fab2986567b7 100644 --- a/tests/ui/regions/regions-lifetime-bounds-on-fns.stderr +++ b/tests/ui/regions/regions-lifetime-bounds-on-fns.stderr @@ -2,7 +2,9 @@ error[E0308]: mismatched types --> $DIR/regions-lifetime-bounds-on-fns.rs:20:43 | LL | let _: fn(&mut &isize, &mut &isize) = a; - | ^ one type is more general than the other + | ---------------------------- ^ one type is more general than the other + | | + | expected due to this | = note: expected fn pointer `for<'a, 'b, 'c, 'd> fn(&'a mut &'b isize, &'c mut &'d isize)` found fn item `for<'a, 'b> fn(&'a mut &isize, &'b mut &isize) {a::<'_, '_>}`