From 976aea34eebd7f3453bfbe3380517f5831829684 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Wed, 28 Jun 2023 06:12:19 +0200 Subject: [PATCH 1/8] we are migrating to askama --- src/librustdoc/html/templates/STYLE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustdoc/html/templates/STYLE.md b/src/librustdoc/html/templates/STYLE.md index 0281b1c47f8ce..c573d9752adb2 100644 --- a/src/librustdoc/html/templates/STYLE.md +++ b/src/librustdoc/html/templates/STYLE.md @@ -32,7 +32,7 @@ Askama templates support quite sophisticated control flow. To keep our templates simple and understandable, we use only a subset: `if` and `for`. In particular we avoid [assignments in the template logic][assignments] and [Askama macros][macros]. This also may make things easier if we switch to a different -Jinja-style template system, like Askama, in the future. +Jinja-style template system in future. [assignments]: https://djc.github.io/askama/template_syntax.html#assignments [macros]: https://djc.github.io/askama/template_syntax.html#macros From 545cd1bd5bcb62fb70e0e8e12076478cb41bdc8b Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Wed, 28 Jun 2023 18:34:35 +0200 Subject: [PATCH 2/8] accept review suggestion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Dániel Buga --- src/librustdoc/html/templates/STYLE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustdoc/html/templates/STYLE.md b/src/librustdoc/html/templates/STYLE.md index c573d9752adb2..38aac2a60e94d 100644 --- a/src/librustdoc/html/templates/STYLE.md +++ b/src/librustdoc/html/templates/STYLE.md @@ -32,7 +32,7 @@ Askama templates support quite sophisticated control flow. To keep our templates simple and understandable, we use only a subset: `if` and `for`. In particular we avoid [assignments in the template logic][assignments] and [Askama macros][macros]. This also may make things easier if we switch to a different -Jinja-style template system in future. +Jinja-style template system in the future. [assignments]: https://djc.github.io/askama/template_syntax.html#assignments [macros]: https://djc.github.io/askama/template_syntax.html#macros From 6933848fbff3da5bfcd78ab836cda15e3f649ffc Mon Sep 17 00:00:00 2001 From: Urgau Date: Mon, 14 Aug 2023 11:47:42 +0200 Subject: [PATCH 3/8] Add diagnostic items for `<*const _>::cast` and `<*mut _>::cast_const` --- compiler/rustc_span/src/symbol.rs | 2 ++ library/core/src/ptr/const_ptr.rs | 1 + library/core/src/ptr/mut_ptr.rs | 1 + 3 files changed, 4 insertions(+) diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 745a3590720a0..f66b1e8970bcf 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -543,6 +543,7 @@ symbols! { const_panic_fmt, const_param_ty, const_precise_live_drops, + const_ptr_cast, const_raw_ptr_deref, const_raw_ptr_to_usize_cast, const_refs_to_cell, @@ -1159,6 +1160,7 @@ symbols! { profiler_runtime, ptr, ptr_cast, + ptr_cast_const, ptr_cast_mut, ptr_const_is_null, ptr_from_mut, diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 502f8a75863a5..ee69d89a4b720 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -55,6 +55,7 @@ impl *const T { /// Casts to a pointer of another type. #[stable(feature = "ptr_cast", since = "1.38.0")] #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")] + #[rustc_diagnostic_item = "const_ptr_cast"] #[inline(always)] pub const fn cast(self) -> *const U { self as _ diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index d129e1d645f59..9dbb3f9d322c0 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -112,6 +112,7 @@ impl *mut T { /// [`cast_mut`]: #method.cast_mut #[stable(feature = "ptr_const_cast", since = "1.65.0")] #[rustc_const_stable(feature = "ptr_const_cast", since = "1.65.0")] + #[rustc_diagnostic_item = "ptr_cast_const"] #[inline(always)] pub const fn cast_const(self) -> *const T { self as _ From 91b05f8e098b310a27fa1b1eaeb7d830790d513a Mon Sep 17 00:00:00 2001 From: Urgau Date: Sun, 13 Aug 2023 17:08:33 +0200 Subject: [PATCH 4/8] Improve `invalid_reference_casting` lint --- compiler/rustc_lint/src/reference_casting.rs | 49 +++++++---- tests/ui/lint/reference_casting.rs | 29 +++++++ tests/ui/lint/reference_casting.stderr | 90 ++++++++++++++++---- 3 files changed, 133 insertions(+), 35 deletions(-) diff --git a/compiler/rustc_lint/src/reference_casting.rs b/compiler/rustc_lint/src/reference_casting.rs index 43f50a04aaddc..2577cabb3f0fb 100644 --- a/compiler/rustc_lint/src/reference_casting.rs +++ b/compiler/rustc_lint/src/reference_casting.rs @@ -100,7 +100,7 @@ fn is_cast_from_const_to_mut<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) fn from_casts<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> { // as *mut ... - let e = if let ExprKind::Cast(e, t) = e.kind + let mut e = if let ExprKind::Cast(e, t) = e.kind && let ty::RawPtr(TypeAndMut { mutbl: Mutability::Mut, .. }) = cx.typeck_results().node_type(t.hir_id).kind() { e // .cast_mut() @@ -112,23 +112,36 @@ fn is_cast_from_const_to_mut<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) return None; }; - let e = e.peel_blocks(); - - // as *const ... - let e = if let ExprKind::Cast(e, t) = e.kind - && let ty::RawPtr(TypeAndMut { mutbl: Mutability::Not, .. }) = cx.typeck_results().node_type(t.hir_id).kind() { - e - // ptr::from_ref() - } else if let ExprKind::Call(path, [arg]) = e.kind - && let ExprKind::Path(ref qpath) = path.kind - && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id() - && cx.tcx.is_diagnostic_item(sym::ptr_from_ref, def_id) { - arg - } else { - return None; - }; - - Some(e) + let mut had_at_least_one_cast = false; + loop { + e = e.peel_blocks(); + // as *mut/const ... or as + e = if let ExprKind::Cast(expr, t) = e.kind + && matches!(cx.typeck_results().node_type(t.hir_id).kind(), ty::RawPtr(_) | ty::Uint(_)) { + had_at_least_one_cast = true; + expr + // .cast(), .cast_mut() or .cast_const() + } else if let ExprKind::MethodCall(_, expr, [], _) = e.kind + && let Some(def_id) = cx.typeck_results().type_dependent_def_id(e.hir_id) + && matches!( + cx.tcx.get_diagnostic_name(def_id), + Some(sym::ptr_cast | sym::const_ptr_cast | sym::ptr_cast_mut | sym::ptr_cast_const) + ) + { + had_at_least_one_cast = true; + expr + // ptr::from_ref() + } else if let ExprKind::Call(path, [arg]) = e.kind + && let ExprKind::Path(ref qpath) = path.kind + && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id() + && cx.tcx.is_diagnostic_item(sym::ptr_from_ref, def_id) { + return Some(arg); + } else if had_at_least_one_cast { + return Some(e); + } else { + return None; + }; + } } fn from_transmute<'tcx>( diff --git a/tests/ui/lint/reference_casting.rs b/tests/ui/lint/reference_casting.rs index f4e463b67c07b..6c38bca3daa91 100644 --- a/tests/ui/lint/reference_casting.rs +++ b/tests/ui/lint/reference_casting.rs @@ -9,6 +9,10 @@ extern "C" { fn int_ffi(c: *mut i32); } +fn static_u8() -> &'static u8 { + &8 +} + unsafe fn ref_to_mut() { let num = &3i32; @@ -24,12 +28,28 @@ unsafe fn ref_to_mut() { //~^ ERROR casting `&T` to `&mut T` is undefined behavior let _num = &mut *(std::ptr::from_ref({ num }) as *mut i32); //~^ ERROR casting `&T` to `&mut T` is undefined behavior + let _num = &mut *(num as *const i32).cast::().cast_mut(); + //~^ ERROR casting `&T` to `&mut T` is undefined behavior + let _num = &mut *(num as *const i32).cast::().cast_mut().cast_const().cast_mut(); + //~^ ERROR casting `&T` to `&mut T` is undefined behavior + let _num = &mut *(std::ptr::from_ref(static_u8()) as *mut i32); + //~^ ERROR casting `&T` to `&mut T` is undefined behavior let _num = &mut *std::mem::transmute::<_, *mut i32>(num); //~^ ERROR casting `&T` to `&mut T` is undefined behavior let deferred = num as *const i32 as *mut i32; let _num = &mut *deferred; //~^ ERROR casting `&T` to `&mut T` is undefined behavior + let deferred = (std::ptr::from_ref(num) as *const i32 as *const i32).cast_mut() as *mut i32; + let _num = &mut *deferred; + //~^ ERROR casting `&T` to `&mut T` is undefined behavior + let _num = &mut *(num as *const _ as usize as *mut i32); + //~^ ERROR casting `&T` to `&mut T` is undefined behavior + + unsafe fn generic_ref_cast_mut(this: &T) -> &mut T { + &mut *((this as *const _) as *mut _) + //~^ ERROR casting `&T` to `&mut T` is undefined behavior + } } unsafe fn assign_to_ref() { @@ -55,6 +75,15 @@ unsafe fn assign_to_ref() { let value = num as *const i32 as *mut i32; *value = 1; //~^ ERROR assigning to `&T` is undefined behavior + *(num as *const i32).cast::().cast_mut() = 2; + //~^ ERROR assigning to `&T` is undefined behavior + *(num as *const _ as usize as *mut i32) = 2; + //~^ ERROR assigning to `&T` is undefined behavior + + unsafe fn generic_assign_to_ref(this: &T, a: T) { + *(this as *const _ as *mut _) = a; + //~^ ERROR assigning to `&T` is undefined behavior + } } unsafe fn no_warn() { diff --git a/tests/ui/lint/reference_casting.stderr b/tests/ui/lint/reference_casting.stderr index e8bb0557ca8a0..7ff9b76a85e9a 100644 --- a/tests/ui/lint/reference_casting.stderr +++ b/tests/ui/lint/reference_casting.stderr @@ -1,5 +1,5 @@ error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` - --> $DIR/reference_casting.rs:15:16 + --> $DIR/reference_casting.rs:19:16 | LL | let _num = &mut *(num as *const i32 as *mut i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -7,98 +7,154 @@ LL | let _num = &mut *(num as *const i32 as *mut i32); = note: `#[deny(invalid_reference_casting)]` on by default error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` - --> $DIR/reference_casting.rs:17:16 + --> $DIR/reference_casting.rs:21:16 | LL | let _num = &mut *(num as *const i32).cast_mut(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` - --> $DIR/reference_casting.rs:19:16 + --> $DIR/reference_casting.rs:23:16 | LL | let _num = &mut *std::ptr::from_ref(num).cast_mut(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` - --> $DIR/reference_casting.rs:21:16 + --> $DIR/reference_casting.rs:25:16 | LL | let _num = &mut *std::ptr::from_ref({ num }).cast_mut(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` - --> $DIR/reference_casting.rs:23:16 + --> $DIR/reference_casting.rs:27:16 | LL | let _num = &mut *{ std::ptr::from_ref(num) }.cast_mut(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` - --> $DIR/reference_casting.rs:25:16 + --> $DIR/reference_casting.rs:29:16 | LL | let _num = &mut *(std::ptr::from_ref({ num }) as *mut i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` - --> $DIR/reference_casting.rs:27:16 + --> $DIR/reference_casting.rs:31:16 + | +LL | let _num = &mut *(num as *const i32).cast::().cast_mut(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` + --> $DIR/reference_casting.rs:33:16 + | +LL | let _num = &mut *(num as *const i32).cast::().cast_mut().cast_const().cast_mut(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` + --> $DIR/reference_casting.rs:35:16 + | +LL | let _num = &mut *(std::ptr::from_ref(static_u8()) as *mut i32); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` + --> $DIR/reference_casting.rs:37:16 | LL | let _num = &mut *std::mem::transmute::<_, *mut i32>(num); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` - --> $DIR/reference_casting.rs:31:16 + --> $DIR/reference_casting.rs:41:16 | LL | let deferred = num as *const i32 as *mut i32; | ----------------------------- casting happend here LL | let _num = &mut *deferred; | ^^^^^^^^^^^^^^ +error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` + --> $DIR/reference_casting.rs:44:16 + | +LL | let deferred = (std::ptr::from_ref(num) as *const i32 as *const i32).cast_mut() as *mut i32; + | ---------------------------------------------------------------------------- casting happend here +LL | let _num = &mut *deferred; + | ^^^^^^^^^^^^^^ + +error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` + --> $DIR/reference_casting.rs:46:16 + | +LL | let _num = &mut *(num as *const _ as usize as *mut i32); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell` + --> $DIR/reference_casting.rs:50:9 + | +LL | &mut *((this as *const _) as *mut _) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` - --> $DIR/reference_casting.rs:40:5 + --> $DIR/reference_casting.rs:60:5 | LL | *(a as *const _ as *mut _) = String::from("Replaced"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` - --> $DIR/reference_casting.rs:42:5 + --> $DIR/reference_casting.rs:62:5 | LL | *(a as *const _ as *mut String) += " world"; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` - --> $DIR/reference_casting.rs:44:5 + --> $DIR/reference_casting.rs:64:5 | LL | *std::ptr::from_ref(num).cast_mut() += 1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` - --> $DIR/reference_casting.rs:46:5 + --> $DIR/reference_casting.rs:66:5 | LL | *std::ptr::from_ref({ num }).cast_mut() += 1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` - --> $DIR/reference_casting.rs:48:5 + --> $DIR/reference_casting.rs:68:5 | LL | *{ std::ptr::from_ref(num) }.cast_mut() += 1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` - --> $DIR/reference_casting.rs:50:5 + --> $DIR/reference_casting.rs:70:5 | LL | *(std::ptr::from_ref({ num }) as *mut i32) += 1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` - --> $DIR/reference_casting.rs:52:5 + --> $DIR/reference_casting.rs:72:5 | LL | *std::mem::transmute::<_, *mut i32>(num) += 1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` - --> $DIR/reference_casting.rs:56:5 + --> $DIR/reference_casting.rs:76:5 | LL | let value = num as *const i32 as *mut i32; | ----------------------------- casting happend here LL | *value = 1; | ^^^^^^^^^^ -error: aborting due to 16 previous errors +error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` + --> $DIR/reference_casting.rs:78:5 + | +LL | *(num as *const i32).cast::().cast_mut() = 2; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` + --> $DIR/reference_casting.rs:80:5 + | +LL | *(num as *const _ as usize as *mut i32) = 2; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` + --> $DIR/reference_casting.rs:84:9 + | +LL | *(this as *const _ as *mut _) = a; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 25 previous errors From 50ca860b5fbcbc6f2c98fcc6b90e6511341d90be Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Wed, 16 Aug 2023 06:33:31 +0200 Subject: [PATCH 5/8] rustc book: make more pleasant to search --- src/doc/rustc/book.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/doc/rustc/book.toml b/src/doc/rustc/book.toml index 14ae1a7207ac0..167aece0ed6a3 100644 --- a/src/doc/rustc/book.toml +++ b/src/doc/rustc/book.toml @@ -7,5 +7,8 @@ title = "The rustc book" git-repository-url = "https://github.com/rust-lang/rust/tree/master/src/doc/rustc" edit-url-template = "https://github.com/rust-lang/rust/edit/master/src/doc/rustc/{path}" +[output.html.search] +use-boolean-and = true + [output.html.playground] runnable = false From a1a94b1c0f0b990fa5dc0ecf05ba3acaa17a1d9a Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 14 Aug 2023 22:25:32 +0200 Subject: [PATCH 6/8] Improve code readability by moving fmt args directly into the string --- src/librustdoc/clean/auto_trait.rs | 14 +-- src/librustdoc/clean/blanket_impl.rs | 4 +- src/librustdoc/clean/cfg.rs | 28 +++--- src/librustdoc/clean/inline.rs | 6 +- src/librustdoc/clean/mod.rs | 8 +- src/librustdoc/clean/types.rs | 6 +- src/librustdoc/clean/utils.rs | 18 ++-- src/librustdoc/config.rs | 26 +++--- src/librustdoc/core.rs | 9 +- src/librustdoc/docfs.rs | 2 +- src/librustdoc/doctest.rs | 10 +-- src/librustdoc/externalfiles.rs | 8 +- src/librustdoc/html/format.rs | 55 ++++++------ src/librustdoc/html/highlight.rs | 21 +++-- src/librustdoc/html/highlight/tests.rs | 2 +- src/librustdoc/html/length_limit.rs | 7 +- src/librustdoc/html/markdown.rs | 32 +++---- src/librustdoc/html/render/context.rs | 19 ++-- src/librustdoc/html/render/mod.rs | 14 ++- src/librustdoc/html/render/print_item.rs | 90 +++++++++---------- src/librustdoc/html/render/sidebar.rs | 14 +-- src/librustdoc/html/render/write_shared.rs | 19 ++-- src/librustdoc/html/sources.rs | 3 +- src/librustdoc/html/static_files.rs | 2 +- src/librustdoc/json/mod.rs | 6 +- src/librustdoc/lib.rs | 12 ++- src/librustdoc/markdown.rs | 10 +-- .../passes/calculate_doc_coverage.rs | 6 +- .../passes/check_doc_test_visibility.rs | 2 +- .../passes/collect_intra_doc_links.rs | 76 ++++++++-------- src/librustdoc/passes/lint/bare_urls.rs | 4 +- .../passes/lint/check_code_block_syntax.rs | 6 +- src/librustdoc/passes/lint/html_tags.rs | 10 +-- src/librustdoc/scrape_examples.rs | 6 +- src/librustdoc/visit_ast.rs | 6 +- 35 files changed, 261 insertions(+), 300 deletions(-) diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 68d636b360ac7..ec804bb98f019 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() @@ -164,7 +164,7 @@ where region_name(region) .map(|name| { names_map.get(&name).unwrap_or_else(|| { - panic!("Missing lifetime with name {:?} for {:?}", name.as_str(), region) + panic!("Missing lifetime with name {:?} for {region:?}", name.as_str()) }) }) .unwrap_or(&Lifetime::statik()) @@ -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 83886dd42aac4..0bb8fcd246805 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))?; @@ -551,21 +551,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}"), }, _ => "", }; @@ -580,12 +580,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 389bac0f09dbc..5d5fb2ae2480e 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 b6ba4c853d4cd..51e454eac1686 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..a973538073c0a 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,7 +601,7 @@ 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) + writeln!(out, " {} => {{ ... }}{arm_delim}", render_macro_matcher(tcx, matcher)) .unwrap(); } out @@ -618,20 +618,18 @@ 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{}}}", render_macro_arms(cx.tcx, matchers, ";")) } else { if matchers.len() <= 1 { format!( - "{}macro {}{} {{\n ...\n}}", + "{}macro {name}{} {{\n ...\n}}", visibility_to_src_with_space(Some(vis), cx.tcx, def_id), - name, matchers.map(|matcher| render_macro_matcher(cx.tcx, matcher)).collect::(), ) } else { format!( - "{}macro {} {{\n{}}}", + "{}macro {name} {{\n{}}}", visibility_to_src_with_space(Some(vis), cx.tcx, def_id), - name, 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..2962517badcff 100644 --- a/src/librustdoc/docfs.rs +++ b/src/librustdoc/docfs.rs @@ -72,7 +72,7 @@ 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(|_| { + sender.send(format!("\"{}\": {e}", path.display())).unwrap_or_else(|_| { panic!("failed to send error on \"{}\"", path.display()) }) }); 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..ada5f0fadacb3 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,7 @@ 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 `{}`: {e}", file_path.display())).emit(); return Err(LoadStringError::ReadFail); } }; diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 58022046294be..b00b48c5d64c1 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -228,9 +228,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 +451,9 @@ impl clean::GenericBound { hir::TraitBoundModifier::MaybeConst => "", }; if f.alternate() { - write!(f, "{}{:#}", modifier_str, ty.print(cx)) + write!(f, "{modifier_str}{:#}", ty.print(cx)) } else { - write!(f, "{}{}", modifier_str, ty.print(cx)) + write!(f, "{modifier_str}{}", ty.print(cx)) } } }) @@ -599,7 +599,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 +631,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.iter().map(|p| p.as_str()).join("/")) } ExternalLocation::Local => { // `root_path` always end with a `/`. format!( - "{}{}/{}", + "{}{crate_name}/{}", root_path.unwrap_or(""), - crate_name, 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 +731,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())) @@ -838,7 +837,7 @@ fn resolved_path<'cx>( } else { anchor(did, last.name, cx).to_string() }; - write!(w, "{}{}", path, last.args.print(cx))?; + write!(w, "{path}{}", last.args.print(cx))?; } Ok(()) } @@ -906,7 +905,7 @@ fn primitive_link_fragment( None => {} } } - write!(f, "{}", name)?; + f.write_str(name)?; if needs_termination { write!(f, "")?; } @@ -946,15 +945,11 @@ pub(crate) fn anchor<'a, 'cx: 'a>( if let Ok((url, short_ty, fqp)) = parts { write!( f, - r#"{}"#, - short_ty, - url, - short_ty, + r#"{text}"#, join_with_double_colon(&fqp), - text.as_str() ) } else { - write!(f, "{}", text) + f.write_str(text.as_str()) } }) } @@ -965,10 +960,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 +1080,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} {:#}", t.print(cx)) } else { - format!("*{} {}", m, t.print(cx)) + format!("*{m} {}", 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) } } @@ -1446,10 +1441,10 @@ impl clean::FnDecl { write!(f, "self")?; } clean::SelfBorrowed(Some(ref lt), mtbl) => { - write!(f, "{}{} {}self", amp, lt.print(), mtbl.print_with_space())?; + write!(f, "{amp}{} {}self", lt.print(), mtbl.print_with_space())?; } clean::SelfBorrowed(None, mtbl) => { - write!(f, "{}{}self", amp, mtbl.print_with_space())?; + write!(f, "{amp}{}self", mtbl.print_with_space())?; } clean::SelfExplicit(ref typ) => { write!(f, "self: ")?; @@ -1523,7 +1518,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 +1527,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 +1627,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 {} as {name};", self.source.print(cx)) } } clean::ImportKind::Glob => { @@ -1661,7 +1656,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..e5d1b2f060c01 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.as_html()).unwrap(); return Some(""); }; @@ -947,14 +947,13 @@ fn string_without_closing_tag( match t { "self" | "Self" => write!( &mut path, - "{}", + "{t}", Class::Self_(DUMMY_SP).as_html(), - t ), "crate" | "super" => { - write!(&mut path, "{}", Class::KeyWord.as_html(), t) + write!(&mut path, "{t}", Class::KeyWord.as_html()) } - t => write!(&mut path, "{}", t), + t => write!(&mut path, "{t}"), } .expect("Failed to build source HTML path"); path @@ -997,13 +996,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 +1017,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..a31b228b70689 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -246,9 +246,8 @@ impl<'a, I: Iterator>> Iterator for CodeBlocks<'_, 'a, I> { return Some(Event::Html( format!( "
\ -
{}
\ +
{}
\
", - lang, 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, + "Run", )) }); @@ -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 {}", 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 {}", 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.into_toc().print()) } } diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index 991edbddc6f45..f1d207d99e733 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 `{}`.", + "API documentation for the Rust `{}` {tyname} in crate `{}`.", it.name.as_ref().unwrap(), - tyname, 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,7 @@ 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!("{}{path}", self.root_path())), } } } @@ -382,11 +381,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 +850,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..f03aaf0590581 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,7 @@ 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 {:#?}, target {target:#?}", 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..f07c93ca58e7b 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, + r#"{contents}"#, Escape(title), - contents ) }) } @@ -614,7 +610,7 @@ 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={:?} {:?} - {:?} = {cfg:?}", item.name, item.cfg, parent.cfg); if let Some(ref cfg) = cfg { write!( f, @@ -689,14 +685,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,10 +737,8 @@ 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, + "{count_consts} associated constant{} and {count_methods} method{}", pluralize(count_consts), - count_methods, pluralize(count_methods), ), ); @@ -768,7 +761,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 +830,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 {:?}", 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 +840,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 +1163,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 +1191,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 +1216,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 +1347,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 +1355,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 +1411,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 +1610,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!("{}.{field_name}", ItemType::StructField)); write!( w, "\ @@ -1722,7 +1715,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 +1838,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,14 +1901,13 @@ 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, + "\n{tab} {}{}: {},", visibility_print_with_space(field.visibility(tcx), field.item_id, cx), field.name.unwrap(), ty.print(cx), @@ -1925,9 +1917,9 @@ fn render_struct( 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..e958721dc5565 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!("{}.{name}", 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!("{}.{name}", 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..2a37577b22b04 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}{}.{extension}", 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. ", + "
  5. {s}
  6. ", ensure_trailing_slash(s), - 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..5a221c0e1c79d 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 `{}`: {}", + "failed to render source code for `{}`: {e}", filename.prefer_local(), - e, ), ); 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..ca84b91522322 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!("{}: {e}", options.output.display())); } let input = input.as_ref(); @@ -57,11 +57,11 @@ 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!("{}: {err}", 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!("{}: {e}", output.display()))?; let (metadata, text) = extract_leading_metadata(&input_str); if metadata.is_empty() { @@ -129,7 +129,7 @@ pub(crate) fn render>( ); match err { - Err(e) => Err(format!("cannot write to `{}`: {}", output.display(), e)), + Err(e) => Err(format!("cannot write to `{}`: {e}", output.display())), Ok(_) => Ok(()), } } @@ -137,7 +137,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!("{}: {err}", 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..305d2e7c162f8 100644 --- a/src/librustdoc/passes/calculate_doc_coverage.rs +++ b/src/librustdoc/passes/calculate_doc_coverage.rs @@ -146,8 +146,8 @@ 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} | {:>10} | {percentage:>9.1}% | {:>10} | {:>9.1}% |", + count.with_docs, count.with_examples, examples_percentage, ); } @@ -249,7 +249,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..f21b0999e87e3 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, + "comparing type {impl_type} with kind {:?} against type {ty:?}", impl_type.kind(), - ty ); // 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 `{}`", + "the {} `{name}` has no {} named `{unresolved}`", res.descr(), - name, disambiguator.map_or(path_description, |d| d.descr()), - unresolved, ); 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: // From 16b34bfae3f3a933b216dc6659ae4702168c723a Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 15 Aug 2023 14:27:29 +0200 Subject: [PATCH 7/8] Use more named format args --- src/librustdoc/clean/auto_trait.rs | 6 +-- src/librustdoc/clean/utils.rs | 24 +++++---- src/librustdoc/docfs.rs | 6 +-- src/librustdoc/externalfiles.rs | 6 ++- src/librustdoc/html/format.rs | 51 ++++++++++++------- src/librustdoc/html/highlight.rs | 12 +++-- src/librustdoc/html/markdown.rs | 12 ++--- src/librustdoc/html/render/context.rs | 13 +++-- src/librustdoc/html/render/mod.rs | 13 +++-- src/librustdoc/html/render/print_item.rs | 30 ++++++----- src/librustdoc/html/render/sidebar.rs | 4 +- src/librustdoc/html/render/write_shared.rs | 6 +-- src/librustdoc/html/sources.rs | 4 +- src/librustdoc/markdown.rs | 12 +++-- .../passes/calculate_doc_coverage.rs | 6 ++- .../passes/collect_intra_doc_links.rs | 10 ++-- 16 files changed, 130 insertions(+), 85 deletions(-) diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index ec804bb98f019..a06f31a932919 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -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 {region:?}", name.as_str()) - }) + names_map + .get(&name) + .unwrap_or_else(|| panic!("Missing lifetime with name {name:?} for {region:?}")) }) .unwrap_or(&Lifetime::statik()) .clone() diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index a973538073c0a..80a7a33d2bda2 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -601,8 +601,12 @@ pub(super) fn render_macro_arms<'a>( ) -> String { let mut out = String::new(); for matcher in matchers { - writeln!(out, " {} => {{ ... }}{arm_delim}", render_macro_matcher(tcx, matcher)) - .unwrap(); + writeln!( + out, + " {matcher} => {{ ... }}{arm_delim}", + matcher = render_macro_matcher(tcx, matcher), + ) + .unwrap(); } out } @@ -618,19 +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! {name} {{\n{}}}", 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 {name}{} {{\n ...\n}}", - visibility_to_src_with_space(Some(vis), cx.tcx, def_id), - 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 {name} {{\n{}}}", - visibility_to_src_with_space(Some(vis), cx.tcx, def_id), - 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/docfs.rs b/src/librustdoc/docfs.rs index 2962517badcff..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!("\"{}\": {e}", path.display())).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/externalfiles.rs b/src/librustdoc/externalfiles.rs index ada5f0fadacb3..f0ebb8e5a3905 100644 --- a/src/librustdoc/externalfiles.rs +++ b/src/librustdoc/externalfiles.rs @@ -81,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 `{}`: {e}", file_path.display())).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 b00b48c5d64c1..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); } @@ -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)) } } }) @@ -631,14 +635,14 @@ 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!( - "{}{crate_name}/{}", - root_path.unwrap_or(""), - 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 => { @@ -827,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() @@ -837,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(()) } @@ -945,8 +949,8 @@ pub(crate) fn anchor<'a, 'cx: 'a>( if let Ok((url, short_ty, fqp)) = parts { write!( f, - r#"{text}"#, - join_with_double_colon(&fqp), + r#"{text}"#, + path = join_with_double_colon(&fqp), ) } else { f.write_str(text.as_str()) @@ -1080,9 +1084,9 @@ 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 { @@ -1440,11 +1444,20 @@ impl clean::FnDecl { clean::SelfValue => { write!(f, "self")?; } - clean::SelfBorrowed(Some(ref lt), mtbl) => { - write!(f, "{amp}{} {}self", 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, "{amp}{}self", 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: ")?; @@ -1627,7 +1640,7 @@ impl clean::Import { if name == self.source.path.last() { write!(f, "use {};", self.source.print(cx)) } else { - write!(f, "use {} as {name};", self.source.print(cx)) + write!(f, "use {source} as {name};", source = self.source.print(cx)) } } clean::ImportKind::Glob => { diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index e5d1b2f060c01..039e8cdb98738 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -937,7 +937,7 @@ fn string_without_closing_tag( write!(out, "{text}").unwrap(); return None; } - write!(out, "{text}", klass.as_html()).unwrap(); + write!(out, "{text}", klass = klass.as_html()).unwrap(); return Some(""); }; @@ -947,11 +947,15 @@ fn string_without_closing_tag( match t { "self" | "Self" => write!( &mut path, - "{t}", - Class::Self_(DUMMY_SP).as_html(), + "{t}", + klass = Class::Self_(DUMMY_SP).as_html(), ), "crate" | "super" => { - write!(&mut path, "{t}", Class::KeyWord.as_html()) + write!( + &mut path, + "{t}", + klass = Class::KeyWord.as_html(), + ) } t => write!(&mut path, "{t}"), } diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index a31b228b70689..0ba2d992392e9 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -246,9 +246,9 @@ impl<'a, I: Iterator>> Iterator for CodeBlocks<'_, 'a, I> { return Some(Event::Html( format!( "
    \ -
    {}
    \ +
    {text}
    \
    ", - Escape(&original_text), + text = Escape(&original_text), ) .into(), )); @@ -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, @@ -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 {text} with {}", link.new_text); + debug!("replacing {text} with {new_text}", new_text = link.new_text); *text = CowStr::Borrowed(&link.new_text); } } @@ -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 {text} with {}", link.new_text); + debug!("replacing {text} with {new_text}", new_text = link.new_text); *text = CowStr::Borrowed(&link.new_text); } } @@ -1038,7 +1038,7 @@ impl MarkdownWithToc<'_> { html::push_html(&mut s, p); } - format!("{s}", toc.into_toc().print()) + format!("{s}", toc = toc.into_toc().print()) } } diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index f1d207d99e733..d7ff248a9bff5 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -206,9 +206,9 @@ impl<'tcx> Context<'tcx> { format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate) } else { format!( - "API documentation for the Rust `{}` {tyname} in crate `{}`.", - it.name.as_ref().unwrap(), - 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; @@ -263,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!("{}{path}", self.root_path())), + None => { + return layout::redirect(&format!( + "{root}{path}", + root = self.root_path() + )); + } } } } diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index f03aaf0590581..ac9c180a6a867 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -565,10 +565,10 @@ fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option None, }) .expect("Expected associated type binding"); - debug!("Render deref methods for {:#?}, target {target:#?}", impl_.inner_impl().for_); + 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 f07c93ca58e7b..6cab349862233 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -581,8 +581,8 @@ fn extra_info_tags<'a, 'tcx: 'a>( display_fn(move |f| { write!( f, - r#"{contents}"#, - Escape(title), + r#"{contents}"#, + title = Escape(title), ) }) } @@ -610,7 +610,12 @@ fn extra_info_tags<'a, 'tcx: 'a>( (cfg, _) => cfg.as_deref().cloned(), }; - debug!("Portability name={:?} {:?} - {:?} = {cfg:?}", item.name, item.cfg, parent.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, @@ -737,9 +742,10 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean: toggle_open( &mut w, format_args!( - "{count_consts} associated constant{} and {count_methods} method{}", - pluralize(count_consts), - 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), ), ); } @@ -830,7 +836,7 @@ 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 {name} on {:?}", 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 mut content = Buffer::empty_from(w); @@ -1610,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!("{}.{field_name}", ItemType::StructField)); + let id = cx.derive_id(format!("{typ}.{field_name}", typ = ItemType::StructField)); write!( w, "\ @@ -1907,10 +1913,10 @@ fn render_struct( 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), ); } } diff --git a/src/librustdoc/html/render/sidebar.rs b/src/librustdoc/html/render/sidebar.rs index e958721dc5565..f3da610565c44 100644 --- a/src/librustdoc/html/render/sidebar.rs +++ b/src/librustdoc/html/render/sidebar.rs @@ -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!("{}.{name}", ItemType::Method)), + 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!("{}.{name}", ItemType::AssocConst)), + 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 2a37577b22b04..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}{}.{extension}", cx.shared.resource_suffix); + let filename = format!("{theme}{suffix}.{extension}", suffix = cx.shared.resource_suffix); cx.shared.fs.write(cx.dst.join(filename), bytes)?; } @@ -349,8 +349,8 @@ if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex}; .iter() .map(|s| { format!( - "
  7. {s}
  8. ", - ensure_trailing_slash(s), + "
  9. {s}
  10. ", + trailing_slash = ensure_trailing_slash(s), ) }) .collect::() diff --git a/src/librustdoc/html/sources.rs b/src/librustdoc/html/sources.rs index 5a221c0e1c79d..c4a1ebbec02ea 100644 --- a/src/librustdoc/html/sources.rs +++ b/src/librustdoc/html/sources.rs @@ -146,8 +146,8 @@ impl DocVisitor for SourceCollector<'_, '_> { self.cx.shared.tcx.sess.span_err( span, format!( - "failed to render source code for `{}`: {e}", - filename.prefer_local(), + "failed to render source code for `{filename}`: {e}", + filename = filename.prefer_local(), ), ); false diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index ca84b91522322..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!("{}: {e}", options.output.display())); + 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!("{}: {err}", input.display()))?; + 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!("{}: {e}", output.display()))?; + 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 `{}`: {e}", output.display())), + 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!("{}: {err}", options.input.display()))?; + .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 305d2e7c162f8..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!( - "| {name:<35} | {:>10} | {percentage:>9.1}% | {:>10} | {:>9.1}% |", - count.with_docs, 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, ); } diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index f21b0999e87e3..26ff64f06a321 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -790,8 +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 {impl_type} with kind {:?} against type {ty:?}", - impl_type.kind(), + "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. @@ -1876,9 +1876,9 @@ fn resolution_failure( }; let name = res.name(tcx); let note = format!( - "the {} `{name}` has no {} named `{unresolved}`", - res.descr(), - disambiguator.map_or(path_description, |d| d.descr()), + "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); From 66573b578130bca54eea2ec6fc853e05be974634 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Wed, 16 Aug 2023 13:10:52 -0300 Subject: [PATCH 8/8] Add missing Clone/Debug impls to SMIR Trait related tys --- compiler/rustc_smir/src/stable_mir/ty.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/compiler/rustc_smir/src/stable_mir/ty.rs b/compiler/rustc_smir/src/stable_mir/ty.rs index f8ff6741208f1..7a6601f09da43 100644 --- a/compiler/rustc_smir/src/stable_mir/ty.rs +++ b/compiler/rustc_smir/src/stable_mir/ty.rs @@ -432,12 +432,14 @@ pub struct UnevaluatedConst { pub promoted: Option, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TraitSpecializationKind { None, Marker, AlwaysApplicable, } +#[derive(Clone, Debug)] pub struct TraitDecl { pub def_id: TraitDef, pub unsafety: Safety, @@ -454,6 +456,7 @@ pub struct TraitDecl { pub type ImplTrait = EarlyBinder; +#[derive(Clone, Debug)] pub struct TraitRef { pub def_id: TraitDef, pub args: GenericArgs,