From b328688d23d56a7b95ddcd994c3967a193dd25ea Mon Sep 17 00:00:00 2001 From: Jon Gjengset Date: Mon, 7 Mar 2022 16:59:10 -0800 Subject: [PATCH 01/11] Statically compile libstdc++ everywhere if asked PR #93918 made it so that `-static-libstdc++` was only set in one place, and was only set during linking, but accidentally also made it so that it is no longer passed when building LLD or sanitizers, only when building LLVM itself. This moves the logic for setting `-static-libstdc++` in the linker flags back to `configure_cmake` so that it takes effect for all CMake invocations in `native.rs`. As a side-effect, this also causes libstdc++ to be statically compiled into sanitizers and LLD if `llvm-tools-enabled` is set but `llvm-static-stdcpp` is not, even though previously it was only linked statically if `llvm-static-stdcpp` was set explicitly. But that seems more like the expected behavior anyway. --- src/bootstrap/native.rs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/bootstrap/native.rs b/src/bootstrap/native.rs index f00c5ce5aa6f0..0fe39defae85d 100644 --- a/src/bootstrap/native.rs +++ b/src/bootstrap/native.rs @@ -259,18 +259,6 @@ impl Step for Llvm { cfg.define("LLVM_LINK_LLVM_DYLIB", "ON"); } - // For distribution we want the LLVM tools to be *statically* linked to libstdc++. - // We also do this if the user explicitly requested static libstdc++. - if builder.config.llvm_tools_enabled || builder.config.llvm_static_stdcpp { - if !target.contains("msvc") && !target.contains("netbsd") { - if target.contains("apple") { - ldflags.push_all("-static-libstdc++"); - } else { - ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++"); - } - } - } - if target.starts_with("riscv") && !target.contains("freebsd") { // RISC-V GCC erroneously requires linking against // `libatomic` when using 1-byte and 2-byte C++ @@ -576,6 +564,18 @@ fn configure_cmake( ldflags.push_all(&flags); } + // For distribution we want the LLVM tools to be *statically* linked to libstdc++. + // We also do this if the user explicitly requested static libstdc++. + if builder.config.llvm_tools_enabled || builder.config.llvm_static_stdcpp { + if !target.contains("msvc") && !target.contains("netbsd") { + if target.contains("apple") { + ldflags.push_all("-static-libstdc++"); + } else { + ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++"); + } + } + } + cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared); cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module); cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe); From 307ee94a8a535019feadf69ce4258cdfb67a3a1c Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 7 Mar 2022 23:06:59 -0800 Subject: [PATCH 02/11] only emit pointer-like metadata for BZST-allocator Box --- .../src/debuginfo/metadata.rs | 4 +++- .../debuginfo-box-with-large-allocator.rs | 23 +++++++++++++++++++ ...fo_with_uninhabitable_field_and_unsized.rs | 2 +- 3 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 src/test/ui/debuginfo/debuginfo-box-with-large-allocator.rs diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index 89fc898003737..a6e4878e5b361 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -617,7 +617,9 @@ pub fn type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll ty::RawPtr(ty::TypeAndMut { ty: pointee_type, .. }) | ty::Ref(_, pointee_type, _) => { pointer_or_reference_metadata(cx, t, pointee_type, unique_type_id) } - ty::Adt(def, _) if def.is_box() => { + // Box may have a non-ZST allocator A. In that case, we + // cannot treat Box as just an owned alias of `*mut T`. + ty::Adt(def, substs) if def.is_box() && cx.layout_of(substs.type_at(1)).is_zst() => { pointer_or_reference_metadata(cx, t, t.boxed_ty(), unique_type_id) } ty::FnDef(..) | ty::FnPtr(_) => subroutine_type_metadata(cx, unique_type_id), diff --git a/src/test/ui/debuginfo/debuginfo-box-with-large-allocator.rs b/src/test/ui/debuginfo/debuginfo-box-with-large-allocator.rs new file mode 100644 index 0000000000000..761539227a79c --- /dev/null +++ b/src/test/ui/debuginfo/debuginfo-box-with-large-allocator.rs @@ -0,0 +1,23 @@ +// build-pass +// compile-flags: -Cdebuginfo=2 +// fixes issue #94725 + +#![feature(allocator_api)] + +use std::alloc::{AllocError, Allocator, Layout}; +use std::ptr::NonNull; + +struct ZST; + +unsafe impl Allocator for &ZST { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + todo!() + } + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + todo!() + } +} + +fn main() { + let _ = Box::::new_in(43, &ZST); +} diff --git a/src/test/ui/debuginfo/debuginfo_with_uninhabitable_field_and_unsized.rs b/src/test/ui/debuginfo/debuginfo_with_uninhabitable_field_and_unsized.rs index 833a4726acb0f..b3f22ecf5115e 100644 --- a/src/test/ui/debuginfo/debuginfo_with_uninhabitable_field_and_unsized.rs +++ b/src/test/ui/debuginfo/debuginfo_with_uninhabitable_field_and_unsized.rs @@ -1,4 +1,4 @@ -// check-pass +// build-pass // compile-flags: -Cdebuginfo=2 // fixes issue #94149 From 885275207810dc0143b56bc4357461aa4c8ed07b Mon Sep 17 00:00:00 2001 From: David Koloski Date: Wed, 23 Feb 2022 04:53:17 +0000 Subject: [PATCH 03/11] Treat unstable lints as unknown This change causes unstable lints to be ignored if the `unknown_lints` lint is allowed. To achieve this, it also changes lints to apply as soon as they are processed. Previously, lints in the same set were processed as a batch and then all simultaneously applied. Implementation of https://github.com/rust-lang/compiler-team/issues/469 --- compiler/rustc_feature/src/active.rs | 2 + compiler/rustc_lint/src/levels.rs | 92 ++++++++++++------- compiler/rustc_lint_defs/src/builtin.rs | 9 ++ compiler/rustc_span/src/symbol.rs | 1 + ...llow-unknown-unstable-lint-command-line.rs | 4 + .../allow-unknown-unstable-lint-inline.rs | 5 + .../unstable-lint-command-line.rs | 5 + .../unstable-lint-command-line.stderr | 11 +++ .../unstable-lint-inline.rs | 6 ++ .../unstable-lint-inline.stderr | 19 ++++ 10 files changed, 119 insertions(+), 35 deletions(-) create mode 100644 src/test/ui/unknown-unstable-lints/allow-unknown-unstable-lint-command-line.rs create mode 100644 src/test/ui/unknown-unstable-lints/allow-unknown-unstable-lint-inline.rs create mode 100644 src/test/ui/unknown-unstable-lints/unstable-lint-command-line.rs create mode 100644 src/test/ui/unknown-unstable-lints/unstable-lint-command-line.stderr create mode 100644 src/test/ui/unknown-unstable-lints/unstable-lint-inline.rs create mode 100644 src/test/ui/unknown-unstable-lints/unstable-lint-inline.stderr diff --git a/compiler/rustc_feature/src/active.rs b/compiler/rustc_feature/src/active.rs index a69d28b184aed..09557332fd725 100644 --- a/compiler/rustc_feature/src/active.rs +++ b/compiler/rustc_feature/src/active.rs @@ -169,6 +169,8 @@ declare_features! ( (active, staged_api, "1.0.0", None, None), /// Added for testing E0705; perma-unstable. (active, test_2018_feature, "1.31.0", None, Some(Edition::Edition2018)), + /// Added for testing unstable lints; perma-unstable. + (active, test_unstable_lint, "1.60.0", None, None), /// Allows non-`unsafe` —and thus, unsound— access to `Pin` constructions. /// Marked `incomplete` since perma-unstable and unsound. (incomplete, unsafe_pin_internals, "1.60.0", None, None), diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index bbfbf61f4869a..a72e0336db915 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -93,10 +93,21 @@ impl<'s> LintLevelsBuilder<'s> { self.store } + fn current_specs(&self) -> &FxHashMap { + &self.sets.list[self.cur].specs + } + + fn current_specs_mut(&mut self) -> &mut FxHashMap { + &mut self.sets.list[self.cur].specs + } + fn process_command_line(&mut self, sess: &Session, store: &LintStore) { - let mut specs = FxHashMap::default(); self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid); + self.cur = self.sets.list.push(LintSet { + specs: FxHashMap::default(), + parent: COMMAND_LINE, + }); for &(ref lint_name, level) in &sess.opts.lint_opts { store.check_lint_name_cmdline(sess, &lint_name, level, self.registered_tools); let orig_level = level; @@ -108,17 +119,16 @@ impl<'s> LintLevelsBuilder<'s> { }; for id in ids { // ForceWarn and Forbid cannot be overriden - if let Some((Level::ForceWarn | Level::Forbid, _)) = specs.get(&id) { + if let Some((Level::ForceWarn | Level::Forbid, _)) = self.current_specs().get(&id) { continue; } - self.check_gated_lint(id, DUMMY_SP); - let src = LintLevelSource::CommandLine(lint_flag_val, orig_level); - specs.insert(id, (level, src)); + if self.check_gated_lint(id, DUMMY_SP) { + let src = LintLevelSource::CommandLine(lint_flag_val, orig_level); + self.current_specs_mut().insert(id, (level, src)); + } } } - - self.cur = self.sets.list.push(LintSet { specs, parent: COMMAND_LINE }); } /// Attempts to insert the `id` to `level_src` map entry. If unsuccessful @@ -126,12 +136,11 @@ impl<'s> LintLevelsBuilder<'s> { /// diagnostic with no change to `specs`. fn insert_spec( &mut self, - specs: &mut FxHashMap, id: LintId, (level, src): LevelAndSource, ) { let (old_level, old_src) = - self.sets.get_lint_level(id.lint, self.cur, Some(&specs), &self.sess); + self.sets.get_lint_level(id.lint, self.cur, Some(self.current_specs()), &self.sess); // Setting to a non-forbid level is an error if the lint previously had // a forbid level. Note that this is not necessarily true even with a // `#[forbid(..)]` attribute present, as that is overriden by `--cap-lints`. @@ -154,7 +163,7 @@ impl<'s> LintLevelsBuilder<'s> { }; debug!( "fcw_warning={:?}, specs.get(&id) = {:?}, old_src={:?}, id_name={:?}", - fcw_warning, specs, old_src, id_name + fcw_warning, self.current_specs(), old_src, id_name ); let decorate_diag = |diag: &mut Diagnostic| { @@ -213,9 +222,9 @@ impl<'s> LintLevelsBuilder<'s> { } } if let Level::ForceWarn = old_level { - specs.insert(id, (old_level, old_src)); + self.current_specs_mut().insert(id, (old_level, old_src)); } else { - specs.insert(id, (level, src)); + self.current_specs_mut().insert(id, (level, src)); } } @@ -239,7 +248,11 @@ impl<'s> LintLevelsBuilder<'s> { is_crate_node: bool, source_hir_id: Option, ) -> BuilderPush { - let mut specs = FxHashMap::default(); + let prev = self.cur; + self.cur = self.sets.list.push(LintSet { + specs: FxHashMap::default(), + parent: prev, + }); let sess = self.sess; let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input"); for (attr_index, attr) in attrs.iter().enumerate() { @@ -348,8 +361,9 @@ impl<'s> LintLevelsBuilder<'s> { reason, ); for &id in *ids { - self.check_gated_lint(id, attr.span); - self.insert_spec(&mut specs, id, (level, src)); + if self.check_gated_lint(id, attr.span) { + self.insert_spec(id, (level, src)); + } } if let Level::Expect(expect_id) = level { self.lint_expectations @@ -368,7 +382,7 @@ impl<'s> LintLevelsBuilder<'s> { reason, ); for id in ids { - self.insert_spec(&mut specs, *id, (level, src)); + self.insert_spec(*id, (level, src)); } if let Level::Expect(expect_id) = level { self.lint_expectations @@ -378,7 +392,7 @@ impl<'s> LintLevelsBuilder<'s> { Err((Some(ids), ref new_lint_name)) => { let lint = builtin::RENAMED_AND_REMOVED_LINTS; let (lvl, src) = - self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess); + self.sets.get_lint_level(lint, self.cur, Some(self.current_specs()), &sess); struct_lint_level( self.sess, lint, @@ -408,7 +422,7 @@ impl<'s> LintLevelsBuilder<'s> { reason, ); for id in ids { - self.insert_spec(&mut specs, *id, (level, src)); + self.insert_spec(*id, (level, src)); } if let Level::Expect(expect_id) = level { self.lint_expectations @@ -449,7 +463,7 @@ impl<'s> LintLevelsBuilder<'s> { CheckLintNameResult::Warning(msg, renamed) => { let lint = builtin::RENAMED_AND_REMOVED_LINTS; let (renamed_lint_level, src) = - self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess); + self.sets.get_lint_level(lint, self.cur, Some(self.current_specs()), &sess); struct_lint_level( self.sess, lint, @@ -473,7 +487,7 @@ impl<'s> LintLevelsBuilder<'s> { CheckLintNameResult::NoLint(suggestion) => { let lint = builtin::UNKNOWN_LINTS; let (level, src) = - self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess); + self.sets.get_lint_level(lint, self.cur, Some(self.current_specs()), self.sess); struct_lint_level(self.sess, lint, level, src, Some(sp.into()), |lint| { let name = if let Some(tool_ident) = tool_ident { format!("{}::{}", tool_ident.name, name) @@ -504,8 +518,9 @@ impl<'s> LintLevelsBuilder<'s> { { let src = LintLevelSource::Node(Symbol::intern(&new_name), sp, reason); for &id in ids { - self.check_gated_lint(id, attr.span); - self.insert_spec(&mut specs, id, (level, src)); + if self.check_gated_lint(id, attr.span) { + self.insert_spec(id, (level, src)); + } } if let Level::Expect(expect_id) = level { self.lint_expectations @@ -519,7 +534,7 @@ impl<'s> LintLevelsBuilder<'s> { } if !is_crate_node { - for (id, &(level, ref src)) in specs.iter() { + for (id, &(level, ref src)) in self.current_specs().iter() { if !id.lint.crate_level_only { continue; } @@ -530,7 +545,7 @@ impl<'s> LintLevelsBuilder<'s> { let lint = builtin::UNUSED_ATTRIBUTES; let (lint_level, lint_src) = - self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess); + self.sets.get_lint_level(lint, self.cur, Some(self.current_specs()), self.sess); struct_lint_level( self.sess, lint, @@ -551,9 +566,9 @@ impl<'s> LintLevelsBuilder<'s> { } } - let prev = self.cur; - if !specs.is_empty() { - self.cur = self.sets.list.push(LintSet { specs, parent: prev }); + if self.current_specs().is_empty() { + self.sets.list.pop(); + self.cur = prev; } BuilderPush { prev, changed: prev != self.cur } @@ -574,18 +589,25 @@ impl<'s> LintLevelsBuilder<'s> { } /// Checks if the lint is gated on a feature that is not enabled. - fn check_gated_lint(&self, lint_id: LintId, span: Span) { + /// + /// Returns `true` if the lint's feature is enabled. + fn check_gated_lint(&self, lint_id: LintId, span: Span) -> bool { if let Some(feature) = lint_id.lint.feature_gate { if !self.sess.features_untracked().enabled(feature) { - feature_err( - &self.sess.parse_sess, - feature, - span, - &format!("the `{}` lint is unstable", lint_id.lint.name_lower()), - ) - .emit(); + let (unknown_lints_level, _) = self.lint_level(builtin::UNKNOWN_LINTS); + if unknown_lints_level != Level::Allow { + feature_err( + &self.sess.parse_sess, + feature, + span, + &format!("the `{}` lint is unstable", lint_id.lint.name_lower()), + ) + .emit(); + } + return false; } } + true } /// Called after `push` when the scope of a set of attributes are exited. diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 04a339f3c95a6..e1c88f74ab33c 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -3128,6 +3128,7 @@ declare_lint_pass! { SUSPICIOUS_AUTO_TRAIT_IMPLS, UNEXPECTED_CFGS, DEPRECATED_WHERE_CLAUSE_LOCATION, + TEST_UNSTABLE_LINT, ] } @@ -3771,3 +3772,11 @@ declare_lint! { Warn, "deprecated where clause location" } + +declare_lint! { + #[doc(hidden)] + pub TEST_UNSTABLE_LINT, + Deny, + "this unstable lint is only for testing", + @feature_gate = sym::test_unstable_lint; +} diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 3f44292e03425..24f802c1d4f94 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1383,6 +1383,7 @@ symbols! { test_case, test_removed_feature, test_runner, + test_unstable_lint, then_with, thread, thread_local, diff --git a/src/test/ui/unknown-unstable-lints/allow-unknown-unstable-lint-command-line.rs b/src/test/ui/unknown-unstable-lints/allow-unknown-unstable-lint-command-line.rs new file mode 100644 index 0000000000000..80e30f23993e3 --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/allow-unknown-unstable-lint-command-line.rs @@ -0,0 +1,4 @@ +// check-pass +// compile-flags: -Aunknown_lints -Atest_unstable_lint + +fn main() {} diff --git a/src/test/ui/unknown-unstable-lints/allow-unknown-unstable-lint-inline.rs b/src/test/ui/unknown-unstable-lints/allow-unknown-unstable-lint-inline.rs new file mode 100644 index 0000000000000..992472c894a8c --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/allow-unknown-unstable-lint-inline.rs @@ -0,0 +1,5 @@ +// check-pass + +#![allow(unknown_lints, test_unstable_lint)] + +fn main() {} diff --git a/src/test/ui/unknown-unstable-lints/unstable-lint-command-line.rs b/src/test/ui/unknown-unstable-lints/unstable-lint-command-line.rs new file mode 100644 index 0000000000000..7663abffd9b48 --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/unstable-lint-command-line.rs @@ -0,0 +1,5 @@ +// check-fail +// compile-flags: -Atest_unstable_lint +// error-pattern: the `test_unstable_lint` lint is unstable + +fn main() {} diff --git a/src/test/ui/unknown-unstable-lints/unstable-lint-command-line.stderr b/src/test/ui/unknown-unstable-lints/unstable-lint-command-line.stderr new file mode 100644 index 0000000000000..d088f4c8fe5aa --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/unstable-lint-command-line.stderr @@ -0,0 +1,11 @@ +error[E0658]: the `test_unstable_lint` lint is unstable + | + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +error[E0658]: the `test_unstable_lint` lint is unstable + | + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0658`. diff --git a/src/test/ui/unknown-unstable-lints/unstable-lint-inline.rs b/src/test/ui/unknown-unstable-lints/unstable-lint-inline.rs new file mode 100644 index 0000000000000..43789906ed6f0 --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/unstable-lint-inline.rs @@ -0,0 +1,6 @@ +// check-fail +// error-pattern: the `test_unstable_lint` lint is unstable + +#![allow(test_unstable_lint)] + +fn main() {} diff --git a/src/test/ui/unknown-unstable-lints/unstable-lint-inline.stderr b/src/test/ui/unknown-unstable-lints/unstable-lint-inline.stderr new file mode 100644 index 0000000000000..5ec85f346fec5 --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/unstable-lint-inline.stderr @@ -0,0 +1,19 @@ +error[E0658]: the `test_unstable_lint` lint is unstable + --> $DIR/unstable-lint-inline.rs:4:1 + | +LL | #![allow(test_unstable_lint)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +error[E0658]: the `test_unstable_lint` lint is unstable + --> $DIR/unstable-lint-inline.rs:4:1 + | +LL | #![allow(test_unstable_lint)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0658`. From 2677eca237c92877ac8b0aca4cc58f8a14061ab3 Mon Sep 17 00:00:00 2001 From: David Koloski Date: Mon, 28 Feb 2022 20:29:06 +0000 Subject: [PATCH 04/11] Switch the primary diagnostic to `unknown_lints` This also affects the `non_exhaustive_omitted_patterns` and `must_not_suspend` lints as they are not stable. This also changes the diagnostic level to pull from `unknown_lints` instead of always being allow or deny. --- compiler/rustc_lint/src/levels.rs | 67 ++++++++++-------- compiler/rustc_lint_defs/src/builtin.rs | 1 + compiler/rustc_session/src/parse.rs | 21 +++++- ...te-non_exhaustive_omitted_patterns_lint.rs | 23 +++--- ...on_exhaustive_omitted_patterns_lint.stderr | 70 +++++++++++++------ .../feature-gate-test_unstable_lint.rs | 9 +++ .../feature-gate-test_unstable_lint.stderr | 30 ++++++++ src/test/ui/lint/must_not_suspend/gated.rs | 11 +-- .../ui/lint/must_not_suspend/gated.stderr | 43 +++--------- .../deny-unstable-lint-command-line.rs | 6 ++ .../deny-unstable-lint-command-line.stderr | 18 +++++ .../deny-unstable-lint-inline.rs | 9 +++ .../deny-unstable-lint-inline.stderr | 35 ++++++++++ .../unstable-lint-command-line.rs | 5 -- .../unstable-lint-command-line.stderr | 11 --- .../unstable-lint-inline.rs | 6 -- .../unstable-lint-inline.stderr | 19 ----- ...warn-unknown-unstable-lint-command-line.rs | 6 ++ ...-unknown-unstable-lint-command-line.stderr | 18 +++++ .../warn-unknown-unstable-lint-inline.rs | 9 +++ .../warn-unknown-unstable-lint-inline.stderr | 35 ++++++++++ 21 files changed, 310 insertions(+), 142 deletions(-) create mode 100644 src/test/ui/feature-gates/feature-gate-test_unstable_lint.rs create mode 100644 src/test/ui/feature-gates/feature-gate-test_unstable_lint.stderr create mode 100644 src/test/ui/unknown-unstable-lints/deny-unstable-lint-command-line.rs create mode 100644 src/test/ui/unknown-unstable-lints/deny-unstable-lint-command-line.stderr create mode 100644 src/test/ui/unknown-unstable-lints/deny-unstable-lint-inline.rs create mode 100644 src/test/ui/unknown-unstable-lints/deny-unstable-lint-inline.stderr delete mode 100644 src/test/ui/unknown-unstable-lints/unstable-lint-command-line.rs delete mode 100644 src/test/ui/unknown-unstable-lints/unstable-lint-command-line.stderr delete mode 100644 src/test/ui/unknown-unstable-lints/unstable-lint-inline.rs delete mode 100644 src/test/ui/unknown-unstable-lints/unstable-lint-inline.stderr create mode 100644 src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-command-line.rs create mode 100644 src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-command-line.stderr create mode 100644 src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-inline.rs create mode 100644 src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-inline.stderr diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index a72e0336db915..2b28fc2c0115e 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -17,7 +17,7 @@ use rustc_session::lint::{ builtin::{self, FORBIDDEN_LINT_GROUPS}, Level, Lint, LintExpectationId, LintId, }; -use rustc_session::parse::feature_err; +use rustc_session::parse::{add_feature_diagnostics, feature_err}; use rustc_session::Session; use rustc_span::symbol::{sym, Symbol}; use rustc_span::{source_map::MultiSpan, Span, DUMMY_SP}; @@ -104,10 +104,8 @@ impl<'s> LintLevelsBuilder<'s> { fn process_command_line(&mut self, sess: &Session, store: &LintStore) { self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid); - self.cur = self.sets.list.push(LintSet { - specs: FxHashMap::default(), - parent: COMMAND_LINE, - }); + self.cur = + self.sets.list.push(LintSet { specs: FxHashMap::default(), parent: COMMAND_LINE }); for &(ref lint_name, level) in &sess.opts.lint_opts { store.check_lint_name_cmdline(sess, &lint_name, level, self.registered_tools); let orig_level = level; @@ -134,11 +132,7 @@ impl<'s> LintLevelsBuilder<'s> { /// Attempts to insert the `id` to `level_src` map entry. If unsuccessful /// (e.g. if a forbid was already inserted on the same scope), then emits a /// diagnostic with no change to `specs`. - fn insert_spec( - &mut self, - id: LintId, - (level, src): LevelAndSource, - ) { + fn insert_spec(&mut self, id: LintId, (level, src): LevelAndSource) { let (old_level, old_src) = self.sets.get_lint_level(id.lint, self.cur, Some(self.current_specs()), &self.sess); // Setting to a non-forbid level is an error if the lint previously had @@ -163,7 +157,10 @@ impl<'s> LintLevelsBuilder<'s> { }; debug!( "fcw_warning={:?}, specs.get(&id) = {:?}, old_src={:?}, id_name={:?}", - fcw_warning, self.current_specs(), old_src, id_name + fcw_warning, + self.current_specs(), + old_src, + id_name ); let decorate_diag = |diag: &mut Diagnostic| { @@ -249,10 +246,8 @@ impl<'s> LintLevelsBuilder<'s> { source_hir_id: Option, ) -> BuilderPush { let prev = self.cur; - self.cur = self.sets.list.push(LintSet { - specs: FxHashMap::default(), - parent: prev, - }); + self.cur = self.sets.list.push(LintSet { specs: FxHashMap::default(), parent: prev }); + let sess = self.sess; let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input"); for (attr_index, attr) in attrs.iter().enumerate() { @@ -391,8 +386,12 @@ impl<'s> LintLevelsBuilder<'s> { } Err((Some(ids), ref new_lint_name)) => { let lint = builtin::RENAMED_AND_REMOVED_LINTS; - let (lvl, src) = - self.sets.get_lint_level(lint, self.cur, Some(self.current_specs()), &sess); + let (lvl, src) = self.sets.get_lint_level( + lint, + self.cur, + Some(self.current_specs()), + &sess, + ); struct_lint_level( self.sess, lint, @@ -462,8 +461,12 @@ impl<'s> LintLevelsBuilder<'s> { CheckLintNameResult::Warning(msg, renamed) => { let lint = builtin::RENAMED_AND_REMOVED_LINTS; - let (renamed_lint_level, src) = - self.sets.get_lint_level(lint, self.cur, Some(self.current_specs()), &sess); + let (renamed_lint_level, src) = self.sets.get_lint_level( + lint, + self.cur, + Some(self.current_specs()), + &sess, + ); struct_lint_level( self.sess, lint, @@ -486,8 +489,12 @@ impl<'s> LintLevelsBuilder<'s> { } CheckLintNameResult::NoLint(suggestion) => { let lint = builtin::UNKNOWN_LINTS; - let (level, src) = - self.sets.get_lint_level(lint, self.cur, Some(self.current_specs()), self.sess); + let (level, src) = self.sets.get_lint_level( + lint, + self.cur, + Some(self.current_specs()), + self.sess, + ); struct_lint_level(self.sess, lint, level, src, Some(sp.into()), |lint| { let name = if let Some(tool_ident) = tool_ident { format!("{}::{}", tool_ident.name, name) @@ -594,16 +601,14 @@ impl<'s> LintLevelsBuilder<'s> { fn check_gated_lint(&self, lint_id: LintId, span: Span) -> bool { if let Some(feature) = lint_id.lint.feature_gate { if !self.sess.features_untracked().enabled(feature) { - let (unknown_lints_level, _) = self.lint_level(builtin::UNKNOWN_LINTS); - if unknown_lints_level != Level::Allow { - feature_err( - &self.sess.parse_sess, - feature, - span, - &format!("the `{}` lint is unstable", lint_id.lint.name_lower()), - ) - .emit(); - } + let (level, src) = self.lint_level(builtin::UNKNOWN_LINTS); + struct_lint_level(self.sess, lint_id.lint, level, src, Some(span.into()), |lint| { + let mut db = + lint.build(&format!("unknown lint: `{}`", lint_id.lint.name_lower())); + db.note(&format!("the `{}` lint is unstable", lint_id.lint.name_lower(),)); + add_feature_diagnostics(&mut db, &self.sess.parse_sess, feature); + db.emit(); + }); return false; } } diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index e1c88f74ab33c..f6ad46cc01888 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -3775,6 +3775,7 @@ declare_lint! { declare_lint! { #[doc(hidden)] + /// Added for testing unsable lints; perma-unstable. pub TEST_UNSTABLE_LINT, Deny, "this unstable lint is only for testing", diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 38ddb841d9656..d34a3360a83e2 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -98,7 +98,26 @@ pub fn feature_err_issue<'a>( explain: &str, ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { let mut err = sess.span_diagnostic.struct_span_err_with_code(span, explain, error_code!(E0658)); + add_feature_diagnostics_for_issue(&mut err, sess, feature, issue); + err +} + +/// Adds the diagnostics for a feature to an existing error. +pub fn add_feature_diagnostics<'a>(err: &mut Diagnostic, sess: &'a ParseSess, feature: Symbol) { + add_feature_diagnostics_for_issue(err, sess, feature, GateIssue::Language); +} +/// Adds the diagnostics for a feature to an existing error. +/// +/// This variant allows you to control whether it is a library or language feature. +/// Almost always, you want to use this for a language feature. If so, prefer +/// `add_feature_diagnostics`. +pub fn add_feature_diagnostics_for_issue<'a>( + err: &mut Diagnostic, + sess: &'a ParseSess, + feature: Symbol, + issue: GateIssue, +) { if let Some(n) = find_feature_issue(feature, issue) { err.note(&format!( "see issue #{} for more information", @@ -110,8 +129,6 @@ pub fn feature_err_issue<'a>( if sess.unstable_features.is_nightly_build() { err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature)); } - - err } /// Info about a parsing session. diff --git a/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.rs b/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.rs index 2a34ed4d4f644..29a6e1f8a016d 100644 --- a/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.rs +++ b/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.rs @@ -1,9 +1,11 @@ +// check-fail + #![deny(non_exhaustive_omitted_patterns)] -//~^ ERROR the `non_exhaustive_omitted_patterns` lint is unstable -//~| ERROR the `non_exhaustive_omitted_patterns` lint is unstable +//~^ WARNING unknown lint: `non_exhaustive_omitted_patterns` +//~| WARNING unknown lint: `non_exhaustive_omitted_patterns` #![allow(non_exhaustive_omitted_patterns)] -//~^ ERROR the `non_exhaustive_omitted_patterns` lint is unstable -//~| ERROR the `non_exhaustive_omitted_patterns` lint is unstable +//~^ WARNING unknown lint: `non_exhaustive_omitted_patterns` +//~| WARNING unknown lint: `non_exhaustive_omitted_patterns` fn main() { enum Foo { @@ -11,14 +13,15 @@ fn main() { } #[allow(non_exhaustive_omitted_patterns)] + //~^ WARNING unknown lint: `non_exhaustive_omitted_patterns` + //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` + //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` + //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` match Foo::A { Foo::A => {} Foo::B => {} } - //~^^^^^ ERROR the `non_exhaustive_omitted_patterns` lint is unstable - //~| ERROR the `non_exhaustive_omitted_patterns` lint is unstable - //~| ERROR the `non_exhaustive_omitted_patterns` lint is unstable - //~| ERROR the `non_exhaustive_omitted_patterns` lint is unstable + //~^^^^ ERROR non-exhaustive patterns: `C` not covered match Foo::A { Foo::A => {} @@ -26,6 +29,6 @@ fn main() { #[warn(non_exhaustive_omitted_patterns)] _ => {} } - //~^^^ ERROR the `non_exhaustive_omitted_patterns` lint is unstable - //~| ERROR the `non_exhaustive_omitted_patterns` lint is unstable + //~^^^ WARNING unknown lint: `non_exhaustive_omitted_patterns` + //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` } diff --git a/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr b/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr index 691f64cf0addd..94568c96b40a3 100644 --- a/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr +++ b/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr @@ -1,93 +1,119 @@ -error[E0658]: the `non_exhaustive_omitted_patterns` lint is unstable - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:1:1 +warning: unknown lint: `non_exhaustive_omitted_patterns` + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:3:1 | LL | #![deny(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: `#[warn(non_exhaustive_omitted_patterns)]` on by default + = note: the `non_exhaustive_omitted_patterns` lint is unstable = note: see issue #89554 for more information = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable -error[E0658]: the `non_exhaustive_omitted_patterns` lint is unstable - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:4:1 +warning: unknown lint: `non_exhaustive_omitted_patterns` + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:6:1 | LL | #![allow(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: the `non_exhaustive_omitted_patterns` lint is unstable = note: see issue #89554 for more information = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable -error[E0658]: the `non_exhaustive_omitted_patterns` lint is unstable - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:13:5 +warning: unknown lint: `non_exhaustive_omitted_patterns` + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:15:5 | LL | #[allow(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: the `non_exhaustive_omitted_patterns` lint is unstable = note: see issue #89554 for more information = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable -error[E0658]: the `non_exhaustive_omitted_patterns` lint is unstable - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:13:5 +warning: unknown lint: `non_exhaustive_omitted_patterns` + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:15:5 | LL | #[allow(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: the `non_exhaustive_omitted_patterns` lint is unstable = note: see issue #89554 for more information = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable -error[E0658]: the `non_exhaustive_omitted_patterns` lint is unstable - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:26:9 +warning: unknown lint: `non_exhaustive_omitted_patterns` + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:29:9 | LL | #[warn(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: the `non_exhaustive_omitted_patterns` lint is unstable = note: see issue #89554 for more information = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable -error[E0658]: the `non_exhaustive_omitted_patterns` lint is unstable - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:1:1 +warning: unknown lint: `non_exhaustive_omitted_patterns` + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:3:1 | LL | #![deny(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: the `non_exhaustive_omitted_patterns` lint is unstable = note: see issue #89554 for more information = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable -error[E0658]: the `non_exhaustive_omitted_patterns` lint is unstable - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:4:1 +warning: unknown lint: `non_exhaustive_omitted_patterns` + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:6:1 | LL | #![allow(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: the `non_exhaustive_omitted_patterns` lint is unstable = note: see issue #89554 for more information = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable -error[E0658]: the `non_exhaustive_omitted_patterns` lint is unstable - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:13:5 +warning: unknown lint: `non_exhaustive_omitted_patterns` + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:15:5 | LL | #[allow(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: the `non_exhaustive_omitted_patterns` lint is unstable = note: see issue #89554 for more information = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable -error[E0658]: the `non_exhaustive_omitted_patterns` lint is unstable - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:13:5 +warning: unknown lint: `non_exhaustive_omitted_patterns` + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:15:5 | LL | #[allow(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: the `non_exhaustive_omitted_patterns` lint is unstable = note: see issue #89554 for more information = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable -error[E0658]: the `non_exhaustive_omitted_patterns` lint is unstable - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:26:9 +warning: unknown lint: `non_exhaustive_omitted_patterns` + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:29:9 | LL | #[warn(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: the `non_exhaustive_omitted_patterns` lint is unstable = note: see issue #89554 for more information = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable -error: aborting due to 10 previous errors +error[E0004]: non-exhaustive patterns: `C` not covered + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:20:11 + | +LL | / enum Foo { +LL | | A, B, C, + | | - not covered +LL | | } + | |_____- `Foo` defined here +... +LL | match Foo::A { + | ^^^^^^ pattern `C` not covered + | + = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms + = note: the matched value is of type `Foo` -For more information about this error, try `rustc --explain E0658`. +error: aborting due to previous error; 10 warnings emitted + +For more information about this error, try `rustc --explain E0004`. diff --git a/src/test/ui/feature-gates/feature-gate-test_unstable_lint.rs b/src/test/ui/feature-gates/feature-gate-test_unstable_lint.rs new file mode 100644 index 0000000000000..c398394cbe1a6 --- /dev/null +++ b/src/test/ui/feature-gates/feature-gate-test_unstable_lint.rs @@ -0,0 +1,9 @@ +// check-pass + +// `test_unstable_lint` is for testing and should never be stabilized. +#![allow(test_unstable_lint)] +//~^ WARNING unknown lint: `test_unstable_lint` +//~| WARNING unknown lint: `test_unstable_lint` +//~| WARNING unknown lint: `test_unstable_lint` + +fn main() {} diff --git a/src/test/ui/feature-gates/feature-gate-test_unstable_lint.stderr b/src/test/ui/feature-gates/feature-gate-test_unstable_lint.stderr new file mode 100644 index 0000000000000..eab89f02018bf --- /dev/null +++ b/src/test/ui/feature-gates/feature-gate-test_unstable_lint.stderr @@ -0,0 +1,30 @@ +warning: unknown lint: `test_unstable_lint` + --> $DIR/feature-gate-test_unstable_lint.rs:4:1 + | +LL | #![allow(test_unstable_lint)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: `#[warn(test_unstable_lint)]` on by default + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +warning: unknown lint: `test_unstable_lint` + --> $DIR/feature-gate-test_unstable_lint.rs:4:1 + | +LL | #![allow(test_unstable_lint)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +warning: unknown lint: `test_unstable_lint` + --> $DIR/feature-gate-test_unstable_lint.rs:4:1 + | +LL | #![allow(test_unstable_lint)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +warning: 3 warnings emitted + diff --git a/src/test/ui/lint/must_not_suspend/gated.rs b/src/test/ui/lint/must_not_suspend/gated.rs index acb81b0bf9def..b73a76555296f 100644 --- a/src/test/ui/lint/must_not_suspend/gated.rs +++ b/src/test/ui/lint/must_not_suspend/gated.rs @@ -1,12 +1,15 @@ +// check-pass + // edition:2018 -#![deny(must_not_suspend)] //~ ERROR the `must_not_suspend` -//~| ERROR the `must_not_suspend` -//~| ERROR the `must_not_suspend` +#![deny(must_not_suspend)] +//~^ WARNING unknown lint: `must_not_suspend` +//~| WARNING unknown lint: `must_not_suspend` +//~| WARNING unknown lint: `must_not_suspend` async fn other() {} pub async fn uhoh(m: std::sync::Mutex<()>) { - let _guard = m.lock().unwrap(); //~ ERROR `MutexGuard` held across + let _guard = m.lock().unwrap(); other().await; } diff --git a/src/test/ui/lint/must_not_suspend/gated.stderr b/src/test/ui/lint/must_not_suspend/gated.stderr index 0d4319670e662..3d6877045ff78 100644 --- a/src/test/ui/lint/must_not_suspend/gated.stderr +++ b/src/test/ui/lint/must_not_suspend/gated.stderr @@ -1,54 +1,33 @@ -error[E0658]: the `must_not_suspend` lint is unstable - --> $DIR/gated.rs:2:1 +warning: unknown lint: `must_not_suspend` + --> $DIR/gated.rs:4:1 | LL | #![deny(must_not_suspend)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: `#[warn(must_not_suspend)]` on by default + = note: the `must_not_suspend` lint is unstable = note: see issue #83310 for more information = help: add `#![feature(must_not_suspend)]` to the crate attributes to enable -error[E0658]: the `must_not_suspend` lint is unstable - --> $DIR/gated.rs:2:1 +warning: unknown lint: `must_not_suspend` + --> $DIR/gated.rs:4:1 | LL | #![deny(must_not_suspend)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: the `must_not_suspend` lint is unstable = note: see issue #83310 for more information = help: add `#![feature(must_not_suspend)]` to the crate attributes to enable -error[E0658]: the `must_not_suspend` lint is unstable - --> $DIR/gated.rs:2:1 +warning: unknown lint: `must_not_suspend` + --> $DIR/gated.rs:4:1 | LL | #![deny(must_not_suspend)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = note: the `must_not_suspend` lint is unstable = note: see issue #83310 for more information = help: add `#![feature(must_not_suspend)]` to the crate attributes to enable -error: `MutexGuard` held across a suspend point, but should not be - --> $DIR/gated.rs:9:9 - | -LL | let _guard = m.lock().unwrap(); - | ^^^^^^ -LL | other().await; - | ------ the value is held across this suspend point - | -note: the lint level is defined here - --> $DIR/gated.rs:2:9 - | -LL | #![deny(must_not_suspend)] - | ^^^^^^^^^^^^^^^^ -note: holding a MutexGuard across suspend points can cause deadlocks, delays, and cause Futures to not implement `Send` - --> $DIR/gated.rs:9:9 - | -LL | let _guard = m.lock().unwrap(); - | ^^^^^^ -help: consider using a block (`{ ... }`) to shrink the value's scope, ending before the suspend point - --> $DIR/gated.rs:9:9 - | -LL | let _guard = m.lock().unwrap(); - | ^^^^^^ - -error: aborting due to 4 previous errors +warning: 3 warnings emitted -For more information about this error, try `rustc --explain E0658`. diff --git a/src/test/ui/unknown-unstable-lints/deny-unstable-lint-command-line.rs b/src/test/ui/unknown-unstable-lints/deny-unstable-lint-command-line.rs new file mode 100644 index 0000000000000..dcc06850de174 --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/deny-unstable-lint-command-line.rs @@ -0,0 +1,6 @@ +// check-fail +// compile-flags: -Dunknown_lints -Atest_unstable_lint +// error-pattern: unknown lint: `test_unstable_lint` +// error-pattern: the `test_unstable_lint` lint is unstable + +fn main() {} diff --git a/src/test/ui/unknown-unstable-lints/deny-unstable-lint-command-line.stderr b/src/test/ui/unknown-unstable-lints/deny-unstable-lint-command-line.stderr new file mode 100644 index 0000000000000..c840849a27d9d --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/deny-unstable-lint-command-line.stderr @@ -0,0 +1,18 @@ +error: unknown lint: `test_unstable_lint` + | + = note: `-D test-unstable-lint` implied by `-D unknown-lints` + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +error: unknown lint: `test_unstable_lint` + | + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +error: unknown lint: `test_unstable_lint` + | + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +error: aborting due to 3 previous errors + diff --git a/src/test/ui/unknown-unstable-lints/deny-unstable-lint-inline.rs b/src/test/ui/unknown-unstable-lints/deny-unstable-lint-inline.rs new file mode 100644 index 0000000000000..c6c60b12d83e9 --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/deny-unstable-lint-inline.rs @@ -0,0 +1,9 @@ +// check-fail + +#![deny(unknown_lints)] +#![allow(test_unstable_lint)] +//~^ ERROR unknown lint: `test_unstable_lint` +//~| ERROR unknown lint: `test_unstable_lint` +//~| ERROR unknown lint: `test_unstable_lint` + +fn main() {} diff --git a/src/test/ui/unknown-unstable-lints/deny-unstable-lint-inline.stderr b/src/test/ui/unknown-unstable-lints/deny-unstable-lint-inline.stderr new file mode 100644 index 0000000000000..6e909f9902c4f --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/deny-unstable-lint-inline.stderr @@ -0,0 +1,35 @@ +error: unknown lint: `test_unstable_lint` + --> $DIR/deny-unstable-lint-inline.rs:4:1 + | +LL | #![allow(test_unstable_lint)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: the lint level is defined here + --> $DIR/deny-unstable-lint-inline.rs:3:9 + | +LL | #![deny(unknown_lints)] + | ^^^^^^^^^^^^^ + = note: `#[deny(test_unstable_lint)]` implied by `#[deny(unknown_lints)]` + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +error: unknown lint: `test_unstable_lint` + --> $DIR/deny-unstable-lint-inline.rs:4:1 + | +LL | #![allow(test_unstable_lint)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +error: unknown lint: `test_unstable_lint` + --> $DIR/deny-unstable-lint-inline.rs:4:1 + | +LL | #![allow(test_unstable_lint)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +error: aborting due to 3 previous errors + diff --git a/src/test/ui/unknown-unstable-lints/unstable-lint-command-line.rs b/src/test/ui/unknown-unstable-lints/unstable-lint-command-line.rs deleted file mode 100644 index 7663abffd9b48..0000000000000 --- a/src/test/ui/unknown-unstable-lints/unstable-lint-command-line.rs +++ /dev/null @@ -1,5 +0,0 @@ -// check-fail -// compile-flags: -Atest_unstable_lint -// error-pattern: the `test_unstable_lint` lint is unstable - -fn main() {} diff --git a/src/test/ui/unknown-unstable-lints/unstable-lint-command-line.stderr b/src/test/ui/unknown-unstable-lints/unstable-lint-command-line.stderr deleted file mode 100644 index d088f4c8fe5aa..0000000000000 --- a/src/test/ui/unknown-unstable-lints/unstable-lint-command-line.stderr +++ /dev/null @@ -1,11 +0,0 @@ -error[E0658]: the `test_unstable_lint` lint is unstable - | - = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable - -error[E0658]: the `test_unstable_lint` lint is unstable - | - = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0658`. diff --git a/src/test/ui/unknown-unstable-lints/unstable-lint-inline.rs b/src/test/ui/unknown-unstable-lints/unstable-lint-inline.rs deleted file mode 100644 index 43789906ed6f0..0000000000000 --- a/src/test/ui/unknown-unstable-lints/unstable-lint-inline.rs +++ /dev/null @@ -1,6 +0,0 @@ -// check-fail -// error-pattern: the `test_unstable_lint` lint is unstable - -#![allow(test_unstable_lint)] - -fn main() {} diff --git a/src/test/ui/unknown-unstable-lints/unstable-lint-inline.stderr b/src/test/ui/unknown-unstable-lints/unstable-lint-inline.stderr deleted file mode 100644 index 5ec85f346fec5..0000000000000 --- a/src/test/ui/unknown-unstable-lints/unstable-lint-inline.stderr +++ /dev/null @@ -1,19 +0,0 @@ -error[E0658]: the `test_unstable_lint` lint is unstable - --> $DIR/unstable-lint-inline.rs:4:1 - | -LL | #![allow(test_unstable_lint)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable - -error[E0658]: the `test_unstable_lint` lint is unstable - --> $DIR/unstable-lint-inline.rs:4:1 - | -LL | #![allow(test_unstable_lint)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0658`. diff --git a/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-command-line.rs b/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-command-line.rs new file mode 100644 index 0000000000000..3778291ebb447 --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-command-line.rs @@ -0,0 +1,6 @@ +// check-pass +// compile-flags: -Wunknown_lints -Atest_unstable_lint +// error-pattern: unknown lint: `test_unstable_lint` +// error-pattern: the `test_unstable_lint` lint is unstable + +fn main() {} diff --git a/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-command-line.stderr b/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-command-line.stderr new file mode 100644 index 0000000000000..a45bed843c71d --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-command-line.stderr @@ -0,0 +1,18 @@ +warning: unknown lint: `test_unstable_lint` + | + = note: `-W test-unstable-lint` implied by `-W unknown-lints` + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +warning: unknown lint: `test_unstable_lint` + | + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +warning: unknown lint: `test_unstable_lint` + | + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +warning: 3 warnings emitted + diff --git a/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-inline.rs b/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-inline.rs new file mode 100644 index 0000000000000..f4247e4569eb7 --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-inline.rs @@ -0,0 +1,9 @@ +// check-pass + +#![warn(unknown_lints)] +#![allow(test_unstable_lint)] +//~^ WARNING unknown lint: `test_unstable_lint` +//~| WARNING unknown lint: `test_unstable_lint` +//~| WARNING unknown lint: `test_unstable_lint` + +fn main() {} diff --git a/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-inline.stderr b/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-inline.stderr new file mode 100644 index 0000000000000..ce6bd0f3ef994 --- /dev/null +++ b/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-inline.stderr @@ -0,0 +1,35 @@ +warning: unknown lint: `test_unstable_lint` + --> $DIR/warn-unknown-unstable-lint-inline.rs:4:1 + | +LL | #![allow(test_unstable_lint)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: the lint level is defined here + --> $DIR/warn-unknown-unstable-lint-inline.rs:3:9 + | +LL | #![warn(unknown_lints)] + | ^^^^^^^^^^^^^ + = note: `#[warn(test_unstable_lint)]` implied by `#[warn(unknown_lints)]` + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +warning: unknown lint: `test_unstable_lint` + --> $DIR/warn-unknown-unstable-lint-inline.rs:4:1 + | +LL | #![allow(test_unstable_lint)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +warning: unknown lint: `test_unstable_lint` + --> $DIR/warn-unknown-unstable-lint-inline.rs:4:1 + | +LL | #![allow(test_unstable_lint)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: the `test_unstable_lint` lint is unstable + = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable + +warning: 3 warnings emitted + From 1593ce8609714f4717a9db964507bf4fdf1e400d Mon Sep 17 00:00:00 2001 From: David Koloski Date: Mon, 28 Feb 2022 22:28:45 +0000 Subject: [PATCH 05/11] Fill out documentation for new lint --- compiler/rustc_lint_defs/src/builtin.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index f6ad46cc01888..7f1591a72120b 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -3774,8 +3774,21 @@ declare_lint! { } declare_lint! { - #[doc(hidden)] - /// Added for testing unsable lints; perma-unstable. + /// The `test_unstable_lint` lint tests unstable lints and is perma-unstable. + /// + /// ### Example + /// + /// ``` + /// #![allow(test_unstable_lint)] + /// ``` + /// + /// {{produces}} + /// + /// ### Explanation + /// + /// In order to test the behavior of unstable traits, a permanently-unstable + /// lint is required. This lint can be used to trigger warnings and errors + /// from the compiler related to unstable lints. pub TEST_UNSTABLE_LINT, Deny, "this unstable lint is only for testing", From fa10d90b9974844790b0ad98fa5c50fae80ee166 Mon Sep 17 00:00:00 2001 From: David Koloski Date: Wed, 2 Mar 2022 00:10:39 +0000 Subject: [PATCH 06/11] Fix docs, fix incorrect lint source in note --- compiler/rustc_lint/src/levels.rs | 5 +++-- compiler/rustc_lint_defs/src/builtin.rs | 2 +- .../feature-gate-non_exhaustive_omitted_patterns_lint.stderr | 2 +- .../ui/feature-gates/feature-gate-test_unstable_lint.stderr | 2 +- src/test/ui/lint/must_not_suspend/gated.stderr | 2 +- .../deny-unstable-lint-command-line.stderr | 2 +- .../unknown-unstable-lints/deny-unstable-lint-inline.stderr | 1 - .../warn-unknown-unstable-lint-command-line.stderr | 2 +- .../warn-unknown-unstable-lint-inline.stderr | 1 - 9 files changed, 9 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 2b28fc2c0115e..7b018e7f75fa7 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -601,10 +601,11 @@ impl<'s> LintLevelsBuilder<'s> { fn check_gated_lint(&self, lint_id: LintId, span: Span) -> bool { if let Some(feature) = lint_id.lint.feature_gate { if !self.sess.features_untracked().enabled(feature) { + let lint = builtin::UNKNOWN_LINTS; let (level, src) = self.lint_level(builtin::UNKNOWN_LINTS); - struct_lint_level(self.sess, lint_id.lint, level, src, Some(span.into()), |lint| { + struct_lint_level(self.sess, lint, level, src, Some(span.into()), |lint_db| { let mut db = - lint.build(&format!("unknown lint: `{}`", lint_id.lint.name_lower())); + lint_db.build(&format!("unknown lint: `{}`", lint_id.lint.name_lower())); db.note(&format!("the `{}` lint is unstable", lint_id.lint.name_lower(),)); add_feature_diagnostics(&mut db, &self.sess.parse_sess, feature); db.emit(); diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 7f1591a72120b..62eba796eae54 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -3786,7 +3786,7 @@ declare_lint! { /// /// ### Explanation /// - /// In order to test the behavior of unstable traits, a permanently-unstable + /// In order to test the behavior of unstable lints, a permanently-unstable /// lint is required. This lint can be used to trigger warnings and errors /// from the compiler related to unstable lints. pub TEST_UNSTABLE_LINT, diff --git a/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr b/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr index 94568c96b40a3..7f82fbdea4eba 100644 --- a/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr +++ b/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr @@ -4,7 +4,7 @@ warning: unknown lint: `non_exhaustive_omitted_patterns` LL | #![deny(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: `#[warn(non_exhaustive_omitted_patterns)]` on by default + = note: `#[warn(unknown_lints)]` on by default = note: the `non_exhaustive_omitted_patterns` lint is unstable = note: see issue #89554 for more information = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable diff --git a/src/test/ui/feature-gates/feature-gate-test_unstable_lint.stderr b/src/test/ui/feature-gates/feature-gate-test_unstable_lint.stderr index eab89f02018bf..a29322443ea98 100644 --- a/src/test/ui/feature-gates/feature-gate-test_unstable_lint.stderr +++ b/src/test/ui/feature-gates/feature-gate-test_unstable_lint.stderr @@ -4,7 +4,7 @@ warning: unknown lint: `test_unstable_lint` LL | #![allow(test_unstable_lint)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: `#[warn(test_unstable_lint)]` on by default + = note: `#[warn(unknown_lints)]` on by default = note: the `test_unstable_lint` lint is unstable = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable diff --git a/src/test/ui/lint/must_not_suspend/gated.stderr b/src/test/ui/lint/must_not_suspend/gated.stderr index 3d6877045ff78..b58ecb55596ab 100644 --- a/src/test/ui/lint/must_not_suspend/gated.stderr +++ b/src/test/ui/lint/must_not_suspend/gated.stderr @@ -4,7 +4,7 @@ warning: unknown lint: `must_not_suspend` LL | #![deny(must_not_suspend)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: `#[warn(must_not_suspend)]` on by default + = note: `#[warn(unknown_lints)]` on by default = note: the `must_not_suspend` lint is unstable = note: see issue #83310 for more information = help: add `#![feature(must_not_suspend)]` to the crate attributes to enable diff --git a/src/test/ui/unknown-unstable-lints/deny-unstable-lint-command-line.stderr b/src/test/ui/unknown-unstable-lints/deny-unstable-lint-command-line.stderr index c840849a27d9d..7e6885bd70646 100644 --- a/src/test/ui/unknown-unstable-lints/deny-unstable-lint-command-line.stderr +++ b/src/test/ui/unknown-unstable-lints/deny-unstable-lint-command-line.stderr @@ -1,6 +1,6 @@ error: unknown lint: `test_unstable_lint` | - = note: `-D test-unstable-lint` implied by `-D unknown-lints` + = note: requested on the command line with `-D unknown-lints` = note: the `test_unstable_lint` lint is unstable = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable diff --git a/src/test/ui/unknown-unstable-lints/deny-unstable-lint-inline.stderr b/src/test/ui/unknown-unstable-lints/deny-unstable-lint-inline.stderr index 6e909f9902c4f..2d1027dd0e05f 100644 --- a/src/test/ui/unknown-unstable-lints/deny-unstable-lint-inline.stderr +++ b/src/test/ui/unknown-unstable-lints/deny-unstable-lint-inline.stderr @@ -9,7 +9,6 @@ note: the lint level is defined here | LL | #![deny(unknown_lints)] | ^^^^^^^^^^^^^ - = note: `#[deny(test_unstable_lint)]` implied by `#[deny(unknown_lints)]` = note: the `test_unstable_lint` lint is unstable = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable diff --git a/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-command-line.stderr b/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-command-line.stderr index a45bed843c71d..799d740b00ef2 100644 --- a/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-command-line.stderr +++ b/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-command-line.stderr @@ -1,6 +1,6 @@ warning: unknown lint: `test_unstable_lint` | - = note: `-W test-unstable-lint` implied by `-W unknown-lints` + = note: requested on the command line with `-W unknown-lints` = note: the `test_unstable_lint` lint is unstable = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable diff --git a/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-inline.stderr b/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-inline.stderr index ce6bd0f3ef994..142558b471b48 100644 --- a/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-inline.stderr +++ b/src/test/ui/unknown-unstable-lints/warn-unknown-unstable-lint-inline.stderr @@ -9,7 +9,6 @@ note: the lint level is defined here | LL | #![warn(unknown_lints)] | ^^^^^^^^^^^^^ - = note: `#[warn(test_unstable_lint)]` implied by `#[warn(unknown_lints)]` = note: the `test_unstable_lint` lint is unstable = help: add `#![feature(test_unstable_lint)]` to the crate attributes to enable From 1c31a95df7de66dc7842b43facf185ef8a776e6f Mon Sep 17 00:00:00 2001 From: David Koloski Date: Tue, 8 Mar 2022 19:57:03 +0000 Subject: [PATCH 07/11] Update for changes to other lints --- ...on_exhaustive_omitted_patterns_lint.stderr | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr b/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr index 7f82fbdea4eba..dbeef6c2d2ae2 100644 --- a/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr +++ b/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr @@ -102,17 +102,22 @@ LL | #[warn(non_exhaustive_omitted_patterns)] error[E0004]: non-exhaustive patterns: `C` not covered --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:20:11 | -LL | / enum Foo { -LL | | A, B, C, - | | - not covered -LL | | } - | |_____- `Foo` defined here -... -LL | match Foo::A { - | ^^^^^^ pattern `C` not covered - | - = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms +LL | match Foo::A { + | ^^^^^^ pattern `C` not covered + | +note: `Foo` defined here + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:12:15 + | +LL | enum Foo { + | --- +LL | A, B, C, + | ^ not covered = note: the matched value is of type `Foo` +help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown + | +LL ~ Foo::B => {} +LL + C => todo!() + | error: aborting due to previous error; 10 warnings emitted From 8073a88f35728289ef535cca5cf13302faba5972 Mon Sep 17 00:00:00 2001 From: Caio Date: Wed, 9 Mar 2022 16:46:23 -0300 Subject: [PATCH 08/11] Implement macro meta-variable expressions --- compiler/rustc_ast/src/util/literal.rs | 2 +- compiler/rustc_expand/src/lib.rs | 1 + compiler/rustc_expand/src/mbe.rs | 16 +- compiler/rustc_expand/src/mbe/macro_check.rs | 4 + compiler/rustc_expand/src/mbe/macro_parser.rs | 13 +- compiler/rustc_expand/src/mbe/macro_rules.rs | 20 +- compiler/rustc_expand/src/mbe/metavar_expr.rs | 157 ++++++++ compiler/rustc_expand/src/mbe/quoted.rs | 123 ++++-- compiler/rustc_expand/src/mbe/transcribe.rs | 27 ++ compiler/rustc_feature/src/active.rs | 2 + compiler/rustc_span/src/symbol.rs | 1 + .../dollar-dollar-has-correct-behavior.rs | 28 ++ .../feature-gate-macro_metavar_expr.rs | 14 + .../rfc-3086-metavar-expr/required-feature.rs | 9 + .../required-feature.stderr | 12 + .../rfc-3086-metavar-expr/syntax-errors.rs | 148 +++++++ .../syntax-errors.stderr | 367 ++++++++++++++++++ 17 files changed, 900 insertions(+), 44 deletions(-) create mode 100644 compiler/rustc_expand/src/mbe/metavar_expr.rs create mode 100644 src/test/ui/macros/rfc-3086-metavar-expr/dollar-dollar-has-correct-behavior.rs create mode 100644 src/test/ui/macros/rfc-3086-metavar-expr/feature-gate-macro_metavar_expr.rs create mode 100644 src/test/ui/macros/rfc-3086-metavar-expr/required-feature.rs create mode 100644 src/test/ui/macros/rfc-3086-metavar-expr/required-feature.stderr create mode 100644 src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs create mode 100644 src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr diff --git a/compiler/rustc_ast/src/util/literal.rs b/compiler/rustc_ast/src/util/literal.rs index 231dd72af2c7d..9c18f55c03b4d 100644 --- a/compiler/rustc_ast/src/util/literal.rs +++ b/compiler/rustc_ast/src/util/literal.rs @@ -23,7 +23,7 @@ pub enum LitError { impl LitKind { /// Converts literal token into a semantic literal. - fn from_lit_token(lit: token::Lit) -> Result { + pub fn from_lit_token(lit: token::Lit) -> Result { let token::Lit { kind, symbol, suffix } = lit; if suffix.is_some() && !kind.may_have_suffix() { return Err(LitError::InvalidSuffix); diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs index b024524aa2968..8a9efe01368e3 100644 --- a/compiler/rustc_expand/src/lib.rs +++ b/compiler/rustc_expand/src/lib.rs @@ -3,6 +3,7 @@ #![feature(crate_visibility_modifier)] #![feature(decl_macro)] #![feature(if_let_guard)] +#![feature(let_chains)] #![feature(let_else)] #![feature(proc_macro_diagnostic)] #![feature(proc_macro_internals)] diff --git a/compiler/rustc_expand/src/mbe.rs b/compiler/rustc_expand/src/mbe.rs index 5244ac36bba5d..3d4c77aba7339 100644 --- a/compiler/rustc_expand/src/mbe.rs +++ b/compiler/rustc_expand/src/mbe.rs @@ -6,17 +6,17 @@ crate mod macro_check; crate mod macro_parser; crate mod macro_rules; +crate mod metavar_expr; crate mod quoted; crate mod transcribe; +use metavar_expr::MetaVarExpr; use rustc_ast::token::{self, NonterminalKind, Token, TokenKind}; use rustc_ast::tokenstream::DelimSpan; - +use rustc_data_structures::sync::Lrc; use rustc_span::symbol::Ident; use rustc_span::Span; -use rustc_data_structures::sync::Lrc; - /// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note /// that the delimiter itself might be `NoDelim`. #[derive(Clone, PartialEq, Encodable, Decodable, Debug)] @@ -73,8 +73,8 @@ enum KleeneOp { ZeroOrOne, } -/// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)` -/// are "first-class" token trees. Useful for parsing macros. +/// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, `$(...)`, +/// and `${...}` are "first-class" token trees. Useful for parsing macros. #[derive(Debug, Clone, PartialEq, Encodable, Decodable)] enum TokenTree { Token(Token), @@ -85,6 +85,8 @@ enum TokenTree { MetaVar(Span, Ident), /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros. MetaVarDecl(Span, Ident /* name to bind */, Option), + /// A meta-variable expression inside `${...}` + MetaVarExpr(DelimSpan, MetaVarExpr), } impl TokenTree { @@ -139,7 +141,9 @@ impl TokenTree { TokenTree::Token(Token { span, .. }) | TokenTree::MetaVar(span, _) | TokenTree::MetaVarDecl(span, _, _) => span, - TokenTree::Delimited(span, _) | TokenTree::Sequence(span, _) => span.entire(), + TokenTree::Delimited(span, _) + | TokenTree::MetaVarExpr(span, _) + | TokenTree::Sequence(span, _) => span.entire(), } } diff --git a/compiler/rustc_expand/src/mbe/macro_check.rs b/compiler/rustc_expand/src/mbe/macro_check.rs index 3497e5ad543a1..88e1169322093 100644 --- a/compiler/rustc_expand/src/mbe/macro_check.rs +++ b/compiler/rustc_expand/src/mbe/macro_check.rs @@ -278,6 +278,8 @@ fn check_binders( binders.insert(name, BinderInfo { span, ops: ops.into() }); } } + // `MetaVarExpr` can not appear in the LHS of a macro arm + TokenTree::MetaVarExpr(..) => {} TokenTree::Delimited(_, ref del) => { for tt in &del.tts { check_binders(sess, node_id, tt, macros, binders, ops, valid); @@ -335,6 +337,8 @@ fn check_occurrences( let name = MacroRulesNormalizedIdent::new(name); check_ops_is_prefix(sess, node_id, macros, binders, ops, span, name); } + // FIXME(c410-f3r) Check token (https://github.com/rust-lang/rust/issues/93902) + TokenTree::MetaVarExpr(..) => {} TokenTree::Delimited(_, ref del) => { check_nested_occurrences(sess, node_id, &del.tts, macros, binders, ops, valid); } diff --git a/compiler/rustc_expand/src/mbe/macro_parser.rs b/compiler/rustc_expand/src/mbe/macro_parser.rs index bb36dfd793d4a..04137086088dd 100644 --- a/compiler/rustc_expand/src/mbe/macro_parser.rs +++ b/compiler/rustc_expand/src/mbe/macro_parser.rs @@ -200,7 +200,7 @@ struct MatcherPos<'root, 'tt> { // This type is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] -rustc_data_structures::static_assert_size!(MatcherPos<'_, '_>, 192); +rustc_data_structures::static_assert_size!(MatcherPos<'_, '_>, 240); impl<'root, 'tt> MatcherPos<'root, 'tt> { /// Generates the top-level matcher position in which the "dot" is before the first token of @@ -321,10 +321,13 @@ pub(super) fn count_names(ms: &[TokenTree]) -> usize { ms.iter().fold(0, |count, elt| { count + match *elt { - TokenTree::Sequence(_, ref seq) => seq.num_captures, TokenTree::Delimited(_, ref delim) => count_names(&delim.tts), TokenTree::MetaVar(..) => 0, TokenTree::MetaVarDecl(..) => 1, + // FIXME(c410-f3r) MetaVarExpr should be handled instead of being ignored + // https://github.com/rust-lang/rust/issues/9390 + TokenTree::MetaVarExpr(..) => 0, + TokenTree::Sequence(_, ref seq) => seq.num_captures, TokenTree::Token(..) => 0, } }) @@ -436,7 +439,9 @@ fn nameize>( } Occupied(..) => return Err((sp, format!("duplicated bind name: {}", bind_name))), }, - TokenTree::MetaVar(..) | TokenTree::Token(..) => (), + // FIXME(c410-f3r) MetaVar and MetaVarExpr should be handled instead of being ignored + // https://github.com/rust-lang/rust/issues/9390 + TokenTree::MetaVar(..) | TokenTree::MetaVarExpr(..) | TokenTree::Token(..) => {} } Ok(()) @@ -650,7 +655,7 @@ fn inner_parse_loop<'root, 'tt>( // rules. NOTE that this is not necessarily an error unless _all_ items in // `cur_items` end up doing this. There may still be some other matchers that do // end up working out. - TokenTree::Token(..) | TokenTree::MetaVar(..) => {} + TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarExpr(..) => {} } } } diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 62ea3aa76a46c..c3b1b34aa29b9 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -580,7 +580,10 @@ fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[mbe::TokenTree]) -> bool { use mbe::TokenTree; for tt in tts { match *tt { - TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (), + TokenTree::Token(..) + | TokenTree::MetaVar(..) + | TokenTree::MetaVarDecl(..) + | TokenTree::MetaVarExpr(..) => (), TokenTree::Delimited(_, ref del) => { if !check_lhs_no_empty_seq(sess, &del.tts) { return false; @@ -669,7 +672,10 @@ impl FirstSets { let mut first = TokenSet::empty(); for tt in tts.iter().rev() { match *tt { - TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => { + TokenTree::Token(..) + | TokenTree::MetaVar(..) + | TokenTree::MetaVarDecl(..) + | TokenTree::MetaVarExpr(..) => { first.replace_with(tt.clone()); } TokenTree::Delimited(span, ref delimited) => { @@ -731,7 +737,10 @@ impl FirstSets { for tt in tts.iter() { assert!(first.maybe_empty); match *tt { - TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => { + TokenTree::Token(..) + | TokenTree::MetaVar(..) + | TokenTree::MetaVarDecl(..) + | TokenTree::MetaVarExpr(..) => { first.add_one(tt.clone()); return first; } @@ -907,7 +916,10 @@ fn check_matcher_core( // First, update `last` so that it corresponds to the set // of NT tokens that might end the sequence `... token`. match *token { - TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => { + TokenTree::Token(..) + | TokenTree::MetaVar(..) + | TokenTree::MetaVarDecl(..) + | TokenTree::MetaVarExpr(..) => { if token_can_be_followed_by_any(token) { // don't need to track tokens that work with any, last.replace_with_irrelevant(); diff --git a/compiler/rustc_expand/src/mbe/metavar_expr.rs b/compiler/rustc_expand/src/mbe/metavar_expr.rs new file mode 100644 index 0000000000000..6c5a755da6f40 --- /dev/null +++ b/compiler/rustc_expand/src/mbe/metavar_expr.rs @@ -0,0 +1,157 @@ +use rustc_ast::token; +use rustc_ast::tokenstream::{Cursor, TokenStream, TokenTree}; +use rustc_ast::{LitIntType, LitKind}; +use rustc_ast_pretty::pprust; +use rustc_errors::{Applicability, PResult}; +use rustc_session::parse::ParseSess; +use rustc_span::symbol::Ident; +use rustc_span::Span; + +/// A meta-variable expression, for expansions based on properties of meta-variables. +#[derive(Debug, Clone, PartialEq, Encodable, Decodable)] +crate enum MetaVarExpr { + /// The number of repetitions of an identifier, optionally limited to a number + /// of outer-most repetition depths. If the depth limit is `None` then the depth is unlimited. + Count(Ident, Option), + + /// Ignore a meta-variable for repetition without expansion. + Ignore(Ident), + + /// The index of the repetition at a particular depth, where 0 is the inner-most + /// repetition. The `usize` is the depth. + Index(usize), + + /// The length of the repetition at a particular depth, where 0 is the inner-most + /// repetition. The `usize` is the depth. + Length(usize), +} + +impl MetaVarExpr { + /// Attempt to parse a meta-variable expression from a token stream. + crate fn parse<'sess>( + input: &TokenStream, + outer_span: Span, + sess: &'sess ParseSess, + ) -> PResult<'sess, MetaVarExpr> { + let mut tts = input.trees(); + let ident = parse_ident(&mut tts, sess, outer_span)?; + let Some(TokenTree::Delimited(_, token::Paren, args)) = tts.next() else { + let msg = "meta-variable expression parameter must be wrapped in parentheses"; + return Err(sess.span_diagnostic.struct_span_err(ident.span, msg)); + }; + check_trailing_token(&mut tts, sess)?; + let mut iter = args.trees(); + let rslt = match &*ident.as_str() { + "count" => parse_count(&mut iter, sess, ident.span)?, + "ignore" => MetaVarExpr::Ignore(parse_ident(&mut iter, sess, ident.span)?), + "index" => MetaVarExpr::Index(parse_depth(&mut iter, sess, ident.span)?), + "length" => MetaVarExpr::Length(parse_depth(&mut iter, sess, ident.span)?), + _ => { + let err_msg = "unrecognized meta-variable expression"; + let mut err = sess.span_diagnostic.struct_span_err(ident.span, err_msg); + err.span_suggestion( + ident.span, + "supported expressions are count, ignore, index and length", + String::new(), + Applicability::MachineApplicable, + ); + return Err(err); + } + }; + check_trailing_token(&mut iter, sess)?; + Ok(rslt) + } + + crate fn ident(&self) -> Option<&Ident> { + match self { + MetaVarExpr::Count(ident, _) | MetaVarExpr::Ignore(ident) => Some(&ident), + MetaVarExpr::Index(..) | MetaVarExpr::Length(..) => None, + } + } +} + +// Checks if there are any remaining tokens. For example, `${ignore(ident ... a b c ...)}` +fn check_trailing_token<'sess>(iter: &mut Cursor, sess: &'sess ParseSess) -> PResult<'sess, ()> { + if let Some(tt) = iter.next() { + let mut diag = sess.span_diagnostic.struct_span_err( + tt.span(), + &format!("unexpected token: {}", pprust::tt_to_string(&tt)), + ); + diag.span_note(tt.span(), "meta-variable expression must not have trailing tokens"); + Err(diag) + } else { + Ok(()) + } +} + +/// Parse a meta-variable `count` expression: `count(ident[, depth])` +fn parse_count<'sess>( + iter: &mut Cursor, + sess: &'sess ParseSess, + span: Span, +) -> PResult<'sess, MetaVarExpr> { + let ident = parse_ident(iter, sess, span)?; + let depth = if try_eat_comma(iter) { Some(parse_depth(iter, sess, span)?) } else { None }; + Ok(MetaVarExpr::Count(ident, depth)) +} + +/// Parses the depth used by index(depth) and length(depth). +fn parse_depth<'sess>( + iter: &mut Cursor, + sess: &'sess ParseSess, + span: Span, +) -> PResult<'sess, usize> { + let Some(tt) = iter.next() else { return Ok(0) }; + let TokenTree::Token(token::Token { + kind: token::TokenKind::Literal(lit), .. + }) = tt else { + return Err(sess.span_diagnostic.struct_span_err( + span, + "meta-variable expression depth must be a literal" + )); + }; + if let Ok(lit_kind) = LitKind::from_lit_token(lit) + && let LitKind::Int(n_u128, LitIntType::Unsuffixed) = lit_kind + && let Ok(n_usize) = usize::try_from(n_u128) + { + Ok(n_usize) + } + else { + let msg = "only unsuffixes integer literals are supported in meta-variable expressions"; + Err(sess.span_diagnostic.struct_span_err(span, msg)) + } +} + +/// Parses an generic ident +fn parse_ident<'sess>( + iter: &mut Cursor, + sess: &'sess ParseSess, + span: Span, +) -> PResult<'sess, Ident> { + let err_fn = |msg| sess.span_diagnostic.struct_span_err(span, msg); + if let Some(tt) = iter.next() && let TokenTree::Token(token) = tt { + if let Some((elem, false)) = token.ident() { + return Ok(elem); + } + let token_str = pprust::token_to_string(&token); + let mut err = err_fn(&format!("expected identifier, found `{}`", &token_str)); + err.span_suggestion( + token.span, + &format!("try removing `{}`", &token_str), + String::new(), + Applicability::MaybeIncorrect, + ); + return Err(err); + } + Err(err_fn("expected identifier")) +} + +/// Tries to move the iterator forward returning `true` if there is a comma. If not, then the +/// iterator is not modified and the result is `false`. +fn try_eat_comma(iter: &mut Cursor) -> bool { + if let Some(TokenTree::Token(token::Token { kind: token::Comma, .. })) = iter.look_ahead(0) { + let _ = iter.next(); + return true; + } + false +} diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index dedc6c618b9a4..12c5dac9e0bf4 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -1,13 +1,13 @@ use crate::mbe::macro_parser; -use crate::mbe::{Delimited, KleeneOp, KleeneToken, SequenceRepetition, TokenTree}; +use crate::mbe::{Delimited, KleeneOp, KleeneToken, MetaVarExpr, SequenceRepetition, TokenTree}; use rustc_ast::token::{self, Token}; use rustc_ast::tokenstream; use rustc_ast::{NodeId, DUMMY_NODE_ID}; use rustc_ast_pretty::pprust; use rustc_feature::Features; -use rustc_session::parse::ParseSess; -use rustc_span::symbol::{kw, Ident}; +use rustc_session::parse::{feature_err, ParseSess}; +use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::edition::Edition; use rustc_span::{Span, SyntaxContext}; @@ -25,22 +25,22 @@ const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \ /// # Parameters /// /// - `input`: a token stream to read from, the contents of which we are parsing. -/// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a -/// macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with -/// their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and -/// `ident` are "matchers". They are not present in the body of a macro rule -- just in the -/// pattern, so we pass a parameter to indicate whether to expect them or not. +/// - `parsing_patterns`: `parse` can be used to parse either the "patterns" or the "body" of a +/// macro. Both take roughly the same form _except_ that: +/// - In a pattern, metavars are declared with their "matcher" type. For example `$var:expr` or +/// `$id:ident`. In this example, `expr` and `ident` are "matchers". They are not present in the +/// body of a macro rule -- just in the pattern. +/// - Metavariable expressions are only valid in the "body", not the "pattern". /// - `sess`: the parsing session. Any errors will be emitted to this session. /// - `node_id`: the NodeId of the macro we are parsing. /// - `features`: language features so we can do feature gating. -/// - `edition`: the edition of the crate defining the macro /// /// # Returns /// /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`. pub(super) fn parse( input: tokenstream::TokenStream, - expect_matchers: bool, + parsing_patterns: bool, sess: &ParseSess, node_id: NodeId, features: &Features, @@ -55,9 +55,9 @@ pub(super) fn parse( while let Some(tree) = trees.next() { // Given the parsed tree, if there is a metavar and we are expecting matchers, actually // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`). - let tree = parse_tree(tree, &mut trees, expect_matchers, sess, node_id, features, edition); + let tree = parse_tree(tree, &mut trees, parsing_patterns, sess, node_id, features, edition); match tree { - TokenTree::MetaVar(start_sp, ident) if expect_matchers => { + TokenTree::MetaVar(start_sp, ident) if parsing_patterns => { let span = match trees.next() { Some(tokenstream::TokenTree::Token(Token { kind: token::Colon, span })) => { match trees.next() { @@ -118,6 +118,14 @@ pub(super) fn parse( result } +/// Asks for the `macro_metavar_expr` feature if it is not already declared +fn maybe_emit_macro_metavar_expr_feature(features: &Features, sess: &ParseSess, span: Span) { + if !features.macro_metavar_expr { + let msg = "meta-variable expressions are unstable"; + feature_err(&sess, sym::macro_metavar_expr, span, msg).emit(); + } +} + /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree` /// for use in parsing a macro. @@ -129,14 +137,13 @@ pub(super) fn parse( /// - `tree`: the tree we wish to convert. /// - `outer_trees`: an iterator over trees. We may need to read more tokens from it in order to finish /// converting `tree` -/// - `expect_matchers`: same as for `parse` (see above). +/// - `parsing_patterns`: same as [parse]. /// - `sess`: the parsing session. Any errors will be emitted to this session. /// - `features`: language features so we can do feature gating. -/// - `edition` - the edition of the crate defining the macro fn parse_tree( tree: tokenstream::TokenTree, outer_trees: &mut impl Iterator, - expect_matchers: bool, + parsing_patterns: bool, sess: &ParseSess, node_id: NodeId, features: &Features, @@ -158,24 +165,57 @@ fn parse_tree( } match next { - // `tree` is followed by a delimited set of token trees. This indicates the beginning - // of a repetition sequence in the macro (e.g. `$(pat)*`). - Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => { - // Must have `(` not `{` or `[` - if delim != token::Paren { - let tok = pprust::token_kind_to_string(&token::OpenDelim(delim)); - let msg = format!("expected `(`, found `{}`", tok); - sess.span_diagnostic.span_err(span.entire(), &msg); + // `tree` is followed by a delimited set of token trees. + Some(tokenstream::TokenTree::Delimited(delim_span, delim, tts)) => { + if parsing_patterns { + if delim != token::Paren { + span_dollar_dollar_or_metavar_in_the_lhs_err( + sess, + &Token { kind: token::OpenDelim(delim), span: delim_span.entire() }, + ); + } + } else { + match delim { + token::Brace => { + // The delimiter is `{`. This indicates the beginning + // of a meta-variable expression (e.g. `${count(ident)}`). + // Try to parse the meta-variable expression. + match MetaVarExpr::parse(&tts, delim_span.entire(), sess) { + Err(mut err) => { + err.emit(); + // Returns early the same read `$` to avoid spanning + // unrelated diagnostics that could be performed afterwards + return TokenTree::token(token::Dollar, span); + } + Ok(elem) => { + maybe_emit_macro_metavar_expr_feature( + features, + sess, + delim_span.entire(), + ); + return TokenTree::MetaVarExpr(delim_span, elem); + } + } + } + token::Paren => {} + _ => { + let tok = pprust::token_kind_to_string(&token::OpenDelim(delim)); + let msg = format!("expected `(` or `{{`, found `{}`", tok); + sess.span_diagnostic.span_err(delim_span.entire(), &msg); + } + } } - // Parse the contents of the sequence itself - let sequence = parse(tts, expect_matchers, sess, node_id, features, edition); + // If we didn't find a metavar expression above, then we must have a + // repetition sequence in the macro (e.g. `$(pat)*`). Parse the + // contents of the sequence itself + let sequence = parse(tts, parsing_patterns, sess, node_id, features, edition); // Get the Kleene operator and optional separator let (separator, kleene) = - parse_sep_and_kleene_op(&mut trees, span.entire(), sess); + parse_sep_and_kleene_op(&mut trees, delim_span.entire(), sess); // Count the number of captured "names" (i.e., named metavars) let name_captures = macro_parser::count_names(&sequence); TokenTree::Sequence( - span, + delim_span, Lrc::new(SequenceRepetition { tts: sequence, separator, @@ -197,7 +237,20 @@ fn parse_tree( } } - // `tree` is followed by a random token. This is an error. + // `tree` is followed by another `$`. This is an escaped `$`. + Some(tokenstream::TokenTree::Token(Token { kind: token::Dollar, span })) => { + if parsing_patterns { + span_dollar_dollar_or_metavar_in_the_lhs_err( + sess, + &Token { kind: token::Dollar, span }, + ); + } else { + maybe_emit_macro_metavar_expr_feature(features, sess, span); + } + TokenTree::token(token::Dollar, span) + } + + // `tree` is followed by some other token. This is an error. Some(tokenstream::TokenTree::Token(token)) => { let msg = format!( "expected identifier, found `{}`", @@ -221,7 +274,7 @@ fn parse_tree( span, Lrc::new(Delimited { delim, - tts: parse(tts, expect_matchers, sess, node_id, features, edition), + tts: parse(tts, parsing_patterns, sess, node_id, features, edition), }), ), } @@ -309,3 +362,15 @@ fn parse_sep_and_kleene_op( // Return a dummy (None, KleeneToken::new(KleeneOp::ZeroOrMore, span)) } + +// `$$` or a meta-variable is the lhs of a macro but shouldn't. +// +// For example, `macro_rules! foo { ( ${length()} ) => {} }` +fn span_dollar_dollar_or_metavar_in_the_lhs_err<'sess>(sess: &'sess ParseSess, token: &Token) { + sess.span_diagnostic + .span_err(token.span, &format!("unexpected token: {}", pprust::token_to_string(token))); + sess.span_diagnostic.span_note_without_error( + token.span, + "`$$` and meta-variable expressions are not allowed inside macro parameter definitions", + ); +} diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index 760dea77f9c2b..b8d8394754134 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -255,6 +255,11 @@ pub(super) fn transcribe<'a>( } } + // Replace meta-variable expressions with the result of their expansion. + mbe::TokenTree::MetaVarExpr(sp, expr) => { + transcribe_metavar_expr(cx, expr, interp, &repeats, &mut result, &sp)?; + } + // If we are entering a new delimiter, we push its contents to the `stack` to be // processed, and we push all of the currently produced results to the `result_stack`. // We will produce all of the results of the inside of the `Delimited` and then we will @@ -391,6 +396,28 @@ fn lockstep_iter_size( _ => LockstepIterSize::Unconstrained, } } + TokenTree::MetaVarExpr(_, ref expr) => { + let default_rslt = LockstepIterSize::Unconstrained; + let Some(ident) = expr.ident() else { return default_rslt; }; + let name = MacroRulesNormalizedIdent::new(ident.clone()); + match lookup_cur_matched(name, interpolations, repeats) { + Some(MatchedSeq(ref ads)) => { + default_rslt.with(LockstepIterSize::Constraint(ads.len(), name)) + } + _ => default_rslt, + } + } TokenTree::Token(..) => LockstepIterSize::Unconstrained, } } + +fn transcribe_metavar_expr<'a>( + _cx: &ExtCtxt<'a>, + _expr: mbe::MetaVarExpr, + _interp: &FxHashMap, + _repeats: &[(usize, usize)], + _result: &mut Vec, + _sp: &DelimSpan, +) -> PResult<'a, ()> { + Ok(()) +} diff --git a/compiler/rustc_feature/src/active.rs b/compiler/rustc_feature/src/active.rs index a69d28b184aed..a91f05587b277 100644 --- a/compiler/rustc_feature/src/active.rs +++ b/compiler/rustc_feature/src/active.rs @@ -426,6 +426,8 @@ declare_features! ( (active, link_cfg, "1.14.0", Some(37406), None), /// Allows using `reason` in lint attributes and the `#[expect(lint)]` lint check. (active, lint_reasons, "1.31.0", Some(54503), None), + /// Give access to additional metadata about declarative macro meta-variables. + (active, macro_metavar_expr, "1.61.0", Some(83527), None), /// Allows `#[marker]` on certain traits allowing overlapping implementations. (active, marker_trait_attr, "1.30.0", Some(29864), None), /// A minimal, sound subset of specialization intended to be used by the diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 3f44292e03425..0d87233d9d79d 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -845,6 +845,7 @@ symbols! { macro_export, macro_lifetime_matcher, macro_literal_matcher, + macro_metavar_expr, macro_reexport, macro_use, macro_vis_matcher, diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/dollar-dollar-has-correct-behavior.rs b/src/test/ui/macros/rfc-3086-metavar-expr/dollar-dollar-has-correct-behavior.rs new file mode 100644 index 0000000000000..ed94c27cf05ca --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/dollar-dollar-has-correct-behavior.rs @@ -0,0 +1,28 @@ +// run-pass + +#![feature(macro_metavar_expr)] + +macro_rules! nested { + ( $a:ident ) => { + macro_rules! $a { + ( $$( $b:ident ),* ) => { + $$( + macro_rules! $b { + ( $$$$( $c:ident ),* ) => { + $$$$( + fn $c() -> &'static str { stringify!($c) } + ),* + }; + } + )* + }; + } + }; +} + +fn main() { + nested!(a); + a!(b); + b!(c); + assert_eq!(c(), "c"); +} diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/feature-gate-macro_metavar_expr.rs b/src/test/ui/macros/rfc-3086-metavar-expr/feature-gate-macro_metavar_expr.rs new file mode 100644 index 0000000000000..6434ecc7e092d --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/feature-gate-macro_metavar_expr.rs @@ -0,0 +1,14 @@ +// run-pass + +#![feature(macro_metavar_expr)] + +macro_rules! ignore { + ( $( $i:ident ),* ) => {{ + let array: [i32; 0] = [$( ${ignore(i)} )*]; + array + }}; +} + +fn main() { + assert_eq!(ignore!(a, b, c), []); +} diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/required-feature.rs b/src/test/ui/macros/rfc-3086-metavar-expr/required-feature.rs new file mode 100644 index 0000000000000..cff6f29a15386 --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/required-feature.rs @@ -0,0 +1,9 @@ +macro_rules! count { + ( $( $e:stmt ),* ) => { + ${ count(e) } + //~^ ERROR meta-variable expressions are unstable + }; +} + +fn main() { +} diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/required-feature.stderr b/src/test/ui/macros/rfc-3086-metavar-expr/required-feature.stderr new file mode 100644 index 0000000000000..f573194479314 --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/required-feature.stderr @@ -0,0 +1,12 @@ +error[E0658]: meta-variable expressions are unstable + --> $DIR/required-feature.rs:3:10 + | +LL | ${ count(e) } + | ^^^^^^^^^^^^ + | + = note: see issue #83527 for more information + = help: add `#![feature(macro_metavar_expr)]` to the crate attributes to enable + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0658`. diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs b/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs new file mode 100644 index 0000000000000..ea73fd0813c5b --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs @@ -0,0 +1,148 @@ +#![feature(macro_metavar_expr)] + +// `curly` = Right hand side curly brackets +// `no_rhs_dollar` = No dollar sign at the right hand side meta variable "function" +// `round` = Left hand side round brackets + +macro_rules! curly__no_rhs_dollar__round { + ( $( $i:ident ),* ) => { ${ count(i) } }; +} + +macro_rules! curly__no_rhs_dollar__no_round { + ( $i:ident ) => { ${ count(i) } }; +} + +macro_rules! curly__rhs_dollar__round { + ( $( $i:ident ),* ) => { ${ count($i) } }; + //~^ ERROR expected identifier, found `$` + //~| ERROR expected expression, found `$` +} + +macro_rules! curly__rhs_dollar__no_round { + ( $i:ident ) => { ${ count($i) } }; + //~^ ERROR expected identifier, found `$` + //~| ERROR expected expression, found `$` +} + +macro_rules! no_curly__no_rhs_dollar__round { + ( $( $i:ident ),* ) => { count(i) }; + //~^ ERROR cannot find function `count` in this scope + //~| ERROR cannot find value `i` in this scope +} + +macro_rules! no_curly__no_rhs_dollar__no_round { + ( $i:ident ) => { count(i) }; + //~^ ERROR cannot find function `count` in this scope + //~| ERROR cannot find value `i` in this scope +} + +macro_rules! no_curly__rhs_dollar__round { + ( $( $i:ident ),* ) => { count($i) }; + //~^ ERROR variable 'i' is still repeating at this depth +} + +macro_rules! no_curly__rhs_dollar__no_round { + ( $i:ident ) => { count($i) }; + //~^ ERROR cannot find function `count` in this scope +} + +// Other scenarios + +macro_rules! dollar_dollar_in_the_lhs { + ( $$ $a:ident ) => { + //~^ ERROR unexpected token: $ + }; +} + +macro_rules! extra_garbage_after_metavar { + ( $( $i:ident ),* ) => { + ${count() a b c} + //~^ ERROR unexpected token: a + //~| ERROR expected expression, found `$` + ${count(i a b c)} + //~^ ERROR unexpected token: a + ${count(i, 1 a b c)} + //~^ ERROR unexpected token: a + ${count(i) a b c} + //~^ ERROR unexpected token: a + + ${ignore(i) a b c} + //~^ ERROR unexpected token: a + ${ignore(i a b c)} + //~^ ERROR unexpected token: a + + ${index() a b c} + //~^ ERROR unexpected token: a + ${index(1 a b c)} + //~^ ERROR unexpected token: a + + ${index() a b c} + //~^ ERROR unexpected token: a + ${index(1 a b c)} + //~^ ERROR unexpected token: a + }; +} + +const IDX: usize = 1; +macro_rules! metavar_depth_is_not_literal { + ( $( $i:ident ),* ) => { ${ index(IDX) } }; + //~^ ERROR meta-variable expression depth must be a literal + //~| ERROR expected expression, found `$` +} + +macro_rules! metavar_in_the_lhs { + ( ${ length() } ) => { + //~^ ERROR unexpected token: { + //~| ERROR expected one of: `*`, `+`, or `?` + }; +} + +macro_rules! metavar_token_without_ident { + ( $( $i:ident ),* ) => { ${ ignore() } }; + //~^ ERROR expected identifier + //~| ERROR expected expression, found `$` +} + +macro_rules! metavar_with_literal_suffix { + ( $( $i:ident ),* ) => { ${ index(1u32) } }; + //~^ ERROR only unsuffixes integer literals are supported in meta-variable expressions + //~| ERROR expected expression, found `$` +} + +macro_rules! metavar_without_parens { + ( $( $i:ident ),* ) => { ${ count{i} } }; + //~^ ERROR meta-variable expression parameter must be wrapped in parentheses + //~| ERROR expected expression, found `$` +} + +macro_rules! open_brackets_without_tokens { + ( $( $i:ident ),* ) => { ${ {} } }; + //~^ ERROR expected expression, found `$` + //~| ERROR expected identifier +} + +macro_rules! unknown_metavar { + ( $( $i:ident ),* ) => { ${ aaaaaaaaaaaaaa(i) } }; + //~^ ERROR unrecognized meta-variable expression + //~| ERROR expected expression +} + +fn main() { + curly__no_rhs_dollar__round!(a, b, c); + curly__no_rhs_dollar__no_round!(a); + curly__rhs_dollar__round!(a, b, c); + curly__rhs_dollar__no_round!(a); + no_curly__no_rhs_dollar__round!(a, b, c); + no_curly__no_rhs_dollar__no_round!(a); + no_curly__rhs_dollar__round!(a, b, c); + no_curly__rhs_dollar__no_round!(a); + //~^ ERROR cannot find value `a` in this scope + + extra_garbage_after_metavar!(a); + unknown_metavar!(a); + metavar_without_parens!(a); + metavar_token_without_ident!(a); + metavar_depth_is_not_literal!(a); + metavar_with_literal_suffix!(a); + open_brackets_without_tokens!(a) +} diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr b/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr new file mode 100644 index 0000000000000..dc8b7a668c4ee --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr @@ -0,0 +1,367 @@ +error: expected identifier, found `$` + --> $DIR/syntax-errors.rs:16:33 + | +LL | ( $( $i:ident ),* ) => { ${ count($i) } }; + | ^^^^^ - help: try removing `$` + +error: expected identifier, found `$` + --> $DIR/syntax-errors.rs:22:26 + | +LL | ( $i:ident ) => { ${ count($i) } }; + | ^^^^^ - help: try removing `$` + +error: unexpected token: $ + --> $DIR/syntax-errors.rs:52:8 + | +LL | ( $$ $a:ident ) => { + | ^ + +note: `$$` and meta-variable expressions are not allowed inside macro parameter definitions + --> $DIR/syntax-errors.rs:52:8 + | +LL | ( $$ $a:ident ) => { + | ^ + +error: unexpected token: a + --> $DIR/syntax-errors.rs:59:19 + | +LL | ${count() a b c} + | ^ + | +note: meta-variable expression must not have trailing tokens + --> $DIR/syntax-errors.rs:59:19 + | +LL | ${count() a b c} + | ^ + +error: unexpected token: a + --> $DIR/syntax-errors.rs:62:19 + | +LL | ${count(i a b c)} + | ^ + | +note: meta-variable expression must not have trailing tokens + --> $DIR/syntax-errors.rs:62:19 + | +LL | ${count(i a b c)} + | ^ + +error: unexpected token: a + --> $DIR/syntax-errors.rs:64:22 + | +LL | ${count(i, 1 a b c)} + | ^ + | +note: meta-variable expression must not have trailing tokens + --> $DIR/syntax-errors.rs:64:22 + | +LL | ${count(i, 1 a b c)} + | ^ + +error: unexpected token: a + --> $DIR/syntax-errors.rs:66:20 + | +LL | ${count(i) a b c} + | ^ + | +note: meta-variable expression must not have trailing tokens + --> $DIR/syntax-errors.rs:66:20 + | +LL | ${count(i) a b c} + | ^ + +error: unexpected token: a + --> $DIR/syntax-errors.rs:69:21 + | +LL | ${ignore(i) a b c} + | ^ + | +note: meta-variable expression must not have trailing tokens + --> $DIR/syntax-errors.rs:69:21 + | +LL | ${ignore(i) a b c} + | ^ + +error: unexpected token: a + --> $DIR/syntax-errors.rs:71:20 + | +LL | ${ignore(i a b c)} + | ^ + | +note: meta-variable expression must not have trailing tokens + --> $DIR/syntax-errors.rs:71:20 + | +LL | ${ignore(i a b c)} + | ^ + +error: unexpected token: a + --> $DIR/syntax-errors.rs:74:19 + | +LL | ${index() a b c} + | ^ + | +note: meta-variable expression must not have trailing tokens + --> $DIR/syntax-errors.rs:74:19 + | +LL | ${index() a b c} + | ^ + +error: unexpected token: a + --> $DIR/syntax-errors.rs:76:19 + | +LL | ${index(1 a b c)} + | ^ + | +note: meta-variable expression must not have trailing tokens + --> $DIR/syntax-errors.rs:76:19 + | +LL | ${index(1 a b c)} + | ^ + +error: unexpected token: a + --> $DIR/syntax-errors.rs:79:19 + | +LL | ${index() a b c} + | ^ + | +note: meta-variable expression must not have trailing tokens + --> $DIR/syntax-errors.rs:79:19 + | +LL | ${index() a b c} + | ^ + +error: unexpected token: a + --> $DIR/syntax-errors.rs:81:19 + | +LL | ${index(1 a b c)} + | ^ + | +note: meta-variable expression must not have trailing tokens + --> $DIR/syntax-errors.rs:81:19 + | +LL | ${index(1 a b c)} + | ^ + +error: meta-variable expression depth must be a literal + --> $DIR/syntax-errors.rs:88:33 + | +LL | ( $( $i:ident ),* ) => { ${ index(IDX) } }; + | ^^^^^ + +error: unexpected token: { + --> $DIR/syntax-errors.rs:94:8 + | +LL | ( ${ length() } ) => { + | ^^^^^^^^^^^^ + +note: `$$` and meta-variable expressions are not allowed inside macro parameter definitions + --> $DIR/syntax-errors.rs:94:8 + | +LL | ( ${ length() } ) => { + | ^^^^^^^^^^^^ + +error: expected one of: `*`, `+`, or `?` + --> $DIR/syntax-errors.rs:94:8 + | +LL | ( ${ length() } ) => { + | ^^^^^^^^^^^^ + +error: expected identifier + --> $DIR/syntax-errors.rs:101:33 + | +LL | ( $( $i:ident ),* ) => { ${ ignore() } }; + | ^^^^^^ + +error: only unsuffixes integer literals are supported in meta-variable expressions + --> $DIR/syntax-errors.rs:107:33 + | +LL | ( $( $i:ident ),* ) => { ${ index(1u32) } }; + | ^^^^^ + +error: meta-variable expression parameter must be wrapped in parentheses + --> $DIR/syntax-errors.rs:113:33 + | +LL | ( $( $i:ident ),* ) => { ${ count{i} } }; + | ^^^^^ + +error: expected identifier + --> $DIR/syntax-errors.rs:119:31 + | +LL | ( $( $i:ident ),* ) => { ${ {} } }; + | ^^^^^^ + +error: unrecognized meta-variable expression + --> $DIR/syntax-errors.rs:125:33 + | +LL | ( $( $i:ident ),* ) => { ${ aaaaaaaaaaaaaa(i) } }; + | ^^^^^^^^^^^^^^ help: supported expressions are count, ignore, index and length + +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:16:30 + | +LL | ( $( $i:ident ),* ) => { ${ count($i) } }; + | ^ expected expression +... +LL | curly__rhs_dollar__round!(a, b, c); + | ---------------------------------- in this macro invocation + | + = note: this error originates in the macro `curly__rhs_dollar__round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:22:23 + | +LL | ( $i:ident ) => { ${ count($i) } }; + | ^ expected expression +... +LL | curly__rhs_dollar__no_round!(a); + | ------------------------------- in this macro invocation + | + = note: this error originates in the macro `curly__rhs_dollar__no_round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: variable 'i' is still repeating at this depth + --> $DIR/syntax-errors.rs:40:36 + | +LL | ( $( $i:ident ),* ) => { count($i) }; + | ^^ + +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:59:9 + | +LL | ${count() a b c} + | ^ expected expression +... +LL | extra_garbage_after_metavar!(a); + | ------------------------------- in this macro invocation + | + = note: this error originates in the macro `extra_garbage_after_metavar` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:125:30 + | +LL | ( $( $i:ident ),* ) => { ${ aaaaaaaaaaaaaa(i) } }; + | ^ expected expression +... +LL | unknown_metavar!(a); + | ------------------- in this macro invocation + | + = note: this error originates in the macro `unknown_metavar` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:113:30 + | +LL | ( $( $i:ident ),* ) => { ${ count{i} } }; + | ^ expected expression +... +LL | metavar_without_parens!(a); + | -------------------------- in this macro invocation + | + = note: this error originates in the macro `metavar_without_parens` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:101:30 + | +LL | ( $( $i:ident ),* ) => { ${ ignore() } }; + | ^ expected expression +... +LL | metavar_token_without_ident!(a); + | ------------------------------- in this macro invocation + | + = note: this error originates in the macro `metavar_token_without_ident` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:88:30 + | +LL | ( $( $i:ident ),* ) => { ${ index(IDX) } }; + | ^ expected expression +... +LL | metavar_depth_is_not_literal!(a); + | -------------------------------- in this macro invocation + | + = note: this error originates in the macro `metavar_depth_is_not_literal` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:107:30 + | +LL | ( $( $i:ident ),* ) => { ${ index(1u32) } }; + | ^ expected expression +... +LL | metavar_with_literal_suffix!(a); + | ------------------------------- in this macro invocation + | + = note: this error originates in the macro `metavar_with_literal_suffix` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:119:30 + | +LL | ( $( $i:ident ),* ) => { ${ {} } }; + | ^ expected expression +... +LL | open_brackets_without_tokens!(a) + | -------------------------------- in this macro invocation + | + = note: this error originates in the macro `open_brackets_without_tokens` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0425]: cannot find function `count` in this scope + --> $DIR/syntax-errors.rs:28:30 + | +LL | ( $( $i:ident ),* ) => { count(i) }; + | ^^^^^ not found in this scope +... +LL | no_curly__no_rhs_dollar__round!(a, b, c); + | ---------------------------------------- in this macro invocation + | + = note: this error originates in the macro `no_curly__no_rhs_dollar__round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0425]: cannot find value `i` in this scope + --> $DIR/syntax-errors.rs:28:36 + | +LL | ( $( $i:ident ),* ) => { count(i) }; + | ^ not found in this scope +... +LL | no_curly__no_rhs_dollar__round!(a, b, c); + | ---------------------------------------- in this macro invocation + | + = note: this error originates in the macro `no_curly__no_rhs_dollar__round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0425]: cannot find function `count` in this scope + --> $DIR/syntax-errors.rs:34:23 + | +LL | ( $i:ident ) => { count(i) }; + | ^^^^^ not found in this scope +... +LL | no_curly__no_rhs_dollar__no_round!(a); + | ------------------------------------- in this macro invocation + | + = note: this error originates in the macro `no_curly__no_rhs_dollar__no_round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0425]: cannot find value `i` in this scope + --> $DIR/syntax-errors.rs:34:29 + | +LL | ( $i:ident ) => { count(i) }; + | ^ not found in this scope +... +LL | no_curly__no_rhs_dollar__no_round!(a); + | ------------------------------------- in this macro invocation + | + = note: this error originates in the macro `no_curly__no_rhs_dollar__no_round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0425]: cannot find function `count` in this scope + --> $DIR/syntax-errors.rs:45:23 + | +LL | ( $i:ident ) => { count($i) }; + | ^^^^^ not found in this scope +... +LL | no_curly__rhs_dollar__no_round!(a); + | ---------------------------------- in this macro invocation + | + = note: this error originates in the macro `no_curly__rhs_dollar__no_round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0425]: cannot find value `a` in this scope + --> $DIR/syntax-errors.rs:138:37 + | +LL | no_curly__rhs_dollar__no_round!(a); + | ^ not found in this scope + +error: aborting due to 37 previous errors + +For more information about this error, try `rustc --explain E0425`. From 29d979fb3c2fb2caf0727b29b22ac400947fc101 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 9 Mar 2022 19:31:25 -0500 Subject: [PATCH 09/11] enable portable-simd doctests in Miri --- library/core/src/lib.rs | 2 -- library/core/src/slice/mod.rs | 3 --- library/std/src/lib.rs | 2 -- 3 files changed, 7 deletions(-) diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index f436afbee448e..f6ede8964ff8b 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -408,12 +408,10 @@ pub mod arch { #[allow(missing_debug_implementations, dead_code, unsafe_op_in_unsafe_fn, unused_unsafe)] #[allow(rustdoc::bare_urls)] #[unstable(feature = "portable_simd", issue = "86656")] -#[cfg(not(all(miri, doctest)))] // Skip SIMD doctests in Miri mod core_simd; #[doc = include_str!("../../portable-simd/crates/core_simd/src/core_simd_docs.md")] #[unstable(feature = "portable_simd", issue = "86656")] -#[cfg(not(all(miri, doctest)))] // Skip SIMD doctests in Miri pub mod simd { #[unstable(feature = "portable_simd", issue = "86656")] pub use crate::core_simd::simd::*; diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 9467c7f54bac7..839dce4ca0b18 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -16,7 +16,6 @@ use crate::option::Option::{None, Some}; use crate::ptr; use crate::result::Result; use crate::result::Result::{Err, Ok}; -#[cfg(not(all(miri, doctest)))] // Miri skips SIMD doctests use crate::simd::{self, Simd}; use crate::slice; @@ -3540,7 +3539,6 @@ impl [T] { /// assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0); /// ``` #[unstable(feature = "portable_simd", issue = "86656")] - #[cfg(not(all(miri, doctest)))] // Miri skips SIMD doctests pub fn as_simd(&self) -> (&[T], &[Simd], &[T]) where Simd: AsRef<[T; LANES]>, @@ -3584,7 +3582,6 @@ impl [T] { /// be lifted in a way that would make it possible to see panics from this /// method for something like `LANES == 3`. #[unstable(feature = "portable_simd", issue = "86656")] - #[cfg(not(all(miri, doctest)))] // Miri skips SIMD doctests pub fn as_simd_mut(&mut self) -> (&mut [T], &mut [Simd], &mut [T]) where Simd: AsMut<[T; LANES]>, diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index c35389d44f9fc..6c801f2f0c56c 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -495,10 +495,8 @@ pub mod lazy; #[allow(missing_debug_implementations, dead_code, unsafe_op_in_unsafe_fn, unused_unsafe)] #[allow(rustdoc::bare_urls)] #[unstable(feature = "portable_simd", issue = "86656")] -#[cfg(not(all(miri, doctest)))] // Miri does not support all SIMD intrinsics mod std_float; -#[cfg(not(all(miri, doctest)))] // Miri does not support all SIMD intrinsics #[doc = include_str!("../../portable-simd/crates/core_simd/src/core_simd_docs.md")] #[unstable(feature = "portable_simd", issue = "86656")] pub mod simd { From 72a25d05bf1a4b155d74139ef700ff93af6d8e22 Mon Sep 17 00:00:00 2001 From: T-O-R-U-S Date: Sat, 12 Feb 2022 23:16:17 +0400 Subject: [PATCH 10/11] Use implicit capture syntax in format_args This updates the standard library's documentation to use the new syntax. The documentation is worthwhile to update as it should be more idiomatic (particularly for features like this, which are nice for users to get acquainted with). The general codebase is likely more hassle than benefit to update: it'll hurt git blame, and generally updates can be done by folks updating the code if (and when) that makes things more readable with the new format. A few places in the compiler and library code are updated (mostly just due to already having been done when this commit was first authored). --- compiler/rustc_errors/src/lib.rs | 4 +- compiler/rustc_lint_defs/src/builtin.rs | 2 +- compiler/rustc_middle/src/ty/closure.rs | 2 +- compiler/rustc_typeck/src/check/upvar.rs | 6 +- library/alloc/src/alloc.rs | 2 +- library/alloc/src/borrow.rs | 2 +- library/alloc/src/boxed.rs | 12 +- library/alloc/src/collections/binary_heap.rs | 10 +- library/alloc/src/collections/btree/map.rs | 12 +- .../alloc/src/collections/btree/map/tests.rs | 2 +- library/alloc/src/collections/btree/set.rs | 4 +- .../alloc/src/collections/btree/set/tests.rs | 6 +- library/alloc/src/fmt.rs | 6 +- library/alloc/src/rc/tests.rs | 6 +- library/alloc/src/slice.rs | 2 +- library/alloc/src/string.rs | 2 +- library/alloc/src/sync.rs | 4 +- library/alloc/src/sync/tests.rs | 8 +- library/alloc/src/tests.rs | 8 +- library/alloc/src/vec/mod.rs | 14 +- library/alloc/tests/fmt.rs | 24 ++-- library/alloc/tests/linked_list.rs | 4 +- library/alloc/tests/slice.rs | 12 +- library/alloc/tests/str.rs | 10 +- library/alloc/tests/string.rs | 4 +- library/alloc/tests/vec.rs | 6 +- library/alloc/tests/vec_deque.rs | 4 +- library/core/benches/num/flt2dec/mod.rs | 2 +- .../benches/num/flt2dec/strategy/grisu.rs | 2 +- library/core/src/any.rs | 2 +- library/core/src/cell.rs | 2 +- library/core/src/char/methods.rs | 10 +- library/core/src/fmt/mod.rs | 92 ++++++------- library/core/src/iter/adapters/map.rs | 4 +- library/core/src/iter/mod.rs | 16 +-- library/core/src/iter/sources/once.rs | 2 +- library/core/src/iter/sources/once_with.rs | 2 +- library/core/src/iter/traits/collect.rs | 4 +- library/core/src/iter/traits/double_ended.rs | 2 +- library/core/src/iter/traits/iterator.rs | 22 +-- library/core/src/macros/mod.rs | 14 +- library/core/src/marker.rs | 4 +- library/core/src/num/dec2flt/mod.rs | 2 +- library/core/src/num/error.rs | 2 +- library/core/src/ops/index.rs | 4 +- library/core/src/ops/range.rs | 2 +- library/core/src/option.rs | 14 +- library/core/src/panic/panic_info.rs | 4 +- library/core/src/panicking.rs | 4 +- library/core/src/primitive_docs.rs | 20 +-- library/core/src/ptr/const_ptr.rs | 4 +- library/core/src/ptr/mut_ptr.rs | 8 +- library/core/src/ptr/non_null.rs | 2 +- library/core/src/result.rs | 24 ++-- library/core/src/slice/index.rs | 6 +- library/core/src/slice/iter.rs | 6 +- library/core/src/slice/mod.rs | 4 +- library/core/src/str/mod.rs | 8 +- library/core/src/sync/atomic.rs | 4 +- library/core/src/time.rs | 2 +- library/core/src/unit.rs | 2 +- library/core/tests/any.rs | 16 +-- library/core/tests/cell.rs | 8 +- library/core/tests/fmt/builders.rs | 126 +++++++++--------- library/core/tests/fmt/mod.rs | 8 +- library/core/tests/fmt/num.rs | 2 +- library/core/tests/lazy.rs | 2 +- library/core/tests/num/dec2flt/mod.rs | 8 +- library/core/tests/num/dec2flt/parse.rs | 2 +- library/core/tests/num/flt2dec/mod.rs | 2 +- library/core/tests/num/flt2dec/random.rs | 2 +- library/core/tests/ptr.rs | 2 +- library/core/tests/result.rs | 4 +- .../crates/core_simd/examples/nbody.rs | 4 +- library/proc_macro/src/lib.rs | 8 +- library/std/src/alloc.rs | 2 +- library/std/src/backtrace/tests.rs | 6 +- library/std/src/collections/hash/map.rs | 18 +-- library/std/src/collections/hash/map/tests.rs | 6 +- library/std/src/collections/hash/set.rs | 18 +-- library/std/src/collections/hash/set/tests.rs | 4 +- library/std/src/collections/mod.rs | 8 +- library/std/src/env.rs | 24 ++-- library/std/src/error.rs | 26 ++-- library/std/src/error/tests.rs | 6 +- library/std/src/ffi/c_str.rs | 4 +- library/std/src/ffi/c_str/tests.rs | 2 +- library/std/src/fs.rs | 6 +- library/std/src/fs/tests.rs | 10 +- library/std/src/io/buffered/bufreader.rs | 2 +- library/std/src/io/error.rs | 14 +- library/std/src/io/error/repr_bitpacked.rs | 3 +- library/std/src/io/error/tests.rs | 8 +- library/std/src/io/mod.rs | 12 +- library/std/src/io/stdio.rs | 8 +- library/std/src/keyword_docs.rs | 48 +++---- library/std/src/net/addr/tests.rs | 30 ++--- library/std/src/net/tcp.rs | 10 +- library/std/src/net/tcp/tests.rs | 11 +- library/std/src/net/udp.rs | 14 +- library/std/src/net/udp/tests.rs | 6 +- library/std/src/os/unix/fs.rs | 4 +- library/std/src/os/unix/net/addr.rs | 6 +- library/std/src/os/unix/net/ancillary.rs | 6 +- library/std/src/os/unix/net/datagram.rs | 24 ++-- library/std/src/os/unix/net/listener.rs | 10 +- library/std/src/os/unix/net/stream.rs | 14 +- library/std/src/os/unix/net/tests.rs | 12 +- library/std/src/panicking.rs | 6 +- library/std/src/path.rs | 2 +- library/std/src/path/tests.rs | 22 +-- library/std/src/primitive_docs.rs | 20 +-- library/std/src/process.rs | 18 +-- library/std/src/process/tests.rs | 14 +- library/std/src/sync/mod.rs | 2 +- library/std/src/sync/mpsc/mod.rs | 20 +-- library/std/src/sync/mpsc/shared.rs | 2 +- library/std/src/sync/mutex/tests.rs | 4 +- library/std/src/sync/poison.rs | 2 +- library/std/src/sync/rwlock/tests.rs | 4 +- library/std/src/sys/sgx/abi/mod.rs | 2 +- library/std/src/sys/sgx/abi/usercalls/mod.rs | 4 +- library/std/src/sys/sgx/abi/usercalls/raw.rs | 2 +- library/std/src/sys/sgx/net.rs | 2 +- library/std/src/sys/sgx/os.rs | 2 +- library/std/src/sys/sgx/stdio.rs | 2 +- library/std/src/sys/solid/mod.rs | 2 +- library/std/src/sys/solid/net.rs | 2 +- library/std/src/sys/solid/os.rs | 2 +- library/std/src/sys/unix/net.rs | 2 +- library/std/src/sys/unix/os_str/tests.rs | 2 +- .../src/sys/unix/process/process_fuchsia.rs | 2 +- .../std/src/sys/unix/process/process_unix.rs | 10 +- .../src/sys/unix/process/process_vxworks.rs | 4 +- library/std/src/sys/unix/rand.rs | 2 +- library/std/src/sys/windows/os.rs | 2 +- library/std/src/sys/windows/process/tests.rs | 4 +- library/std/src/sys/windows/thread_parker.rs | 2 +- library/std/src/sys_common/backtrace.rs | 2 +- library/std/src/sys_common/net/tests.rs | 2 +- .../src/sys_common/thread_parker/generic.rs | 2 +- library/std/src/sys_common/wtf8.rs | 2 +- library/std/src/sys_common/wtf8/tests.rs | 4 +- library/std/src/thread/mod.rs | 6 +- library/std/src/thread/scoped.rs | 2 +- library/std/src/time.rs | 4 +- library/std/src/time/tests.rs | 6 +- library/test/src/cli.rs | 4 +- library/test/src/console.rs | 16 +-- library/test/src/formatters/junit.rs | 2 +- library/test/src/formatters/pretty.rs | 16 +-- library/test/src/formatters/terse.rs | 14 +- library/test/src/helpers/concurrency.rs | 2 +- library/test/src/helpers/exit_code.rs | 2 +- library/test/src/lib.rs | 12 +- library/test/src/term/terminfo/parm.rs | 2 +- library/test/src/term/terminfo/parm/tests.rs | 6 +- .../test/src/term/terminfo/parser/compiled.rs | 2 +- library/test/src/test_result.rs | 2 +- .../rustdoc/src/how-to-write-documentation.md | 2 +- .../src/compiler-flags/sanitizer.md | 8 +- .../src/language-features/box-patterns.md | 4 +- src/librustdoc/clean/mod.rs | 2 +- src/librustdoc/doctest.rs | 39 +++--- src/librustdoc/html/markdown.rs | 2 +- src/librustdoc/markdown.rs | 2 +- src/tools/tidy/src/bins.rs | 2 +- src/tools/tidy/src/deps.rs | 14 +- src/tools/tidy/src/error_codes_check.rs | 4 +- src/tools/tidy/src/features.rs | 8 +- src/tools/tidy/src/primitive_docs.rs | 6 +- src/tools/tidy/src/style.rs | 10 +- src/tools/tidy/src/target_specific_tests.rs | 4 +- src/tools/unicode-table-generator/src/main.rs | 10 +- .../src/unicode_download.rs | 5 +- src/tools/unstable-book-gen/src/main.rs | 2 +- src/tools/x/src/main.rs | 2 +- 177 files changed, 724 insertions(+), 734 deletions(-) diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 217d3ec2c247a..3641c38f9dcd0 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -1087,12 +1087,12 @@ impl HandlerInner { let warnings = match self.deduplicated_warn_count { 0 => String::new(), 1 => "1 warning emitted".to_string(), - count => format!("{} warnings emitted", count), + count => format!("{count} warnings emitted"), }; let errors = match self.deduplicated_err_count { 0 => String::new(), 1 => "aborting due to previous error".to_string(), - count => format!("aborting due to {} previous errors", count), + count => format!("aborting due to {count} previous errors"), }; if self.treat_err_as_bug() { return; diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 04a339f3c95a6..0f80ccaf6ad7f 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -3399,7 +3399,7 @@ declare_lint! { /// // ^^^^^^^^ /// // This call to try_into matches both Foo:try_into and TryInto::try_into as /// // `TryInto` has been added to the Rust prelude in 2021 edition. - /// println!("{}", x); + /// println!("{x}"); /// } /// ``` /// diff --git a/compiler/rustc_middle/src/ty/closure.rs b/compiler/rustc_middle/src/ty/closure.rs index 8ba6c1f67c94c..65a60dd6b9d7b 100644 --- a/compiler/rustc_middle/src/ty/closure.rs +++ b/compiler/rustc_middle/src/ty/closure.rs @@ -281,7 +281,7 @@ pub struct CaptureInfo { /// let mut t = (0,1); /// /// let c = || { - /// println!("{}",t); // L1 + /// println!("{t}"); // L1 /// t.1 = 4; // L2 /// }; /// ``` diff --git a/compiler/rustc_typeck/src/check/upvar.rs b/compiler/rustc_typeck/src/check/upvar.rs index 2b5ff11501abe..a2c79c6903218 100644 --- a/compiler/rustc_typeck/src/check/upvar.rs +++ b/compiler/rustc_typeck/src/check/upvar.rs @@ -458,10 +458,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// let s: String; // hir_id_s /// let mut p: Point; // his_id_p /// let c = || { - /// println!("{}", s); // L1 + /// println!("{s}"); // L1 /// p.x += 10; // L2 - /// println!("{}" , p.y) // L3 - /// println!("{}", p) // L4 + /// println!("{}" , p.y); // L3 + /// println!("{p}"); // L4 /// drop(s); // L5 /// }; /// ``` diff --git a/library/alloc/src/alloc.rs b/library/alloc/src/alloc.rs index 9d4f9af91a5e1..bd7d721b5e173 100644 --- a/library/alloc/src/alloc.rs +++ b/library/alloc/src/alloc.rs @@ -397,7 +397,7 @@ pub mod __alloc_error_handler { // if there is no `#[alloc_error_handler]` #[rustc_std_internal_symbol] pub unsafe extern "C-unwind" fn __rdl_oom(size: usize, _align: usize) -> ! { - panic!("memory allocation of {} bytes failed", size) + panic!("memory allocation of {size} bytes failed") } // if there is an `#[alloc_error_handler]` diff --git a/library/alloc/src/borrow.rs b/library/alloc/src/borrow.rs index 63234ee91f091..8b13e36c4b3c7 100644 --- a/library/alloc/src/borrow.rs +++ b/library/alloc/src/borrow.rs @@ -161,7 +161,7 @@ where /// let readonly = [1, 2]; /// let borrowed = Items::new((&readonly[..]).into()); /// match borrowed { -/// Items { values: Cow::Borrowed(b) } => println!("borrowed {:?}", b), +/// Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"), /// _ => panic!("expect borrowed value"), /// } /// diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 68bf59a01b3dd..6b5b73740e135 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -31,7 +31,7 @@ //! } //! //! let list: List = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))); -//! println!("{:?}", list); +//! println!("{list:?}"); //! ``` //! //! This will print `Cons(1, Cons(2, Nil))`. @@ -1408,7 +1408,7 @@ impl From<&[T]> for Box<[T]> { /// let slice: &[u8] = &[104, 101, 108, 108, 111]; /// let boxed_slice: Box<[u8]> = Box::from(slice); /// - /// println!("{:?}", boxed_slice); + /// println!("{boxed_slice:?}"); /// ``` fn from(slice: &[T]) -> Box<[T]> { let len = slice.len(); @@ -1450,7 +1450,7 @@ impl From<&str> for Box { /// /// ```rust /// let boxed: Box = Box::from("hello"); - /// println!("{}", boxed); + /// println!("{boxed}"); /// ``` #[inline] fn from(s: &str) -> Box { @@ -1475,14 +1475,14 @@ impl From> for Box { /// /// let unboxed = Cow::Borrowed("hello"); /// let boxed: Box = Box::from(unboxed); - /// println!("{}", boxed); + /// println!("{boxed}"); /// ``` /// /// ```rust /// # use std::borrow::Cow; /// let unboxed = Cow::Owned("hello".to_string()); /// let boxed: Box = Box::from(unboxed); - /// println!("{}", boxed); + /// println!("{boxed}"); /// ``` #[inline] fn from(cow: Cow<'_, str>) -> Box { @@ -1529,7 +1529,7 @@ impl From<[T; N]> for Box<[T]> { /// /// ```rust /// let boxed: Box<[u8]> = Box::from([4, 2]); - /// println!("{:?}", boxed); + /// println!("{boxed:?}"); /// ``` fn from(array: [T; N]) -> Box<[T]> { box array diff --git a/library/alloc/src/collections/binary_heap.rs b/library/alloc/src/collections/binary_heap.rs index e18cd8cd46427..43fa612de6c50 100644 --- a/library/alloc/src/collections/binary_heap.rs +++ b/library/alloc/src/collections/binary_heap.rs @@ -194,7 +194,7 @@ use super::SpecExtend; /// // We can iterate over the items in the heap, although they are returned in /// // a random order. /// for x in &heap { -/// println!("{}", x); +/// println!("{x}"); /// } /// /// // If we instead pop these scores, they should come back in order. @@ -830,7 +830,7 @@ impl BinaryHeap { /// /// // Print 1, 2, 3, 4 in arbitrary order /// for x in heap.iter() { - /// println!("{}", x); + /// println!("{x}"); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -1110,7 +1110,7 @@ impl BinaryHeap { /// /// // Will print in some order /// for x in vec { - /// println!("{}", x); + /// println!("{x}"); /// } /// ``` #[must_use = "`self` will be dropped if the result is not used"] @@ -1179,7 +1179,7 @@ impl BinaryHeap { /// assert!(!heap.is_empty()); /// /// for x in heap.drain() { - /// println!("{}", x); + /// println!("{x}"); /// } /// /// assert!(heap.is_empty()); @@ -1624,7 +1624,7 @@ impl IntoIterator for BinaryHeap { /// // Print 1, 2, 3, 4 in arbitrary order /// for x in heap.into_iter() { /// // x has type i32, not &i32 - /// println!("{}", x); + /// println!("{x}"); /// } /// ``` fn into_iter(self) -> IntoIter { diff --git a/library/alloc/src/collections/btree/map.rs b/library/alloc/src/collections/btree/map.rs index 7890c1040f0a1..6d00642e03b22 100644 --- a/library/alloc/src/collections/btree/map.rs +++ b/library/alloc/src/collections/btree/map.rs @@ -104,8 +104,8 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT; /// let to_find = ["Up!", "Office Space"]; /// for movie in &to_find { /// match movie_reviews.get(movie) { -/// Some(review) => println!("{}: {}", movie, review), -/// None => println!("{} is unreviewed.", movie) +/// Some(review) => println!("{movie}: {review}"), +/// None => println!("{movie} is unreviewed.") /// } /// } /// @@ -114,7 +114,7 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT; /// /// // iterate over everything. /// for (movie, review) in &movie_reviews { -/// println!("{}: \"{}\"", movie, review); +/// println!("{movie}: \"{review}\""); /// } /// ``` /// @@ -1061,7 +1061,7 @@ impl BTreeMap { /// map.insert(5, "b"); /// map.insert(8, "c"); /// for (&key, &value) in map.range((Included(&4), Included(&8))) { - /// println!("{}: {}", key, value); + /// println!("{key}: {value}"); /// } /// assert_eq!(Some((&5, &"b")), map.range(4..).next()); /// ``` @@ -1104,7 +1104,7 @@ impl BTreeMap { /// *balance += 100; /// } /// for (name, balance) in &map { - /// println!("{} => {}", name, balance); + /// println!("{name} => {balance}"); /// } /// ``` #[stable(feature = "btree_range", since = "1.17.0")] @@ -2088,7 +2088,7 @@ impl BTreeMap { /// map.insert(1, "a"); /// /// for (key, value) in map.iter() { - /// println!("{}: {}", key, value); + /// println!("{key}: {value}"); /// } /// /// let (first_key, first_value) = map.iter().next().unwrap(); diff --git a/library/alloc/src/collections/btree/map/tests.rs b/library/alloc/src/collections/btree/map/tests.rs index 65468d5fe5716..4d21df3241724 100644 --- a/library/alloc/src/collections/btree/map/tests.rs +++ b/library/alloc/src/collections/btree/map/tests.rs @@ -1758,7 +1758,7 @@ fn test_ord_absence() { } fn map_debug(mut map: BTreeMap) { - format!("{:?}", map); + format!("{map:?}"); format!("{:?}", map.iter()); format!("{:?}", map.iter_mut()); format!("{:?}", map.keys()); diff --git a/library/alloc/src/collections/btree/set.rs b/library/alloc/src/collections/btree/set.rs index bab6af8269864..405833720b37c 100644 --- a/library/alloc/src/collections/btree/set.rs +++ b/library/alloc/src/collections/btree/set.rs @@ -60,7 +60,7 @@ use super::Recover; /// /// // Iterate over everything. /// for book in &books { -/// println!("{}", book); +/// println!("{book}"); /// } /// ``` /// @@ -284,7 +284,7 @@ impl BTreeSet { /// set.insert(5); /// set.insert(8); /// for &elem in set.range((Included(&4), Included(&8))) { - /// println!("{}", elem); + /// println!("{elem}"); /// } /// assert_eq!(Some(&5), set.range(4..).next()); /// ``` diff --git a/library/alloc/src/collections/btree/set/tests.rs b/library/alloc/src/collections/btree/set/tests.rs index 7865d37ae51f1..032563e4f09be 100644 --- a/library/alloc/src/collections/btree/set/tests.rs +++ b/library/alloc/src/collections/btree/set/tests.rs @@ -431,10 +431,10 @@ fn test_show() { set.insert(1); set.insert(2); - let set_str = format!("{:?}", set); + let set_str = format!("{set:?}"); assert_eq!(set_str, "{1, 2}"); - assert_eq!(format!("{:?}", empty), "{}"); + assert_eq!(format!("{empty:?}"), "{}"); } #[test] @@ -649,7 +649,7 @@ fn test_ord_absence() { } fn set_debug(set: BTreeSet) { - format!("{:?}", set); + format!("{set:?}"); format!("{:?}", set.iter()); format!("{:?}", set.into_iter()); } diff --git a/library/alloc/src/fmt.rs b/library/alloc/src/fmt.rs index aeb7554f8e914..501a6353b2c97 100644 --- a/library/alloc/src/fmt.rs +++ b/library/alloc/src/fmt.rs @@ -416,9 +416,9 @@ //! fn main() { //! let myvector = Vector2D { x: 3, y: 4 }; //! -//! println!("{}", myvector); // => "(3, 4)" -//! println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}" -//! println!("{:10.3b}", myvector); // => " 5.000" +//! println!("{myvector}"); // => "(3, 4)" +//! println!("{myvector:?}"); // => "Vector2D {x: 3, y:4}" +//! println!("{myvector:10.3b}"); // => " 5.000" //! } //! ``` //! diff --git a/library/alloc/src/rc/tests.rs b/library/alloc/src/rc/tests.rs index 843a9b07fa934..d7c28f8063337 100644 --- a/library/alloc/src/rc/tests.rs +++ b/library/alloc/src/rc/tests.rs @@ -309,7 +309,7 @@ fn test_cowrc_clone_weak() { #[test] fn test_show() { let foo = Rc::new(75); - assert_eq!(format!("{:?}", foo), "75"); + assert_eq!(format!("{foo:?}"), "75"); } #[test] @@ -324,7 +324,7 @@ fn test_maybe_thin_unsized() { use std::ffi::{CStr, CString}; let x: Rc = Rc::from(CString::new("swordfish").unwrap().into_boxed_c_str()); - assert_eq!(format!("{:?}", x), "\"swordfish\""); + assert_eq!(format!("{x:?}"), "\"swordfish\""); let y: Weak = Rc::downgrade(&x); drop(x); @@ -451,7 +451,7 @@ fn test_from_box_trait_zero_sized() { let b: Box = box (); let r: Rc = Rc::from(b); - assert_eq!(format!("{:?}", r), "()"); + assert_eq!(format!("{r:?}"), "()"); } #[test] diff --git a/library/alloc/src/slice.rs b/library/alloc/src/slice.rs index f0397d08f95a8..f52871c73d9fc 100644 --- a/library/alloc/src/slice.rs +++ b/library/alloc/src/slice.rs @@ -48,7 +48,7 @@ //! ``` //! let numbers = &[0, 1, 2]; //! for n in numbers { -//! println!("{} is a number!", n); +//! println!("{n} is a number!"); //! } //! ``` //! diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 716bb4983a651..71419c151968d 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -2718,7 +2718,7 @@ impl From for Vec { /// let v1 = Vec::from(s1); /// /// for b in v1 { - /// println!("{}", b); + /// println!("{b}"); /// } /// ``` fn from(string: String) -> Vec { diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 7e7670aad6425..2140c3f168d1c 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -200,7 +200,7 @@ macro_rules! acquire { /// let five = Arc::clone(&five); /// /// thread::spawn(move || { -/// println!("{:?}", five); +/// println!("{five:?}"); /// }); /// } /// ``` @@ -221,7 +221,7 @@ macro_rules! acquire { /// /// thread::spawn(move || { /// let v = val.fetch_add(1, Ordering::SeqCst); -/// println!("{:?}", v); +/// println!("{v:?}"); /// }); /// } /// ``` diff --git a/library/alloc/src/sync/tests.rs b/library/alloc/src/sync/tests.rs index 4ccb32fbbf63d..452a88773018c 100644 --- a/library/alloc/src/sync/tests.rs +++ b/library/alloc/src/sync/tests.rs @@ -335,7 +335,7 @@ fn test_weak_count() { #[test] fn show_arc() { let a = Arc::new(5); - assert_eq!(format!("{:?}", a), "5"); + assert_eq!(format!("{a:?}"), "5"); } // Make sure deriving works with Arc @@ -347,7 +347,7 @@ struct Foo { #[test] fn test_unsized() { let x: Arc<[i32]> = Arc::new([1, 2, 3]); - assert_eq!(format!("{:?}", x), "[1, 2, 3]"); + assert_eq!(format!("{x:?}"), "[1, 2, 3]"); let y = Arc::downgrade(&x.clone()); drop(x); assert!(y.upgrade().is_none()); @@ -359,7 +359,7 @@ fn test_maybe_thin_unsized() { use std::ffi::{CStr, CString}; let x: Arc = Arc::from(CString::new("swordfish").unwrap().into_boxed_c_str()); - assert_eq!(format!("{:?}", x), "\"swordfish\""); + assert_eq!(format!("{x:?}"), "\"swordfish\""); let y: Weak = Arc::downgrade(&x); drop(x); @@ -509,7 +509,7 @@ fn test_from_box_trait_zero_sized() { let b: Box = box (); let r: Arc = Arc::from(b); - assert_eq!(format!("{:?}", r), "()"); + assert_eq!(format!("{r:?}"), "()"); } #[test] diff --git a/library/alloc/src/tests.rs b/library/alloc/src/tests.rs index b4741c35c583f..299ed156a5d27 100644 --- a/library/alloc/src/tests.rs +++ b/library/alloc/src/tests.rs @@ -47,8 +47,8 @@ fn any_move() { fn test_show() { let a = Box::new(8) as Box; let b = Box::new(Test) as Box; - let a_str = format!("{:?}", a); - let b_str = format!("{:?}", b); + let a_str = format!("{a:?}"); + let b_str = format!("{b:?}"); assert_eq!(a_str, "Any { .. }"); assert_eq!(b_str, "Any { .. }"); @@ -56,9 +56,9 @@ fn test_show() { static TEST: Test = Test; let a = &EIGHT as &dyn Any; let b = &TEST as &dyn Any; - let s = format!("{:?}", a); + let s = format!("{a:?}"); assert_eq!(s, "Any { .. }"); - let s = format!("{:?}", b); + let s = format!("{b:?}"); assert_eq!(s, "Any { .. }"); } diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index c4c393f55eee9..32590a2996c01 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -169,7 +169,7 @@ mod spec_extend; /// vec.extend([1, 2, 3].iter().copied()); /// /// for x in &vec { -/// println!("{}", x); +/// println!("{x}"); /// } /// assert_eq!(vec, [7, 1, 2, 3]); /// ``` @@ -211,7 +211,7 @@ mod spec_extend; /// /// while let Some(top) = stack.pop() { /// // Prints 3, 2, 1 -/// println!("{}", top); +/// println!("{top}"); /// } /// ``` /// @@ -1297,7 +1297,7 @@ impl Vec { #[cold] #[inline(never)] fn assert_failed(index: usize, len: usize) -> ! { - panic!("swap_remove index (is {}) should be < len (is {})", index, len); + panic!("swap_remove index (is {index}) should be < len (is {len})"); } let len = self.len(); @@ -1338,7 +1338,7 @@ impl Vec { #[cold] #[inline(never)] fn assert_failed(index: usize, len: usize) -> ! { - panic!("insertion index (is {}) should be <= len (is {})", index, len); + panic!("insertion index (is {index}) should be <= len (is {len})"); } let len = self.len(); @@ -1397,7 +1397,7 @@ impl Vec { #[inline(never)] #[track_caller] fn assert_failed(index: usize, len: usize) -> ! { - panic!("removal index (is {}) should be < len (is {})", index, len); + panic!("removal index (is {index}) should be < len (is {len})"); } let len = self.len(); @@ -1942,7 +1942,7 @@ impl Vec { #[cold] #[inline(never)] fn assert_failed(at: usize, len: usize) -> ! { - panic!("`at` split index (is {}) should be <= len (is {})", at, len); + panic!("`at` split index (is {at}) should be <= len (is {len})"); } if at > self.len() { @@ -2568,7 +2568,7 @@ impl IntoIterator for Vec { /// let v = vec!["a".to_string(), "b".to_string()]; /// for s in v.into_iter() { /// // s has type String, not &String - /// println!("{}", s); + /// println!("{s}"); /// } /// ``` #[inline] diff --git a/library/alloc/tests/fmt.rs b/library/alloc/tests/fmt.rs index 27ab6c07e4309..1575a5999f932 100644 --- a/library/alloc/tests/fmt.rs +++ b/library/alloc/tests/fmt.rs @@ -84,8 +84,8 @@ fn test_format_macro_interface() { } t!(format!("{:p}", 0x1234 as *const isize), "0x1234"); t!(format!("{:p}", 0x1234 as *mut isize), "0x1234"); - t!(format!("{:x}", A), "aloha"); - t!(format!("{:X}", B), "adios"); + t!(format!("{A:x}"), "aloha"); + t!(format!("{B:X}"), "adios"); t!(format!("foo {} ☃☃☃☃☃☃", "bar"), "foo bar ☃☃☃☃☃☃"); t!(format!("{1} {0}", 0, 1), "1 0"); t!(format!("{foo} {bar}", foo = 0, bar = 1), "0 1"); @@ -94,11 +94,11 @@ fn test_format_macro_interface() { t!(format!("{_foo}", _foo = 6usize), "6"); t!(format!("{foo_bar}", foo_bar = 1), "1"); t!(format!("{}", 5 + 5), "10"); - t!(format!("{:#4}", C), "☃123"); - t!(format!("{:b}", D), "aa☃bb"); + t!(format!("{C:#4}"), "☃123"); + t!(format!("{D:b}"), "aa☃bb"); let a: &dyn fmt::Debug = &1; - t!(format!("{:?}", a), "1"); + t!(format!("{a:?}"), "1"); // Formatting strings and their arguments t!(format!("{}", "a"), "a"); @@ -206,7 +206,7 @@ fn test_format_macro_interface() { // Test that pointers don't get truncated. { let val = usize::MAX; - let exp = format!("{:#x}", val); + let exp = format!("{val:#x}"); t!(format!("{:p}", val as *const isize), exp); } @@ -216,14 +216,14 @@ fn test_format_macro_interface() { // make sure that format! doesn't move out of local variables let a = Box::new(3); - format!("{}", a); - format!("{}", a); + format!("{a}"); + format!("{a}"); // make sure that format! doesn't cause spurious unused-unsafe warnings when // it's inside of an outer unsafe block unsafe { let a: isize = ::std::mem::transmute(3_usize); - format!("{}", a); + format!("{a}"); } // test that trailing commas are acceptable @@ -315,9 +315,9 @@ fn test_once() { #[test] fn test_refcell() { let refcell = RefCell::new(5); - assert_eq!(format!("{:?}", refcell), "RefCell { value: 5 }"); + assert_eq!(format!("{refcell:?}"), "RefCell { value: 5 }"); let borrow = refcell.borrow_mut(); - assert_eq!(format!("{:?}", refcell), "RefCell { value: }"); + assert_eq!(format!("{refcell:?}"), "RefCell { value: }"); drop(borrow); - assert_eq!(format!("{:?}", refcell), "RefCell { value: 5 }"); + assert_eq!(format!("{refcell:?}"), "RefCell { value: 5 }"); } diff --git a/library/alloc/tests/linked_list.rs b/library/alloc/tests/linked_list.rs index 5f5bd9af2fe5f..66a9cca6644c4 100644 --- a/library/alloc/tests/linked_list.rs +++ b/library/alloc/tests/linked_list.rs @@ -302,10 +302,10 @@ fn test_ord_nan() { #[test] fn test_show() { let list: LinkedList<_> = (0..10).collect(); - assert_eq!(format!("{:?}", list), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); + assert_eq!(format!("{list:?}"), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); let list: LinkedList<_> = ["just", "one", "test", "more"].into_iter().collect(); - assert_eq!(format!("{:?}", list), "[\"just\", \"one\", \"test\", \"more\"]"); + assert_eq!(format!("{list:?}"), "[\"just\", \"one\", \"test\", \"more\"]"); } #[test] diff --git a/library/alloc/tests/slice.rs b/library/alloc/tests/slice.rs index b93d7938bc9a5..b027a25a146bc 100644 --- a/library/alloc/tests/slice.rs +++ b/library/alloc/tests/slice.rs @@ -1045,10 +1045,10 @@ fn test_split_iterators_size_hint() { a(v.rsplit_mut(p), b, "rsplit_mut"); for n in 0..=3 { - a(v.splitn(n, p), b, f!("splitn, n = {}", n)); - a(v.splitn_mut(n, p), b, f!("splitn_mut, n = {}", n)); - a(v.rsplitn(n, p), b, f!("rsplitn, n = {}", n)); - a(v.rsplitn_mut(n, p), b, f!("rsplitn_mut, n = {}", n)); + a(v.splitn(n, p), b, f!("splitn, n = {n}")); + a(v.splitn_mut(n, p), b, f!("splitn_mut, n = {n}")); + a(v.rsplitn(n, p), b, f!("rsplitn, n = {n}")); + a(v.rsplitn_mut(n, p), b, f!("rsplitn_mut, n = {n}")); } } } @@ -1184,8 +1184,8 @@ fn test_show() { macro_rules! test_show_vec { ($x:expr, $x_str:expr) => {{ let (x, x_str) = ($x, $x_str); - assert_eq!(format!("{:?}", x), x_str); - assert_eq!(format!("{:?}", x), x_str); + assert_eq!(format!("{x:?}"), x_str); + assert_eq!(format!("{x:?}"), x_str); }}; } let empty = Vec::::new(); diff --git a/library/alloc/tests/str.rs b/library/alloc/tests/str.rs index 6b8be2506b64e..f3ed611acda5a 100644 --- a/library/alloc/tests/str.rs +++ b/library/alloc/tests/str.rs @@ -1259,7 +1259,7 @@ fn test_chars_debug() { let s = "ศไทย中华Việt Nam"; let c = s.chars(); assert_eq!( - format!("{:?}", c), + format!("{c:?}"), r#"Chars(['ศ', 'ไ', 'ท', 'ย', '中', '华', 'V', 'i', 'ệ', 't', ' ', 'N', 'a', 'm'])"# ); } @@ -1870,7 +1870,7 @@ mod pattern { } if let Some(err) = err { - panic!("Input skipped range at {}", err); + panic!("Input skipped range at {err}"); } if first_index != haystack.len() { @@ -2187,10 +2187,10 @@ fn utf8() { fn check_str_eq(a: String, b: String) { let mut i: isize = 0; for ab in a.bytes() { - println!("{}", i); - println!("{}", ab); + println!("{i}"); + println!("{ab}"); let bb: u8 = b.as_bytes()[i as usize]; - println!("{}", bb); + println!("{bb}"); assert_eq!(ab, bb); i += 1; } diff --git a/library/alloc/tests/string.rs b/library/alloc/tests/string.rs index 893283e5a2485..b6836fdc88ee8 100644 --- a/library/alloc/tests/string.rs +++ b/library/alloc/tests/string.rs @@ -470,7 +470,7 @@ fn test_simple_types() { #[test] fn test_vectors() { let x: Vec = vec![]; - assert_eq!(format!("{:?}", x), "[]"); + assert_eq!(format!("{x:?}"), "[]"); assert_eq!(format!("{:?}", vec![1]), "[1]"); assert_eq!(format!("{:?}", vec![1, 2, 3]), "[1, 2, 3]"); assert!(format!("{:?}", vec![vec![], vec![1], vec![1, 1]]) == "[[], [1], [1, 1]]"); @@ -871,6 +871,6 @@ fn test_from_char() { fn test_str_concat() { let a: String = "hello".to_string(); let b: String = "world".to_string(); - let s: String = format!("{}{}", a, b); + let s: String = format!("{a}{b}"); assert_eq!(s.as_bytes()[9], 'd' as u8); } diff --git a/library/alloc/tests/vec.rs b/library/alloc/tests/vec.rs index 705914b44971c..ca0fcc855c7b8 100644 --- a/library/alloc/tests/vec.rs +++ b/library/alloc/tests/vec.rs @@ -100,7 +100,7 @@ fn test_debug_fmt() { assert_eq!("[0, 1]", format!("{:?}", vec2)); let slice: &[isize] = &[4, 5]; - assert_eq!("[4, 5]", format!("{:?}", slice)); + assert_eq!("[4, 5]", format!("{slice:?}")); } #[test] @@ -918,7 +918,7 @@ fn test_into_iter_as_mut_slice() { fn test_into_iter_debug() { let vec = vec!['a', 'b', 'c']; let into_iter = vec.into_iter(); - let debug = format!("{:?}", into_iter); + let debug = format!("{into_iter:?}"); assert_eq!(debug, "IntoIter(['a', 'b', 'c'])"); } @@ -2336,7 +2336,7 @@ fn test_vec_dedup_panicking() { let ok = vec.iter().zip(expected.iter()).all(|(x, y)| x.index == y.index); if !ok { - panic!("expected: {:?}\ngot: {:?}\n", expected, vec); + panic!("expected: {expected:?}\ngot: {vec:?}\n"); } } diff --git a/library/alloc/tests/vec_deque.rs b/library/alloc/tests/vec_deque.rs index 18954f094c671..89cc7f905be2c 100644 --- a/library/alloc/tests/vec_deque.rs +++ b/library/alloc/tests/vec_deque.rs @@ -647,10 +647,10 @@ fn test_ord() { #[test] fn test_show() { let ringbuf: VecDeque<_> = (0..10).collect(); - assert_eq!(format!("{:?}", ringbuf), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); + assert_eq!(format!("{ringbuf:?}"), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); let ringbuf: VecDeque<_> = vec!["just", "one", "test", "more"].iter().cloned().collect(); - assert_eq!(format!("{:?}", ringbuf), "[\"just\", \"one\", \"test\", \"more\"]"); + assert_eq!(format!("{ringbuf:?}"), "[\"just\", \"one\", \"test\", \"more\"]"); } #[test] diff --git a/library/core/benches/num/flt2dec/mod.rs b/library/core/benches/num/flt2dec/mod.rs index a1ce33d0bb49e..32fd5e626bc1f 100644 --- a/library/core/benches/num/flt2dec/mod.rs +++ b/library/core/benches/num/flt2dec/mod.rs @@ -12,7 +12,7 @@ use test::Bencher; pub fn decode_finite(v: T) -> Decoded { match decode(v).1 { FullDecoded::Finite(decoded) => decoded, - full_decoded => panic!("expected finite, got {:?} instead", full_decoded), + full_decoded => panic!("expected finite, got {full_decoded:?} instead"), } } diff --git a/library/core/benches/num/flt2dec/strategy/grisu.rs b/library/core/benches/num/flt2dec/strategy/grisu.rs index 76425731e1ddd..8e47a046cdea5 100644 --- a/library/core/benches/num/flt2dec/strategy/grisu.rs +++ b/library/core/benches/num/flt2dec/strategy/grisu.rs @@ -6,7 +6,7 @@ use test::Bencher; pub fn decode_finite(v: T) -> Decoded { match decode(v).1 { FullDecoded::Finite(decoded) => decoded, - full_decoded => panic!("expected finite, got {:?} instead", full_decoded), + full_decoded => panic!("expected finite, got {full_decoded:?} instead"), } } diff --git a/library/core/src/any.rs b/library/core/src/any.rs index 72528185707a6..3b15ab1e6895b 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -62,7 +62,7 @@ //! println!("String ({}): {}", as_string.len(), as_string); //! } //! None => { -//! println!("{:?}", value); +//! println!("{value:?}"); //! } //! } //! } diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index aef7ad7756803..9dbb5eecd469b 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -85,7 +85,7 @@ //! // of scope then the subsequent borrow would cause a dynamic thread panic. //! // This is the major hazard of using `RefCell`. //! let total: i32 = shared_map.borrow().values().sum(); -//! println!("{}", total); +//! println!("{total}"); //! } //! ``` //! diff --git a/library/core/src/char/methods.rs b/library/core/src/char/methods.rs index c4c0a5a6c78ad..66de94d1b92dc 100644 --- a/library/core/src/char/methods.rs +++ b/library/core/src/char/methods.rs @@ -370,7 +370,7 @@ impl char { /// /// ``` /// for c in '❤'.escape_unicode() { - /// print!("{}", c); + /// print!("{c}"); /// } /// println!(); /// ``` @@ -448,7 +448,7 @@ impl char { /// /// ``` /// for c in '\n'.escape_debug() { - /// print!("{}", c); + /// print!("{c}"); /// } /// println!(); /// ``` @@ -504,7 +504,7 @@ impl char { /// /// ``` /// for c in '"'.escape_default() { - /// print!("{}", c); + /// print!("{c}"); /// } /// println!(); /// ``` @@ -949,7 +949,7 @@ impl char { /// /// ``` /// for c in 'İ'.to_lowercase() { - /// print!("{}", c); + /// print!("{c}"); /// } /// println!(); /// ``` @@ -1016,7 +1016,7 @@ impl char { /// /// ``` /// for c in 'ß'.to_uppercase() { - /// print!("{}", c); + /// print!("{c}"); /// } /// println!(); /// ``` diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index 90c5719f486cb..84cf1753f86ba 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -64,7 +64,7 @@ pub mod rt { /// /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 }; /// -/// assert_eq!(format!("{}", pythagorean_triple), "(3, 4, 5)"); +/// assert_eq!(format!("{pythagorean_triple}"), "(3, 4, 5)"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub type Result = result::Result<(), Error>; @@ -174,7 +174,7 @@ pub trait Write { /// use std::fmt::{Error, Write}; /// /// fn writer(f: &mut W, s: &str) -> Result<(), Error> { - /// f.write_fmt(format_args!("{}", s)) + /// f.write_fmt(format_args!("{s}")) /// } /// /// let mut buf = String::new(); @@ -562,7 +562,7 @@ impl Display for Arguments<'_> { /// /// let origin = Point { x: 0, y: 0 }; /// -/// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }"); +/// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }"); /// ``` /// /// Manually implementing: @@ -586,7 +586,7 @@ impl Display for Arguments<'_> { /// /// let origin = Point { x: 0, y: 0 }; /// -/// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }"); +/// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }"); /// ``` /// /// There are a number of helper methods on the [`Formatter`] struct to help you with manual @@ -627,7 +627,7 @@ impl Display for Arguments<'_> { /// /// let origin = Point { x: 0, y: 0 }; /// -/// assert_eq!(format!("The origin is: {:#?}", origin), +/// assert_eq!(format!("The origin is: {origin:#?}"), /// "The origin is: Point { /// x: 0, /// y: 0, @@ -670,9 +670,9 @@ pub trait Debug { /// } /// /// let position = Position { longitude: 1.987, latitude: 2.983 }; - /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)"); + /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)"); /// - /// assert_eq!(format!("{:#?}", position), "( + /// assert_eq!(format!("{position:#?}"), "( /// 1.987, /// 2.983, /// )"); @@ -724,7 +724,7 @@ pub use macros::Debug; /// /// let origin = Point { x: 0, y: 0 }; /// -/// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)"); +/// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)"); /// ``` #[rustc_on_unimplemented( on( @@ -786,8 +786,8 @@ pub trait Display { /// ``` /// let x = 42; // 42 is '52' in octal /// -/// assert_eq!(format!("{:o}", x), "52"); -/// assert_eq!(format!("{:#o}", x), "0o52"); +/// assert_eq!(format!("{x:o}"), "52"); +/// assert_eq!(format!("{x:#o}"), "0o52"); /// /// assert_eq!(format!("{:o}", -16), "37777777760"); /// ``` @@ -809,9 +809,9 @@ pub trait Display { /// /// let l = Length(9); /// -/// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11"); +/// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11"); /// -/// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011"); +/// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub trait Octal { @@ -840,8 +840,8 @@ pub trait Octal { /// ``` /// let x = 42; // 42 is '101010' in binary /// -/// assert_eq!(format!("{:b}", x), "101010"); -/// assert_eq!(format!("{:#b}", x), "0b101010"); +/// assert_eq!(format!("{x:b}"), "101010"); +/// assert_eq!(format!("{x:#b}"), "0b101010"); /// /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000"); /// ``` @@ -863,10 +863,10 @@ pub trait Octal { /// /// let l = Length(107); /// -/// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011"); +/// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011"); /// /// assert_eq!( -/// format!("l as binary is: {:#032b}", l), +/// format!("l as binary is: {l:#032b}"), /// "l as binary is: 0b000000000000000000000001101011" /// ); /// ``` @@ -898,8 +898,8 @@ pub trait Binary { /// ``` /// let x = 42; // 42 is '2a' in hex /// -/// assert_eq!(format!("{:x}", x), "2a"); -/// assert_eq!(format!("{:#x}", x), "0x2a"); +/// assert_eq!(format!("{x:x}"), "2a"); +/// assert_eq!(format!("{x:#x}"), "0x2a"); /// /// assert_eq!(format!("{:x}", -16), "fffffff0"); /// ``` @@ -921,9 +921,9 @@ pub trait Binary { /// /// let l = Length(9); /// -/// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9"); +/// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9"); /// -/// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009"); +/// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub trait LowerHex { @@ -953,8 +953,8 @@ pub trait LowerHex { /// ``` /// let x = 42; // 42 is '2A' in hex /// -/// assert_eq!(format!("{:X}", x), "2A"); -/// assert_eq!(format!("{:#X}", x), "0x2A"); +/// assert_eq!(format!("{x:X}"), "2A"); +/// assert_eq!(format!("{x:#X}"), "0x2A"); /// /// assert_eq!(format!("{:X}", -16), "FFFFFFF0"); /// ``` @@ -976,9 +976,9 @@ pub trait LowerHex { /// /// let l = Length(i32::MAX); /// -/// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF"); +/// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF"); /// -/// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF"); +/// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub trait UpperHex { @@ -1003,7 +1003,7 @@ pub trait UpperHex { /// ``` /// let x = &42; /// -/// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0' +/// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0' /// ``` /// /// Implementing `Pointer` on a type: @@ -1024,9 +1024,9 @@ pub trait UpperHex { /// /// let l = Length(42); /// -/// println!("l is in memory here: {:p}", l); +/// println!("l is in memory here: {l:p}"); /// -/// let l_ptr = format!("{:018p}", l); +/// let l_ptr = format!("{l:018p}"); /// assert_eq!(l_ptr.len(), 18); /// assert_eq!(&l_ptr[..2], "0x"); /// ``` @@ -1054,7 +1054,7 @@ pub trait Pointer { /// ``` /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation /// -/// assert_eq!(format!("{:e}", x), "4.2e1"); +/// assert_eq!(format!("{x:e}"), "4.2e1"); /// ``` /// /// Implementing `LowerExp` on a type: @@ -1074,12 +1074,12 @@ pub trait Pointer { /// let l = Length(100); /// /// assert_eq!( -/// format!("l in scientific notation is: {:e}", l), +/// format!("l in scientific notation is: {l:e}"), /// "l in scientific notation is: 1e2" /// ); /// /// assert_eq!( -/// format!("l in scientific notation is: {:05e}", l), +/// format!("l in scientific notation is: {l:05e}"), /// "l in scientific notation is: 001e2" /// ); /// ``` @@ -1105,7 +1105,7 @@ pub trait LowerExp { /// ``` /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation /// -/// assert_eq!(format!("{:E}", x), "4.2E1"); +/// assert_eq!(format!("{x:E}"), "4.2E1"); /// ``` /// /// Implementing `UpperExp` on a type: @@ -1125,12 +1125,12 @@ pub trait LowerExp { /// let l = Length(100); /// /// assert_eq!( -/// format!("l in scientific notation is: {:E}", l), +/// format!("l in scientific notation is: {l:E}"), /// "l in scientific notation is: 1E2" /// ); /// /// assert_eq!( -/// format!("l in scientific notation is: {:05E}", l), +/// format!("l in scientific notation is: {l:05E}"), /// "l in scientific notation is: 001E2" /// ); /// ``` @@ -1429,8 +1429,8 @@ impl<'a> Formatter<'a> { /// } /// } /// - /// assert_eq!(&format!("{:<4}", Foo), "Foo "); - /// assert_eq!(&format!("{:0>4}", Foo), "0Foo"); + /// assert_eq!(&format!("{Foo:<4}"), "Foo "); + /// assert_eq!(&format!("{Foo:0>4}"), "0Foo"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn pad(&mut self, s: &str) -> Result { @@ -1613,8 +1613,8 @@ impl<'a> Formatter<'a> { /// } /// } /// - /// assert_eq!(&format!("{}", Foo), "Foo"); - /// assert_eq!(&format!("{:0>8}", Foo), "Foo"); + /// assert_eq!(&format!("{Foo}"), "Foo"); + /// assert_eq!(&format!("{Foo:0>8}"), "Foo"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn write_str(&mut self, data: &str) -> Result { @@ -1670,18 +1670,18 @@ impl<'a> Formatter<'a> { /// let c = formatter.fill(); /// if let Some(width) = formatter.width() { /// for _ in 0..width { - /// write!(formatter, "{}", c)?; + /// write!(formatter, "{c}")?; /// } /// Ok(()) /// } else { - /// write!(formatter, "{}", c) + /// write!(formatter, "{c}") /// } /// } /// } /// /// // We set alignment to the right with ">". - /// assert_eq!(&format!("{:G>3}", Foo), "GGG"); - /// assert_eq!(&format!("{:t>6}", Foo), "tttttt"); + /// assert_eq!(&format!("{Foo:G>3}"), "GGG"); + /// assert_eq!(&format!("{Foo:t>6}"), "tttttt"); /// ``` #[must_use] #[stable(feature = "fmt_flags", since = "1.5.0")] @@ -1711,14 +1711,14 @@ impl<'a> Formatter<'a> { /// } else { /// "into the void" /// }; - /// write!(formatter, "{}", s) + /// write!(formatter, "{s}") /// } /// } /// - /// assert_eq!(&format!("{:<}", Foo), "left"); - /// assert_eq!(&format!("{:>}", Foo), "right"); - /// assert_eq!(&format!("{:^}", Foo), "center"); - /// assert_eq!(&format!("{}", Foo), "into the void"); + /// assert_eq!(&format!("{Foo:<}"), "left"); + /// assert_eq!(&format!("{Foo:>}"), "right"); + /// assert_eq!(&format!("{Foo:^}"), "center"); + /// assert_eq!(&format!("{Foo}"), "into the void"); /// ``` #[must_use] #[stable(feature = "fmt_flags_align", since = "1.28.0")] diff --git a/library/core/src/iter/adapters/map.rs b/library/core/src/iter/adapters/map.rs index d2077a63e150a..4b03449972c9a 100644 --- a/library/core/src/iter/adapters/map.rs +++ b/library/core/src/iter/adapters/map.rs @@ -34,7 +34,7 @@ use crate::ops::Try; /// /// for pair in ['a', 'b', 'c'].into_iter() /// .map(|letter| { c += 1; (letter, c) }) { -/// println!("{:?}", pair); +/// println!("{pair:?}"); /// } /// ``` /// @@ -52,7 +52,7 @@ use crate::ops::Try; /// for pair in ['a', 'b', 'c'].into_iter() /// .map(|letter| { c += 1; (letter, c) }) /// .rev() { -/// println!("{:?}", pair); +/// println!("{pair:?}"); /// } /// ``` #[must_use = "iterators are lazy and do nothing unless consumed"] diff --git a/library/core/src/iter/mod.rs b/library/core/src/iter/mod.rs index 65f56f64dbfa6..5a987733134a4 100644 --- a/library/core/src/iter/mod.rs +++ b/library/core/src/iter/mod.rs @@ -144,7 +144,7 @@ //! let values = vec![1, 2, 3, 4, 5]; //! //! for x in values { -//! println!("{}", x); +//! println!("{x}"); //! } //! ``` //! @@ -164,7 +164,7 @@ //! let values = vec![1, 2, 3, 4, 5]; //! //! for x in values { -//! println!("{}", x); +//! println!("{x}"); //! } //! ``` //! @@ -181,7 +181,7 @@ //! None => break, //! }; //! let x = next; -//! let () = { println!("{}", x); }; +//! let () = { println!("{x}"); }; //! }, //! }; //! result @@ -280,7 +280,7 @@ //! ``` //! # #![allow(unused_must_use)] //! let v = vec![1, 2, 3, 4, 5]; -//! v.iter().map(|x| println!("{}", x)); +//! v.iter().map(|x| println!("{x}")); //! ``` //! //! This will not print any values, as we only created an iterator, rather than @@ -297,10 +297,10 @@ //! ``` //! let v = vec![1, 2, 3, 4, 5]; //! -//! v.iter().for_each(|x| println!("{}", x)); +//! v.iter().for_each(|x| println!("{x}")); //! // or //! for x in &v { -//! println!("{}", x); +//! println!("{x}"); //! } //! ``` //! @@ -329,7 +329,7 @@ //! let five_numbers = numbers.take(5); //! //! for number in five_numbers { -//! println!("{}", number); +//! println!("{number}"); //! } //! ``` //! @@ -345,7 +345,7 @@ //! let ones = std::iter::repeat(1); //! let least = ones.min().unwrap(); // Oh no! An infinite loop! //! // `ones.min()` causes an infinite loop, so we won't reach this point! -//! println!("The smallest number one is {}.", least); +//! println!("The smallest number one is {least}."); //! ``` //! //! [`take`]: Iterator::take diff --git a/library/core/src/iter/sources/once.rs b/library/core/src/iter/sources/once.rs index 27bc3dcfd79e0..6e9ed0d3c5278 100644 --- a/library/core/src/iter/sources/once.rs +++ b/library/core/src/iter/sources/once.rs @@ -48,7 +48,7 @@ use crate::iter::{FusedIterator, TrustedLen}; /// /// // this will give us all of the files in .foo as well as .foorc /// for f in files { -/// println!("{:?}", f); +/// println!("{f:?}"); /// } /// ``` #[stable(feature = "iter_once", since = "1.2.0")] diff --git a/library/core/src/iter/sources/once_with.rs b/library/core/src/iter/sources/once_with.rs index cf6a3c1152452..d79f85c2559fe 100644 --- a/library/core/src/iter/sources/once_with.rs +++ b/library/core/src/iter/sources/once_with.rs @@ -52,7 +52,7 @@ use crate::iter::{FusedIterator, TrustedLen}; /// /// // this will give us all of the files in .foo as well as .foorc /// for f in files { -/// println!("{:?}", f); +/// println!("{f:?}"); /// } /// ``` #[inline] diff --git a/library/core/src/iter/traits/collect.rs b/library/core/src/iter/traits/collect.rs index 637d7bc44885e..31ce4a895e1bc 100644 --- a/library/core/src/iter/traits/collect.rs +++ b/library/core/src/iter/traits/collect.rs @@ -214,7 +214,7 @@ pub trait FromIterator: Sized { /// { /// collection /// .into_iter() -/// .map(|item| format!("{:?}", item)) +/// .map(|item| format!("{item:?}")) /// .collect() /// } /// ``` @@ -332,7 +332,7 @@ impl IntoIterator for I { /// c.extend(vec![1, 2, 3]); /// /// // we've added these elements onto the end -/// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c)); +/// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{c:?}")); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub trait Extend { diff --git a/library/core/src/iter/traits/double_ended.rs b/library/core/src/iter/traits/double_ended.rs index a6aed6d210beb..bdf94c792c27c 100644 --- a/library/core/src/iter/traits/double_ended.rs +++ b/library/core/src/iter/traits/double_ended.rs @@ -281,7 +281,7 @@ pub trait DoubleEndedIterator: Iterator { /// let zero = "0".to_string(); /// /// let result = numbers.iter().rfold(zero, |acc, &x| { - /// format!("({} + {})", x, acc) + /// format!("({x} + {acc})") /// }); /// /// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))"); diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index c35d0784dd5a4..d980f5930810b 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -709,13 +709,13 @@ pub trait Iterator { /// ``` /// # #![allow(unused_must_use)] /// // don't do this: - /// (0..5).map(|x| println!("{}", x)); + /// (0..5).map(|x| println!("{x}")); /// /// // it won't even execute, as it is lazy. Rust will warn you about this. /// /// // Instead, use for: /// for x in 0..5 { - /// println!("{}", x); + /// println!("{x}"); /// } /// ``` #[inline] @@ -761,7 +761,7 @@ pub trait Iterator { /// (0..5).flat_map(|x| x * 100 .. x * 110) /// .enumerate() /// .filter(|&(i, x)| (i + x) % 3 == 0) - /// .for_each(|(i, x)| println!("{}:{}", i, x)); + /// .for_each(|(i, x)| println!("{i}:{x}")); /// ``` #[inline] #[stable(feature = "iterator_for_each", since = "1.21.0")] @@ -1575,17 +1575,17 @@ pub trait Iterator { /// .filter(|x| x % 2 == 0) /// .fold(0, |sum, i| sum + i); /// - /// println!("{}", sum); + /// println!("{sum}"); /// /// // let's add some inspect() calls to investigate what's happening /// let sum = a.iter() /// .cloned() - /// .inspect(|x| println!("about to filter: {}", x)) + /// .inspect(|x| println!("about to filter: {x}")) /// .filter(|x| x % 2 == 0) - /// .inspect(|x| println!("made it through filter: {}", x)) + /// .inspect(|x| println!("made it through filter: {x}")) /// .fold(0, |sum, i| sum + i); /// - /// println!("{}", sum); + /// println!("{sum}"); /// ``` /// /// This will print: @@ -1611,13 +1611,13 @@ pub trait Iterator { /// .map(|line| line.parse::()) /// .inspect(|num| { /// if let Err(ref e) = *num { - /// println!("Parsing error: {}", e); + /// println!("Parsing error: {e}"); /// } /// }) /// .filter_map(Result::ok) /// .sum(); /// - /// println!("Sum: {}", sum); + /// println!("Sum: {sum}"); /// ``` /// /// This will print: @@ -2205,7 +2205,7 @@ pub trait Iterator { /// /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"]; /// - /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x)); + /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}")); /// assert!(res.is_ok()); /// /// let mut it = data.iter().cloned(); @@ -2319,7 +2319,7 @@ pub trait Iterator { /// let zero = "0".to_string(); /// /// let result = numbers.iter().fold(zero, |acc, &x| { - /// format!("({} + {})", acc, x) + /// format!("({acc} + {x})") /// }); /// /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)"); diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index 65a2c3ff6edc9..ba7ae55ec6f4b 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -895,7 +895,7 @@ pub(crate) mod builtin { /// /// ``` /// let path: &'static str = env!("PATH"); - /// println!("the $PATH variable at the time of compiling was: {}", path); + /// println!("the $PATH variable at the time of compiling was: {path}"); /// ``` /// /// You can customize the error message by passing a string as the second @@ -935,7 +935,7 @@ pub(crate) mod builtin { /// /// ``` /// let key: Option<&'static str> = option_env!("SECRET_KEY"); - /// println!("the secret key might be: {:?}", key); + /// println!("the secret key might be: {key:?}"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_builtin_macro] @@ -1046,7 +1046,7 @@ pub(crate) mod builtin { /// /// ``` /// let current_line = line!(); - /// println!("defined on line: {}", current_line); + /// println!("defined on line: {current_line}"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_builtin_macro] @@ -1074,7 +1074,7 @@ pub(crate) mod builtin { /// /// ``` /// let current_col = column!(); - /// println!("defined on column: {}", current_col); + /// println!("defined on column: {current_col}"); /// ``` /// /// `column!` counts Unicode code points, not bytes or graphemes. As a result, the first two @@ -1112,7 +1112,7 @@ pub(crate) mod builtin { /// /// ``` /// let this_file = file!(); - /// println!("defined in file: {}", this_file); + /// println!("defined in file: {this_file}"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_builtin_macro] @@ -1176,7 +1176,7 @@ pub(crate) mod builtin { /// fn main() { /// let my_str = include_str!("spanish.in"); /// assert_eq!(my_str, "adiós\n"); - /// print!("{}", my_str); + /// print!("{my_str}"); /// } /// ``` /// @@ -1325,7 +1325,7 @@ pub(crate) mod builtin { /// fn main() { /// let my_string = include!("monkeys.in"); /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string); - /// println!("{}", my_string); + /// println!("{my_string}"); /// } /// ``` /// diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index 71eea43aa54e1..82bac2640b405 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -219,7 +219,7 @@ pub trait StructuralEq { /// /// // `x` has moved into `y`, and so cannot be used /// -/// // println!("{:?}", x); // error: use of moved value +/// // println!("{x:?}"); // error: use of moved value /// ``` /// /// However, if a type implements `Copy`, it instead has 'copy semantics': @@ -236,7 +236,7 @@ pub trait StructuralEq { /// /// // `y` is a copy of `x` /// -/// println!("{:?}", x); // A-OK! +/// println!("{x:?}"); // A-OK! /// ``` /// /// It's important to note that in these two examples, the only difference is whether you diff --git a/library/core/src/num/dec2flt/mod.rs b/library/core/src/num/dec2flt/mod.rs index 2b280773e4c50..d45ba595f1bae 100644 --- a/library/core/src/num/dec2flt/mod.rs +++ b/library/core/src/num/dec2flt/mod.rs @@ -163,7 +163,7 @@ from_str_float_impl!(f64); /// use std::str::FromStr; /// /// if let Err(e) = f64::from_str("a.12") { -/// println!("Failed conversion to f64: {}", e); +/// println!("Failed conversion to f64: {e}"); /// } /// ``` #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/library/core/src/num/error.rs b/library/core/src/num/error.rs index 8a9ecbe98dff6..1a223016dae0f 100644 --- a/library/core/src/num/error.rs +++ b/library/core/src/num/error.rs @@ -61,7 +61,7 @@ impl const From for TryFromIntError { /// /// ``` /// if let Err(e) = i32::from_str_radix("a12", 10) { -/// println!("Failed conversion to i32: {}", e); +/// println!("Failed conversion to i32: {e}"); /// } /// ``` #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/library/core/src/ops/index.rs b/library/core/src/ops/index.rs index 964378cc9c3c6..e2e569cb7ea81 100644 --- a/library/core/src/ops/index.rs +++ b/library/core/src/ops/index.rs @@ -106,7 +106,7 @@ pub trait Index { /// type Output = Weight; /// /// fn index(&self, index: Side) -> &Self::Output { -/// println!("Accessing {:?}-side of balance immutably", index); +/// println!("Accessing {index:?}-side of balance immutably"); /// match index { /// Side::Left => &self.left, /// Side::Right => &self.right, @@ -116,7 +116,7 @@ pub trait Index { /// /// impl IndexMut for Balance { /// fn index_mut(&mut self, index: Side) -> &mut Self::Output { -/// println!("Accessing {:?}-side of balance mutably", index); +/// println!("Accessing {index:?}-side of balance mutably"); /// match index { /// Side::Left => &mut self.left, /// Side::Right => &mut self.right, diff --git a/library/core/src/ops/range.rs b/library/core/src/ops/range.rs index 5029e0560b892..a3b14847342cb 100644 --- a/library/core/src/ops/range.rs +++ b/library/core/src/ops/range.rs @@ -653,7 +653,7 @@ impl> RangeToInclusive { /// map.insert(8, "c"); /// /// for (key, value) in map.range((Excluded(3), Included(8))) { -/// println!("{}: {}", key, value); +/// println!("{key}: {value}"); /// } /// /// assert_eq!(Some((&3, &"a")), map.range((Unbounded, Included(5))).next()); diff --git a/library/core/src/option.rs b/library/core/src/option.rs index a6286f8d8d103..7d0c375cd4f5f 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -34,7 +34,7 @@ //! // Pattern match to retrieve the value //! match result { //! // The division was valid -//! Some(x) => println!("Result: {}", x), +//! Some(x) => println!("Result: {x}"), //! // The division was invalid //! None => println!("Cannot divide by 0"), //! } @@ -66,7 +66,7 @@ //! //! fn check_optional(optional: Option>) { //! match optional { -//! Some(p) => println!("has value {}", p), +//! Some(p) => println!("has value {p}"), //! None => println!("has no value"), //! } //! } @@ -493,7 +493,7 @@ //! } //! //! match name_of_biggest_animal { -//! Some(name) => println!("the biggest animal is {}", name), +//! Some(name) => println!("the biggest animal is {name}"), //! None => println!("there are no animals :("), //! } //! ``` @@ -615,7 +615,7 @@ impl Option { /// // First, cast `Option` to `Option<&String>` with `as_ref`, /// // then consume *that* with `map`, leaving `text` on the stack. /// let text_length: Option = text.as_ref().map(|s| s.len()); - /// println!("still can print text: {:?}", text); + /// println!("still can print text: {text:?}"); /// ``` #[inline] #[rustc_const_stable(feature = "const_option", since = "1.48.0")] @@ -918,10 +918,10 @@ impl Option { /// let v = vec![1, 2, 3, 4, 5]; /// /// // prints "got: 4" - /// let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {}", x)); + /// let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {x}")); /// /// // prints nothing - /// let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {}", x)); + /// let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {x}")); /// ``` #[inline] #[unstable(feature = "result_option_inspect", issue = "91345")] @@ -1976,7 +1976,7 @@ impl<'a, T> const From<&'a Option> for Option<&'a T> { /// let s: Option = Some(String::from("Hello, Rustaceans!")); /// let o: Option = Option::from(&s).map(|ss: &String| ss.len()); /// - /// println!("Can still print s: {:?}", s); + /// println!("Can still print s: {s:?}"); /// /// assert_eq!(o, Some(18)); /// ``` diff --git a/library/core/src/panic/panic_info.rs b/library/core/src/panic/panic_info.rs index be8598fae09d7..1923155ebc15f 100644 --- a/library/core/src/panic/panic_info.rs +++ b/library/core/src/panic/panic_info.rs @@ -16,7 +16,7 @@ use crate::panic::Location; /// /// panic::set_hook(Box::new(|panic_info| { /// if let Some(s) = panic_info.payload().downcast_ref::<&str>() { -/// println!("panic occurred: {:?}", s); +/// println!("panic occurred: {s:?}"); /// } else { /// println!("panic occurred"); /// } @@ -75,7 +75,7 @@ impl<'a> PanicInfo<'a> { /// /// panic::set_hook(Box::new(|panic_info| { /// if let Some(s) = panic_info.payload().downcast_ref::<&str>() { - /// println!("panic occurred: {:?}", s); + /// println!("panic occurred: {s:?}"); /// } else { /// println!("panic occurred"); /// } diff --git a/library/core/src/panicking.rs b/library/core/src/panicking.rs index 89cebaa653f4b..a908b1f3ba4ce 100644 --- a/library/core/src/panicking.rs +++ b/library/core/src/panicking.rs @@ -39,7 +39,7 @@ use crate::panic::{Location, PanicInfo}; #[rustc_const_unstable(feature = "core_panic", issue = "none")] #[lang = "panic"] // needed by codegen for panic on overflow and other `Assert` MIR terminators pub const fn panic(expr: &'static str) -> ! { - // Use Arguments::new_v1 instead of format_args!("{}", expr) to potentially + // Use Arguments::new_v1 instead of format_args!("{expr}") to potentially // reduce size overhead. The format_args! macro uses str's Display trait to // write expr, which calls Formatter::pad, which must accommodate string // truncation and padding (even though none is used here). Using @@ -81,7 +81,7 @@ fn panic_bounds_check(index: usize, len: usize) -> ! { super::intrinsics::abort() } - panic!("index out of bounds: the len is {} but the index is {}", len, index) + panic!("index out of bounds: the len is {len} but the index is {index}") } // This function is called directly by the codegen backend, and must not have diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index ebb1d8971b99d..225a679efd221 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -607,7 +607,7 @@ mod prim_pointer {} /// /// // This loop prints: 0 1 2 /// for x in array { -/// print!("{} ", x); +/// print!("{x} "); /// } /// ``` /// @@ -646,19 +646,19 @@ mod prim_pointer {} /// // This creates a slice iterator, producing references to each value. /// for item in array.into_iter().enumerate() { /// let (i, x): (usize, &i32) = item; -/// println!("array[{}] = {}", i, x); +/// println!("array[{i}] = {x}"); /// } /// /// // The `array_into_iter` lint suggests this change for future compatibility: /// for item in array.iter().enumerate() { /// let (i, x): (usize, &i32) = item; -/// println!("array[{}] = {}", i, x); +/// println!("array[{i}] = {x}"); /// } /// /// // You can explicitly iterate an array by value using `IntoIterator::into_iter` /// for item in IntoIterator::into_iter(array).enumerate() { /// let (i, x): (usize, i32) = item; -/// println!("array[{}] = {}", i, x); +/// println!("array[{i}] = {x}"); /// } /// ``` /// @@ -673,13 +673,13 @@ mod prim_pointer {} /// // This iterates by reference: /// for item in array.iter().enumerate() { /// let (i, x): (usize, &i32) = item; -/// println!("array[{}] = {}", i, x); +/// println!("array[{i}] = {x}"); /// } /// /// // This iterates by value: /// for item in array.into_iter().enumerate() { /// let (i, x): (usize, i32) = item; -/// println!("array[{}] = {}", i, x); +/// println!("array[{i}] = {x}"); /// } /// ``` /// @@ -702,26 +702,26 @@ mod prim_pointer {} /// // This iterates by reference: /// for item in array.iter() { /// let x: &i32 = item; -/// println!("{}", x); +/// println!("{x}"); /// } /// /// // This iterates by value: /// for item in IntoIterator::into_iter(array) { /// let x: i32 = item; -/// println!("{}", x); +/// println!("{x}"); /// } /// /// // This iterates by value: /// for item in array { /// let x: i32 = item; -/// println!("{}", x); +/// println!("{x}"); /// } /// /// // IntoIter can also start a chain. /// // This iterates by value: /// for item in IntoIterator::into_iter(array).enumerate() { /// let (i, x): (usize, i32) = item; -/// println!("array[{}] = {}", i, x); +/// println!("array[{i}] = {x}"); /// } /// ``` /// diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index ee544b4842e86..753220669831f 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -153,7 +153,7 @@ impl *const T { /// /// unsafe { /// if let Some(val_back) = ptr.as_ref() { - /// println!("We got back the value: {}!", val_back); + /// println!("We got back the value: {val_back}!"); /// } /// } /// ``` @@ -169,7 +169,7 @@ impl *const T { /// /// unsafe { /// let val_back = &*ptr; - /// println!("We got back the value: {}!", val_back); + /// println!("We got back the value: {val_back}!"); /// } /// ``` #[stable(feature = "ptr_as_ref", since = "1.9.0")] diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index 3374b48c88c6b..861412703d3c6 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -160,7 +160,7 @@ impl *mut T { /// /// unsafe { /// if let Some(val_back) = ptr.as_ref() { - /// println!("We got back the value: {}!", val_back); + /// println!("We got back the value: {val_back}!"); /// } /// } /// ``` @@ -176,7 +176,7 @@ impl *mut T { /// /// unsafe { /// let val_back = &*ptr; - /// println!("We got back the value: {}!", val_back); + /// println!("We got back the value: {val_back}!"); /// } /// ``` #[stable(feature = "ptr_as_ref", since = "1.9.0")] @@ -409,7 +409,7 @@ impl *mut T { /// let first_value = unsafe { ptr.as_mut().unwrap() }; /// *first_value = 4; /// # assert_eq!(s, [4, 2, 3]); - /// println!("{:?}", s); // It'll print: "[4, 2, 3]". + /// println!("{s:?}"); // It'll print: "[4, 2, 3]". /// ``` /// /// # Null-unchecked version @@ -424,7 +424,7 @@ impl *mut T { /// let first_value = unsafe { &mut *ptr }; /// *first_value = 4; /// # assert_eq!(s, [4, 2, 3]); - /// println!("{:?}", s); // It'll print: "[4, 2, 3]". + /// println!("{s:?}"); // It'll print: "[4, 2, 3]". /// ``` #[stable(feature = "ptr_as_ref", since = "1.9.0")] #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")] diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index c744ad5dd2deb..a698aec51ca71 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -314,7 +314,7 @@ impl NonNull { /// let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!"); /// /// let ref_x = unsafe { ptr.as_ref() }; - /// println!("{}", ref_x); + /// println!("{ref_x}"); /// ``` /// /// [the module documentation]: crate::ptr#safety diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 5a189f2b09811..2d739bf295b92 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -35,8 +35,8 @@ //! //! let version = parse_version(&[1, 2, 3, 4]); //! match version { -//! Ok(v) => println!("working with version: {:?}", v), -//! Err(e) => println!("error parsing header: {:?}", e), +//! Ok(v) => println!("working with version: {v:?}"), +//! Err(e) => println!("error parsing header: {e:?}"), //! } //! ``` //! @@ -447,9 +447,9 @@ //! .collect(); //! assert_eq!(errs.len(), 3); //! assert_eq!(nums, [17, 99]); -//! println!("results {:?}", results); -//! println!("errs {:?}", errs); -//! println!("nums {:?}", nums); +//! println!("results {results:?}"); +//! println!("errs {errs:?}"); +//! println!("nums {nums:?}"); //! ``` //! //! ## Collecting into `Result` @@ -756,7 +756,7 @@ impl Result { /// /// for num in line.lines() { /// match num.parse::().map(|i| i * 2) { - /// Ok(n) => println!("{}", n), + /// Ok(n) => println!("{n}"), /// Err(..) => {} /// } /// } @@ -838,7 +838,7 @@ impl Result { /// Basic usage: /// /// ``` - /// fn stringify(x: u32) -> String { format!("error code: {}", x) } + /// fn stringify(x: u32) -> String { format!("error code: {x}") } /// /// let x: Result = Ok(2); /// assert_eq!(x.map_err(stringify), Ok(2)); @@ -864,7 +864,7 @@ impl Result { /// /// let x: u8 = "4" /// .parse::() - /// .inspect(|x| println!("original: {}", x)) + /// .inspect(|x| println!("original: {x}")) /// .map(|x| x.pow(3)) /// .expect("failed to parse number"); /// ``` @@ -889,7 +889,7 @@ impl Result { /// /// fn read() -> io::Result { /// fs::read_to_string("address.txt") - /// .inspect_err(|e| eprintln!("failed to read file: {}", e)) + /// .inspect_err(|e| eprintln!("failed to read file: {e}")) /// } /// ``` #[inline] @@ -1198,7 +1198,7 @@ impl Result { /// } /// /// let s: String = only_good_news().into_ok(); - /// println!("{}", s); + /// println!("{s}"); /// ``` #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] #[inline] @@ -1235,7 +1235,7 @@ impl Result { /// } /// /// let error: String = only_bad_news().into_err(); - /// println!("{}", error); + /// println!("{error}"); /// ``` #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] #[inline] @@ -1781,7 +1781,7 @@ impl Result { #[cold] #[track_caller] fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! { - panic!("{}: {:?}", msg, error) + panic!("{msg}: {error:?}") } // This is a separate function to avoid constructing a `dyn Debug` diff --git a/library/core/src/slice/index.rs b/library/core/src/slice/index.rs index 7e6fbbe353889..3353c239866af 100644 --- a/library/core/src/slice/index.rs +++ b/library/core/src/slice/index.rs @@ -48,7 +48,7 @@ const fn slice_start_index_len_fail(index: usize, len: usize) -> ! { // FIXME const-hack fn slice_start_index_len_fail_rt(index: usize, len: usize) -> ! { - panic!("range start index {} out of range for slice of length {}", index, len); + panic!("range start index {index} out of range for slice of length {len}"); } const fn slice_start_index_len_fail_ct(_: usize, _: usize) -> ! { @@ -69,7 +69,7 @@ const fn slice_end_index_len_fail(index: usize, len: usize) -> ! { // FIXME const-hack fn slice_end_index_len_fail_rt(index: usize, len: usize) -> ! { - panic!("range end index {} out of range for slice of length {}", index, len); + panic!("range end index {index} out of range for slice of length {len}"); } const fn slice_end_index_len_fail_ct(_: usize, _: usize) -> ! { @@ -88,7 +88,7 @@ const fn slice_index_order_fail(index: usize, end: usize) -> ! { // FIXME const-hack fn slice_index_order_fail_rt(index: usize, end: usize) -> ! { - panic!("slice index starts at {} but ends at {}", index, end); + panic!("slice index starts at {index} but ends at {end}"); } const fn slice_index_order_fail_ct(_: usize, _: usize) -> ! { diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs index d260cc69469cf..82bd7dbcf6cd2 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -55,7 +55,7 @@ fn size_from_ptr(_: *const T) -> usize { /// /// // Then, we iterate over it: /// for element in slice.iter() { -/// println!("{}", element); +/// println!("{element}"); /// } /// ``` /// @@ -176,7 +176,7 @@ impl AsRef<[T]> for Iter<'_, T> { /// } /// /// // We now have "[2, 3, 4]": -/// println!("{:?}", slice); +/// println!("{slice:?}"); /// ``` /// /// [`iter_mut`]: slice::iter_mut @@ -266,7 +266,7 @@ impl<'a, T> IterMut<'a, T> { /// *iter.next().unwrap() += 1; /// } /// // Now slice is "[2, 2, 3]": - /// println!("{:?}", slice); + /// println!("{slice:?}"); /// ``` #[must_use = "`self` will be dropped if the result is not used"] #[stable(feature = "iter_to_slice", since = "1.4.0")] diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 7311fe40e04d6..166b343437246 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -2012,7 +2012,7 @@ impl [T] { /// let v = [10, 40, 30, 20, 60, 50]; /// /// for group in v.splitn(2, |num| *num % 3 == 0) { - /// println!("{:?}", group); + /// println!("{group:?}"); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -2067,7 +2067,7 @@ impl [T] { /// let v = [10, 40, 30, 20, 60, 50]; /// /// for group in v.rsplitn(2, |num| *num % 3 == 0) { - /// println!("{:?}", group); + /// println!("{group:?}"); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index f66bab999a98a..b1d36f2710737 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -104,7 +104,7 @@ fn slice_error_fail_rt(s: &str, begin: usize, end: usize) -> ! { // 1. out of bounds if begin > s.len() || end > s.len() { let oob_index = if begin > s.len() { begin } else { end }; - panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis); + panic!("byte index {oob_index} is out of bounds of `{s_trunc}`{ellipsis}"); } // 2. begin <= end @@ -2446,7 +2446,7 @@ impl str { /// /// ``` /// for c in "❤\n!".escape_debug() { - /// print!("{}", c); + /// print!("{c}"); /// } /// println!(); /// ``` @@ -2492,7 +2492,7 @@ impl str { /// /// ``` /// for c in "❤\n!".escape_default() { - /// print!("{}", c); + /// print!("{c}"); /// } /// println!(); /// ``` @@ -2530,7 +2530,7 @@ impl str { /// /// ``` /// for c in "❤\n!".escape_unicode() { - /// print!("{}", c); + /// print!("{c}"); /// } /// println!(); /// ``` diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 2da04ab2cea7d..62103f5b075ae 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -94,7 +94,7 @@ //! } //! //! if let Err(panic) = thread.join() { -//! println!("Thread had an error: {:?}", panic); +//! println!("Thread had an error: {panic:?}"); //! } //! } //! ``` @@ -1345,7 +1345,7 @@ impl const From for AtomicBool { /// ``` /// use std::sync::atomic::AtomicBool; /// let atomic_bool = AtomicBool::from(true); - /// assert_eq!(format!("{:?}", atomic_bool), "true") + /// assert_eq!(format!("{atomic_bool:?}"), "true") /// ``` #[inline] fn from(b: bool) -> Self { diff --git a/library/core/src/time.rs b/library/core/src/time.rs index 243c044b5d9d0..bd72d82b71c00 100644 --- a/library/core/src/time.rs +++ b/library/core/src/time.rs @@ -1214,7 +1214,7 @@ impl fmt::Debug for Duration { /// use std::time::Duration; /// /// if let Err(e) = Duration::try_from_secs_f32(-1.0) { -/// println!("Failed conversion to Duration: {}", e); +/// println!("Failed conversion to Duration: {e}"); /// } /// ``` #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/library/core/src/unit.rs b/library/core/src/unit.rs index f41f4a5e94a76..6656dd5c40beb 100644 --- a/library/core/src/unit.rs +++ b/library/core/src/unit.rs @@ -9,7 +9,7 @@ use crate::iter::FromIterator; /// use std::io::*; /// let data = vec![1, 2, 3, 4, 5]; /// let res: Result<()> = data.iter() -/// .map(|x| writeln!(stdout(), "{}", x)) +/// .map(|x| writeln!(stdout(), "{x}")) /// .collect(); /// assert!(res.is_ok()); /// ``` diff --git a/library/core/tests/any.rs b/library/core/tests/any.rs index b36d6f0d40405..eccddcbbf59fe 100644 --- a/library/core/tests/any.rs +++ b/library/core/tests/any.rs @@ -46,12 +46,12 @@ fn any_downcast_ref() { match a.downcast_ref::() { Some(&5) => {} - x => panic!("Unexpected value {:?}", x), + x => panic!("Unexpected value {x:?}"), } match a.downcast_ref::() { None => {} - x => panic!("Unexpected value {:?}", x), + x => panic!("Unexpected value {x:?}"), } } @@ -69,7 +69,7 @@ fn any_downcast_mut() { assert_eq!(*x, 5); *x = 612; } - x => panic!("Unexpected value {:?}", x), + x => panic!("Unexpected value {x:?}"), } match b_r.downcast_mut::() { @@ -77,27 +77,27 @@ fn any_downcast_mut() { assert_eq!(*x, 7); *x = 413; } - x => panic!("Unexpected value {:?}", x), + x => panic!("Unexpected value {x:?}"), } match a_r.downcast_mut::() { None => (), - x => panic!("Unexpected value {:?}", x), + x => panic!("Unexpected value {x:?}"), } match b_r.downcast_mut::() { None => (), - x => panic!("Unexpected value {:?}", x), + x => panic!("Unexpected value {x:?}"), } match a_r.downcast_mut::() { Some(&mut 612) => {} - x => panic!("Unexpected value {:?}", x), + x => panic!("Unexpected value {x:?}"), } match b_r.downcast_mut::() { Some(&mut 413) => {} - x => panic!("Unexpected value {:?}", x), + x => panic!("Unexpected value {x:?}"), } } diff --git a/library/core/tests/cell.rs b/library/core/tests/cell.rs index 4707cc7076ec0..f15e03076caf7 100644 --- a/library/core/tests/cell.rs +++ b/library/core/tests/cell.rs @@ -62,10 +62,10 @@ fn cell_update() { #[test] fn cell_has_sensible_show() { let x = Cell::new("foo bar"); - assert!(format!("{:?}", x).contains(x.get())); + assert!(format!("{x:?}").contains(x.get())); x.set("baz qux"); - assert!(format!("{:?}", x).contains(x.get())); + assert!(format!("{x:?}").contains(x.get())); } #[test] @@ -73,11 +73,11 @@ fn ref_and_refmut_have_sensible_show() { let refcell = RefCell::new("foo"); let refcell_refmut = refcell.borrow_mut(); - assert!(format!("{:?}", refcell_refmut).contains("foo")); + assert!(format!("{refcell_refmut:?}").contains("foo")); drop(refcell_refmut); let refcell_ref = refcell.borrow(); - assert!(format!("{:?}", refcell_ref).contains("foo")); + assert!(format!("{refcell_ref:?}").contains("foo")); drop(refcell_ref); } diff --git a/library/core/tests/fmt/builders.rs b/library/core/tests/fmt/builders.rs index 9567479c8137b..487ce46be28d7 100644 --- a/library/core/tests/fmt/builders.rs +++ b/library/core/tests/fmt/builders.rs @@ -11,8 +11,8 @@ mod debug_struct { } } - assert_eq!("Foo", format!("{:?}", Foo)); - assert_eq!("Foo", format!("{:#?}", Foo)); + assert_eq!("Foo", format!("{Foo:?}")); + assert_eq!("Foo", format!("{Foo:#?}")); } #[test] @@ -25,12 +25,12 @@ mod debug_struct { } } - assert_eq!("Foo { bar: true }", format!("{:?}", Foo)); + assert_eq!("Foo { bar: true }", format!("{Foo:?}")); assert_eq!( "Foo { bar: true, }", - format!("{:#?}", Foo) + format!("{Foo:#?}") ); } @@ -47,13 +47,13 @@ mod debug_struct { } } - assert_eq!("Foo { bar: true, baz: 10/20 }", format!("{:?}", Foo)); + assert_eq!("Foo { bar: true, baz: 10/20 }", format!("{Foo:?}")); assert_eq!( "Foo { bar: true, baz: 10/20, }", - format!("{:#?}", Foo) + format!("{Foo:#?}") ); } @@ -80,7 +80,7 @@ mod debug_struct { assert_eq!( "Bar { foo: Foo { bar: true, baz: 10/20 }, hello: \"world\" }", - format!("{:?}", Bar) + format!("{Bar:?}") ); assert_eq!( "Bar { @@ -90,7 +90,7 @@ mod debug_struct { }, hello: \"world\", }", - format!("{:#?}", Bar) + format!("{Bar:#?}") ); } @@ -104,8 +104,8 @@ mod debug_struct { } } - assert_eq!("Foo { .. }", format!("{:?}", Foo)); - assert_eq!("Foo { .. }", format!("{:#?}", Foo)); + assert_eq!("Foo { .. }", format!("{Foo:?}")); + assert_eq!("Foo { .. }", format!("{Foo:#?}")); } #[test] @@ -121,14 +121,14 @@ mod debug_struct { } } - assert_eq!("Foo { bar: true, baz: 10/20, .. }", format!("{:?}", Foo)); + assert_eq!("Foo { bar: true, baz: 10/20, .. }", format!("{Foo:?}")); assert_eq!( "Foo { bar: true, baz: 10/20, .. }", - format!("{:#?}", Foo) + format!("{Foo:#?}") ); } @@ -158,7 +158,7 @@ mod debug_struct { assert_eq!( "Bar { foo: Foo { bar: true, baz: 10/20, .. }, hello: \"world\", .. }", - format!("{:?}", Bar) + format!("{Bar:?}") ); assert_eq!( "Bar { @@ -170,7 +170,7 @@ mod debug_struct { hello: \"world\", .. }", - format!("{:#?}", Bar) + format!("{Bar:#?}") ); } } @@ -188,8 +188,8 @@ mod debug_tuple { } } - assert_eq!("Foo", format!("{:?}", Foo)); - assert_eq!("Foo", format!("{:#?}", Foo)); + assert_eq!("Foo", format!("{Foo:?}")); + assert_eq!("Foo", format!("{Foo:#?}")); } #[test] @@ -202,12 +202,12 @@ mod debug_tuple { } } - assert_eq!("Foo(true)", format!("{:?}", Foo)); + assert_eq!("Foo(true)", format!("{Foo:?}")); assert_eq!( "Foo( true, )", - format!("{:#?}", Foo) + format!("{Foo:#?}") ); } @@ -221,13 +221,13 @@ mod debug_tuple { } } - assert_eq!("Foo(true, 10/20)", format!("{:?}", Foo)); + assert_eq!("Foo(true, 10/20)", format!("{Foo:?}")); assert_eq!( "Foo( true, 10/20, )", - format!("{:#?}", Foo) + format!("{Foo:#?}") ); } @@ -249,7 +249,7 @@ mod debug_tuple { } } - assert_eq!("Bar(Foo(true, 10/20), \"world\")", format!("{:?}", Bar)); + assert_eq!("Bar(Foo(true, 10/20), \"world\")", format!("{Bar:?}")); assert_eq!( "Bar( Foo( @@ -258,7 +258,7 @@ mod debug_tuple { ), \"world\", )", - format!("{:#?}", Bar) + format!("{Bar:#?}") ); } } @@ -276,8 +276,8 @@ mod debug_map { } } - assert_eq!("{}", format!("{:?}", Foo)); - assert_eq!("{}", format!("{:#?}", Foo)); + assert_eq!("{}", format!("{Foo:?}")); + assert_eq!("{}", format!("{Foo:#?}")); } #[test] @@ -298,15 +298,15 @@ mod debug_map { } } - assert_eq!(format!("{:?}", Entry), format!("{:?}", KeyValue)); - assert_eq!(format!("{:#?}", Entry), format!("{:#?}", KeyValue)); + assert_eq!(format!("{Entry:?}"), format!("{KeyValue:?}")); + assert_eq!(format!("{Entry:#?}"), format!("{KeyValue:#?}")); - assert_eq!("{\"bar\": true}", format!("{:?}", Entry)); + assert_eq!("{\"bar\": true}", format!("{Entry:?}")); assert_eq!( "{ \"bar\": true, }", - format!("{:#?}", Entry) + format!("{Entry:#?}") ); } @@ -336,16 +336,16 @@ mod debug_map { } } - assert_eq!(format!("{:?}", Entry), format!("{:?}", KeyValue)); - assert_eq!(format!("{:#?}", Entry), format!("{:#?}", KeyValue)); + assert_eq!(format!("{Entry:?}"), format!("{KeyValue:?}")); + assert_eq!(format!("{Entry:#?}"), format!("{KeyValue:#?}")); - assert_eq!("{\"bar\": true, 10: 10/20}", format!("{:?}", Entry)); + assert_eq!("{\"bar\": true, 10: 10/20}", format!("{Entry:?}")); assert_eq!( "{ \"bar\": true, 10: 10/20, }", - format!("{:#?}", Entry) + format!("{Entry:#?}") ); } @@ -373,7 +373,7 @@ mod debug_map { assert_eq!( "{\"foo\": {\"bar\": true, 10: 10/20}, \ {\"bar\": true, 10: 10/20}: \"world\"}", - format!("{:?}", Bar) + format!("{Bar:?}") ); assert_eq!( "{ @@ -386,7 +386,7 @@ mod debug_map { 10: 10/20, }: \"world\", }", - format!("{:#?}", Bar) + format!("{Bar:#?}") ); } @@ -441,7 +441,7 @@ mod debug_map { } } - format!("{:?}", Foo); + format!("{Foo:?}"); } #[test] @@ -455,7 +455,7 @@ mod debug_map { } } - format!("{:?}", Foo); + format!("{Foo:?}"); } #[test] @@ -469,7 +469,7 @@ mod debug_map { } } - format!("{:?}", Foo); + format!("{Foo:?}"); } } @@ -486,8 +486,8 @@ mod debug_set { } } - assert_eq!("{}", format!("{:?}", Foo)); - assert_eq!("{}", format!("{:#?}", Foo)); + assert_eq!("{}", format!("{Foo:?}")); + assert_eq!("{}", format!("{Foo:#?}")); } #[test] @@ -500,12 +500,12 @@ mod debug_set { } } - assert_eq!("{true}", format!("{:?}", Foo)); + assert_eq!("{true}", format!("{Foo:?}")); assert_eq!( "{ true, }", - format!("{:#?}", Foo) + format!("{Foo:#?}") ); } @@ -519,13 +519,13 @@ mod debug_set { } } - assert_eq!("{true, 10/20}", format!("{:?}", Foo)); + assert_eq!("{true, 10/20}", format!("{Foo:?}")); assert_eq!( "{ true, 10/20, }", - format!("{:#?}", Foo) + format!("{Foo:#?}") ); } @@ -547,7 +547,7 @@ mod debug_set { } } - assert_eq!("{{true, 10/20}, \"world\"}", format!("{:?}", Bar)); + assert_eq!("{{true, 10/20}, \"world\"}", format!("{Bar:?}")); assert_eq!( "{ { @@ -556,7 +556,7 @@ mod debug_set { }, \"world\", }", - format!("{:#?}", Bar) + format!("{Bar:#?}") ); } } @@ -574,8 +574,8 @@ mod debug_list { } } - assert_eq!("[]", format!("{:?}", Foo)); - assert_eq!("[]", format!("{:#?}", Foo)); + assert_eq!("[]", format!("{Foo:?}")); + assert_eq!("[]", format!("{Foo:#?}")); } #[test] @@ -588,12 +588,12 @@ mod debug_list { } } - assert_eq!("[true]", format!("{:?}", Foo)); + assert_eq!("[true]", format!("{Foo:?}")); assert_eq!( "[ true, ]", - format!("{:#?}", Foo) + format!("{Foo:#?}") ); } @@ -607,13 +607,13 @@ mod debug_list { } } - assert_eq!("[true, 10/20]", format!("{:?}", Foo)); + assert_eq!("[true, 10/20]", format!("{Foo:?}")); assert_eq!( "[ true, 10/20, ]", - format!("{:#?}", Foo) + format!("{Foo:#?}") ); } @@ -635,7 +635,7 @@ mod debug_list { } } - assert_eq!("[[true, 10/20], \"world\"]", format!("{:?}", Bar)); + assert_eq!("[[true, 10/20], \"world\"]", format!("{Bar:?}")); assert_eq!( "[ [ @@ -644,7 +644,7 @@ mod debug_list { ], \"world\", ]", - format!("{:#?}", Bar) + format!("{Bar:#?}") ); } } @@ -668,13 +668,13 @@ fn test_formatting_parameters_are_forwarded() { set.insert(1024); set.insert(7); - assert_eq!(format!("{:03?}", struct_), "Foo { bar: 1024, baz: 007 }"); - assert_eq!(format!("{:03?}", tuple), "(1024, 007)"); - assert_eq!(format!("{:03?}", list), "[1024, 007]"); - assert_eq!(format!("{:03?}", map), r#"{"bar": 1024, "baz": 007}"#); - assert_eq!(format!("{:03?}", set), "{007, 1024}"); + assert_eq!(format!("{struct_:03?}"), "Foo { bar: 1024, baz: 007 }"); + assert_eq!(format!("{tuple:03?}"), "(1024, 007)"); + assert_eq!(format!("{list:03?}"), "[1024, 007]"); + assert_eq!(format!("{map:03?}"), r#"{"bar": 1024, "baz": 007}"#); + assert_eq!(format!("{set:03?}"), "{007, 1024}"); assert_eq!( - format!("{:#03?}", struct_), + format!("{struct_:#03?}"), " Foo { bar: 1024, @@ -684,7 +684,7 @@ Foo { .trim() ); assert_eq!( - format!("{:#03?}", tuple), + format!("{tuple:#03?}"), " ( 1024, @@ -694,7 +694,7 @@ Foo { .trim() ); assert_eq!( - format!("{:#03?}", list), + format!("{list:#03?}"), " [ 1024, @@ -704,7 +704,7 @@ Foo { .trim() ); assert_eq!( - format!("{:#03?}", map), + format!("{map:#03?}"), r#" { "bar": 1024, @@ -714,7 +714,7 @@ Foo { .trim() ); assert_eq!( - format!("{:#03?}", set), + format!("{set:#03?}"), " { 007, diff --git a/library/core/tests/fmt/mod.rs b/library/core/tests/fmt/mod.rs index 7b281ce48e6aa..61807635813c4 100644 --- a/library/core/tests/fmt/mod.rs +++ b/library/core/tests/fmt/mod.rs @@ -6,7 +6,7 @@ mod num; fn test_format_flags() { // No residual flags left by pointer formatting let p = "".as_ptr(); - assert_eq!(format!("{:p} {:x}", p, 16), format!("{:p} 10", p)); + assert_eq!(format!("{:p} {:x}", p, 16), format!("{p:p} 10")); assert_eq!(format!("{: >3}", 'a'), " a"); } @@ -15,8 +15,8 @@ fn test_format_flags() { fn test_pointer_formats_data_pointer() { let b: &[u8] = b""; let s: &str = ""; - assert_eq!(format!("{:p}", s), format!("{:p}", s.as_ptr())); - assert_eq!(format!("{:p}", b), format!("{:p}", b.as_ptr())); + assert_eq!(format!("{s:p}"), format!("{:p}", s.as_ptr())); + assert_eq!(format!("{b:p}"), format!("{:p}", b.as_ptr())); } #[test] @@ -41,5 +41,5 @@ fn pad_integral_resets() { } } - assert_eq!(format!("{:<03}", Bar), "1 0051 "); + assert_eq!(format!("{Bar:<03}"), "1 0051 "); } diff --git a/library/core/tests/fmt/num.rs b/library/core/tests/fmt/num.rs index b958422d14f84..b9ede65c9ff09 100644 --- a/library/core/tests/fmt/num.rs +++ b/library/core/tests/fmt/num.rs @@ -126,7 +126,7 @@ fn test_format_int_exp_limits() { fn test_format_int_exp_precision() { //test that float and integer match let big_int: u32 = 314_159_265; - assert_eq!(format!("{:.1e}", big_int), format!("{:.1e}", f64::from(big_int))); + assert_eq!(format!("{big_int:.1e}"), format!("{:.1e}", f64::from(big_int))); //test adding precision assert_eq!(format!("{:.10e}", i8::MIN), "-1.2800000000e2"); diff --git a/library/core/tests/lazy.rs b/library/core/tests/lazy.rs index 064024ab87b28..416d2b2dae41f 100644 --- a/library/core/tests/lazy.rs +++ b/library/core/tests/lazy.rs @@ -113,7 +113,7 @@ fn aliasing_in_get() { x.set(42).unwrap(); let at_x = x.get().unwrap(); // --- (shared) borrow of inner `Option` --+ let _ = x.set(27); // <-- temporary (unique) borrow of inner `Option` | - println!("{}", at_x); // <------- up until here ---------------------------+ + println!("{at_x}"); // <------- up until here ---------------------------+ } #[test] diff --git a/library/core/tests/num/dec2flt/mod.rs b/library/core/tests/num/dec2flt/mod.rs index 4990d4a083df6..c4e105cba600d 100644 --- a/library/core/tests/num/dec2flt/mod.rs +++ b/library/core/tests/num/dec2flt/mod.rs @@ -15,7 +15,7 @@ macro_rules! test_literal { for input in inputs { assert_eq!(input.parse(), Ok(x64)); assert_eq!(input.parse(), Ok(x32)); - let neg_input = &format!("-{}", input); + let neg_input = &format!("-{input}"); assert_eq!(neg_input.parse(), Ok(-x64)); assert_eq!(neg_input.parse(), Ok(-x32)); } @@ -123,9 +123,9 @@ fn inf() { #[test] fn massive_exponent() { let max = i64::MAX; - assert_eq!(format!("1e{}000", max).parse(), Ok(f64::INFINITY)); - assert_eq!(format!("1e-{}000", max).parse(), Ok(0.0)); - assert_eq!(format!("1e{}000", max).parse(), Ok(f64::INFINITY)); + assert_eq!(format!("1e{max}000").parse(), Ok(f64::INFINITY)); + assert_eq!(format!("1e-{max}000").parse(), Ok(0.0)); + assert_eq!(format!("1e{max}000").parse(), Ok(f64::INFINITY)); } #[test] diff --git a/library/core/tests/num/dec2flt/parse.rs b/library/core/tests/num/dec2flt/parse.rs index 473feacc91fa9..edc77377d5820 100644 --- a/library/core/tests/num/dec2flt/parse.rs +++ b/library/core/tests/num/dec2flt/parse.rs @@ -46,7 +46,7 @@ fn valid() { assert_eq!(parse_positive(b".1e300"), Some(new_number(299, 1))); assert_eq!(parse_positive(b"101e-33"), Some(new_number(-33, 101))); let zeros = "0".repeat(25); - let s = format!("1.5e{}", zeros); + let s = format!("1.5e{zeros}"); assert_eq!(parse_positive(s.as_bytes()), Some(new_number(-1, 15))); } diff --git a/library/core/tests/num/flt2dec/mod.rs b/library/core/tests/num/flt2dec/mod.rs index 4874e8ec09f8c..798473bbde377 100644 --- a/library/core/tests/num/flt2dec/mod.rs +++ b/library/core/tests/num/flt2dec/mod.rs @@ -20,7 +20,7 @@ mod random; pub fn decode_finite(v: T) -> Decoded { match decode(v).1 { FullDecoded::Finite(decoded) => decoded, - full_decoded => panic!("expected finite, got {:?} instead", full_decoded), + full_decoded => panic!("expected finite, got {full_decoded:?} instead"), } } diff --git a/library/core/tests/num/flt2dec/random.rs b/library/core/tests/num/flt2dec/random.rs index 57b3dcf8e1e04..d0950039314ac 100644 --- a/library/core/tests/num/flt2dec/random.rs +++ b/library/core/tests/num/flt2dec/random.rs @@ -15,7 +15,7 @@ use rand::SeedableRng; pub fn decode_finite(v: T) -> Decoded { match decode(v).1 { FullDecoded::Finite(decoded) => decoded, - full_decoded => panic!("expected finite, got {:?} instead", full_decoded), + full_decoded => panic!("expected finite, got {full_decoded:?} instead"), } } diff --git a/library/core/tests/ptr.rs b/library/core/tests/ptr.rs index 9c65871ac4b4c..af8e78f1f4e16 100644 --- a/library/core/tests/ptr.rs +++ b/library/core/tests/ptr.rs @@ -550,7 +550,7 @@ fn dyn_metadata() { assert_eq!(meta.align_of(), std::mem::align_of::()); assert_eq!(meta.layout(), std::alloc::Layout::new::()); - assert!(format!("{:?}", meta).starts_with("DynMetadata(0x")); + assert!(format!("{meta:?}").starts_with("DynMetadata(0x")); } #[test] diff --git a/library/core/tests/result.rs b/library/core/tests/result.rs index 1652c1b83de33..98b870512b046 100644 --- a/library/core/tests/result.rs +++ b/library/core/tests/result.rs @@ -80,9 +80,9 @@ fn test_fmt_default() { let ok: Result = Ok(100); let err: Result = Err("Err"); - let s = format!("{:?}", ok); + let s = format!("{ok:?}"); assert_eq!(s, "Ok(100)"); - let s = format!("{:?}", err); + let s = format!("{err:?}"); assert_eq!(s, "Err(\"Err\")"); } diff --git a/library/portable-simd/crates/core_simd/examples/nbody.rs b/library/portable-simd/crates/core_simd/examples/nbody.rs index 7b1e6840f6424..b16b952f71e86 100644 --- a/library/portable-simd/crates/core_simd/examples/nbody.rs +++ b/library/portable-simd/crates/core_simd/examples/nbody.rs @@ -187,7 +187,7 @@ mod tests { fn main() { { let (energy_before, energy_after) = nbody::run(1000); - println!("Energy before: {}", energy_before); - println!("Energy after: {}", energy_after); + println!("Energy before: {energy_before}"); + println!("Energy after: {energy_after}"); } } diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index 31900912df468..5338cd077572c 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -1106,7 +1106,7 @@ impl Literal { #[stable(feature = "proc_macro_lib2", since = "1.29.0")] pub fn f32_unsuffixed(n: f32) -> Literal { if !n.is_finite() { - panic!("Invalid float literal {}", n); + panic!("Invalid float literal {n}"); } let mut repr = n.to_string(); if !repr.contains('.') { @@ -1131,7 +1131,7 @@ impl Literal { #[stable(feature = "proc_macro_lib2", since = "1.29.0")] pub fn f32_suffixed(n: f32) -> Literal { if !n.is_finite() { - panic!("Invalid float literal {}", n); + panic!("Invalid float literal {n}"); } Literal(bridge::client::Literal::f32(&n.to_string())) } @@ -1151,7 +1151,7 @@ impl Literal { #[stable(feature = "proc_macro_lib2", since = "1.29.0")] pub fn f64_unsuffixed(n: f64) -> Literal { if !n.is_finite() { - panic!("Invalid float literal {}", n); + panic!("Invalid float literal {n}"); } let mut repr = n.to_string(); if !repr.contains('.') { @@ -1176,7 +1176,7 @@ impl Literal { #[stable(feature = "proc_macro_lib2", since = "1.29.0")] pub fn f64_suffixed(n: f64) -> Literal { if !n.is_finite() { - panic!("Invalid float literal {}", n); + panic!("Invalid float literal {n}"); } Literal(bridge::client::Literal::f64(&n.to_string())) } diff --git a/library/std/src/alloc.rs b/library/std/src/alloc.rs index 8ee55234cea43..a880439624690 100644 --- a/library/std/src/alloc.rs +++ b/library/std/src/alloc.rs @@ -83,7 +83,7 @@ pub use alloc_crate::alloc::*; /// /// fn main() { /// let a = Box::new(4); // Allocates from the system allocator. -/// println!("{}", a); +/// println!("{a}"); /// } /// ``` /// diff --git a/library/std/src/backtrace/tests.rs b/library/std/src/backtrace/tests.rs index f5da93f93fd93..4dfbf88e83ebc 100644 --- a/library/std/src/backtrace/tests.rs +++ b/library/std/src/backtrace/tests.rs @@ -57,10 +57,10 @@ fn test_debug() { \n { fn: \"std::rt::lang_start\", file: \"rust/rt.rs\", line: 400 },\ \n]"; - assert_eq!(format!("{:#?}", backtrace), expected); + assert_eq!(format!("{backtrace:#?}"), expected); // Format the backtrace a second time, just to make sure lazily resolved state is stable - assert_eq!(format!("{:#?}", backtrace), expected); + assert_eq!(format!("{backtrace:#?}"), expected); } #[test] @@ -91,5 +91,5 @@ fn test_frames() { let mut iter = frames.iter().zip(expected.iter()); - assert!(iter.all(|(f, e)| format!("{:#?}", f) == *e)); + assert!(iter.all(|(f, e)| format!("{f:#?}") == *e)); } diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index c0524352193f9..b5dd17d99296b 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -109,8 +109,8 @@ use crate::sys; /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"]; /// for &book in &to_find { /// match book_reviews.get(book) { -/// Some(review) => println!("{}: {}", book, review), -/// None => println!("{} is unreviewed.", book) +/// Some(review) => println!("{book}: {review}"), +/// None => println!("{book} is unreviewed.") /// } /// } /// @@ -119,7 +119,7 @@ use crate::sys; /// /// // Iterate over everything. /// for (book, review) in &book_reviews { -/// println!("{}: \"{}\"", book, review); +/// println!("{book}: \"{review}\""); /// } /// ``` /// @@ -199,7 +199,7 @@ use crate::sys; /// /// // Use derived implementation to print the status of the vikings. /// for (viking, health) in &vikings { -/// println!("{:?} has {} hp", viking, health); +/// println!("{viking:?} has {health} hp"); /// } /// ``` @@ -341,7 +341,7 @@ impl HashMap { /// ]); /// /// for key in map.keys() { - /// println!("{}", key); + /// println!("{key}"); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -392,7 +392,7 @@ impl HashMap { /// ]); /// /// for val in map.values() { - /// println!("{}", val); + /// println!("{val}"); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -419,7 +419,7 @@ impl HashMap { /// } /// /// for val in map.values() { - /// println!("{}", val); + /// println!("{val}"); /// } /// ``` #[stable(feature = "map_values_mut", since = "1.10.0")] @@ -470,7 +470,7 @@ impl HashMap { /// ]); /// /// for (key, val) in map.iter() { - /// println!("key: {} val: {}", key, val); + /// println!("key: {key} val: {val}"); /// } /// ``` #[rustc_lint_query_instability] @@ -500,7 +500,7 @@ impl HashMap { /// } /// /// for (key, val) in &map { - /// println!("key: {} val: {}", key, val); + /// println!("key: {key} val: {val}"); /// } /// ``` #[rustc_lint_query_instability] diff --git a/library/std/src/collections/hash/map/tests.rs b/library/std/src/collections/hash/map/tests.rs index 30da22b80849c..7ebc41588b3df 100644 --- a/library/std/src/collections/hash/map/tests.rs +++ b/library/std/src/collections/hash/map/tests.rs @@ -515,10 +515,10 @@ fn test_show() { map.insert(1, 2); map.insert(3, 4); - let map_str = format!("{:?}", map); + let map_str = format!("{map:?}"); assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}"); - assert_eq!(format!("{:?}", empty), "{}"); + assert_eq!(format!("{empty:?}"), "{}"); } #[test] @@ -702,7 +702,7 @@ fn test_entry_take_doesnt_corrupt() { // Test for #19292 fn check(m: &HashMap) { for k in m.keys() { - assert!(m.contains_key(k), "{} is in keys() but not in the map?", k); + assert!(m.contains_key(k), "{k} is in keys() but not in the map?"); } } diff --git a/library/std/src/collections/hash/set.rs b/library/std/src/collections/hash/set.rs index 2eb4cacabb831..876d05b50fb80 100644 --- a/library/std/src/collections/hash/set.rs +++ b/library/std/src/collections/hash/set.rs @@ -66,7 +66,7 @@ use super::map::{map_try_reserve_error, RandomState}; /// /// // Iterate over everything. /// for book in &books { -/// println!("{}", book); +/// println!("{book}"); /// } /// ``` /// @@ -91,7 +91,7 @@ use super::map::{map_try_reserve_error, RandomState}; /// /// // Use derived implementation to print the vikings. /// for x in &vikings { -/// println!("{:?}", x); +/// println!("{x:?}"); /// } /// ``` /// @@ -181,7 +181,7 @@ impl HashSet { /// /// // Will print in an arbitrary order. /// for x in set.iter() { - /// println!("{}", x); + /// println!("{x}"); /// } /// ``` #[inline] @@ -244,7 +244,7 @@ impl HashSet { /// /// // print 1, 2, 3 in an arbitrary order /// for i in set.drain() { - /// println!("{}", i); + /// println!("{i}"); /// } /// /// assert!(set.is_empty()); @@ -525,7 +525,7 @@ where /// /// // Can be seen as `a - b`. /// for x in a.difference(&b) { - /// println!("{}", x); // Print 1 + /// println!("{x}"); // Print 1 /// } /// /// let diff: HashSet<_> = a.difference(&b).collect(); @@ -555,7 +555,7 @@ where /// /// // Print 1, 4 in arbitrary order. /// for x in a.symmetric_difference(&b) { - /// println!("{}", x); + /// println!("{x}"); /// } /// /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect(); @@ -586,7 +586,7 @@ where /// /// // Print 2, 3 in arbitrary order. /// for x in a.intersection(&b) { - /// println!("{}", x); + /// println!("{x}"); /// } /// /// let intersection: HashSet<_> = a.intersection(&b).collect(); @@ -615,7 +615,7 @@ where /// /// // Print 1, 2, 3, 4 in arbitrary order. /// for x in a.union(&b) { - /// println!("{}", x); + /// println!("{x}"); /// } /// /// let union: HashSet<_> = a.union(&b).collect(); @@ -1451,7 +1451,7 @@ impl IntoIterator for HashSet { /// /// // Will print in an arbitrary order. /// for x in &v { - /// println!("{}", x); + /// println!("{x}"); /// } /// ``` #[inline] diff --git a/library/std/src/collections/hash/set/tests.rs b/library/std/src/collections/hash/set/tests.rs index 6a625e6243c21..233db276b9e61 100644 --- a/library/std/src/collections/hash/set/tests.rs +++ b/library/std/src/collections/hash/set/tests.rs @@ -301,10 +301,10 @@ fn test_show() { set.insert(1); set.insert(2); - let set_str = format!("{:?}", set); + let set_str = format!("{set:?}"); assert!(set_str == "{1, 2}" || set_str == "{2, 1}"); - assert_eq!(format!("{:?}", empty), "{}"); + assert_eq!(format!("{empty:?}"), "{}"); } #[test] diff --git a/library/std/src/collections/mod.rs b/library/std/src/collections/mod.rs index b5e81deb48080..0caec8fe05aa7 100644 --- a/library/std/src/collections/mod.rs +++ b/library/std/src/collections/mod.rs @@ -199,7 +199,7 @@ //! ``` //! let vec = vec![1, 2, 3, 4]; //! for x in vec.iter() { -//! println!("vec contained {}", x); +//! println!("vec contained {x:?}"); //! } //! ``` //! @@ -246,7 +246,7 @@ //! ``` //! let vec = vec![1, 2, 3, 4]; //! for x in vec.iter().rev() { -//! println!("vec contained {}", x); +//! println!("vec contained {x:?}"); //! } //! ``` //! @@ -306,7 +306,7 @@ //! //! println!("Number of occurrences of each character"); //! for (char, count) in &count { -//! println!("{}: {}", char, count); +//! println!("{char}: {count}"); //! } //! ``` //! @@ -339,7 +339,7 @@ //! // Check if they're sober enough to have another beer. //! if person.blood_alcohol > 0.3 { //! // Too drunk... for now. -//! println!("Sorry {}, I have to cut you off", id); +//! println!("Sorry {id}, I have to cut you off"); //! } else { //! // Have another! //! person.blood_alcohol += 0.1; diff --git a/library/std/src/env.rs b/library/std/src/env.rs index 5ed9fa9d6f0fd..05f08c498e683 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -118,7 +118,7 @@ pub struct VarsOs { /// // We will iterate through the references to the element returned by /// // env::vars(); /// for (key, value) in env::vars() { -/// println!("{}: {}", key, value); +/// println!("{key}: {value}"); /// } /// ``` /// @@ -148,7 +148,7 @@ pub fn vars() -> Vars { /// // We will iterate through the references to the element returned by /// // env::vars_os(); /// for (key, value) in env::vars_os() { -/// println!("{:?}: {:?}", key, value); +/// println!("{key:?}: {value:?}"); /// } /// ``` #[must_use] @@ -212,8 +212,8 @@ impl fmt::Debug for VarsOs { /// /// let key = "HOME"; /// match env::var(key) { -/// Ok(val) => println!("{}: {:?}", key, val), -/// Err(e) => println!("couldn't interpret {}: {}", key, e), +/// Ok(val) => println!("{key}: {val:?}"), +/// Err(e) => println!("couldn't interpret {key}: {e}"), /// } /// ``` #[stable(feature = "env", since = "1.0.0")] @@ -252,8 +252,8 @@ fn _var(key: &OsStr) -> Result { /// /// let key = "HOME"; /// match env::var_os(key) { -/// Some(val) => println!("{}: {:?}", key, val), -/// None => println!("{} is not defined in the environment.", key) +/// Some(val) => println!("{key}: {val:?}"), +/// None => println!("{key} is not defined in the environment.") /// } /// ``` #[must_use] @@ -343,7 +343,7 @@ pub fn set_var, V: AsRef>(key: K, value: V) { fn _set_var(key: &OsStr, value: &OsStr) { os_imp::setenv(key, value).unwrap_or_else(|e| { - panic!("failed to set environment variable `{:?}` to `{:?}`: {}", key, value, e) + panic!("failed to set environment variable `{key:?}` to `{value:?}`: {e}") }) } @@ -385,7 +385,7 @@ pub fn remove_var>(key: K) { fn _remove_var(key: &OsStr) { os_imp::unsetenv(key) - .unwrap_or_else(|e| panic!("failed to remove environment variable `{:?}`: {}", key, e)) + .unwrap_or_else(|e| panic!("failed to remove environment variable `{key:?}`: {e}")) } /// An iterator that splits an environment variable into paths according to @@ -421,7 +421,7 @@ pub struct SplitPaths<'a> { /// println!("'{}'", path.display()); /// } /// } -/// None => println!("{} is not defined in the environment.", key) +/// None => println!("{key} is not defined in the environment.") /// } /// ``` #[stable(feature = "env", since = "1.0.0")] @@ -684,7 +684,7 @@ pub fn temp_dir() -> PathBuf { /// match env::current_exe() { /// Ok(exe_path) => println!("Path of this executable is: {}", /// exe_path.display()), -/// Err(e) => println!("failed to get current exe path: {}", e), +/// Err(e) => println!("failed to get current exe path: {e}"), /// }; /// ``` #[stable(feature = "env", since = "1.0.0")] @@ -755,7 +755,7 @@ pub struct ArgsOs { /// /// // Prints each argument on a separate line /// for argument in env::args() { -/// println!("{}", argument); +/// println!("{argument}"); /// } /// ``` #[stable(feature = "env", since = "1.0.0")] @@ -790,7 +790,7 @@ pub fn args() -> Args { /// /// // Prints each argument on a separate line /// for argument in env::args_os() { -/// println!("{:?}", argument); +/// println!("{argument:?}"); /// } /// ``` #[stable(feature = "env", since = "1.0.0")] diff --git a/library/std/src/error.rs b/library/std/src/error.rs index 1a96b9c928289..c3cb71a5dee63 100644 --- a/library/std/src/error.rs +++ b/library/std/src/error.rs @@ -96,7 +96,7 @@ pub trait Error: Debug + Display { /// fn main() { /// match get_super_error() { /// Err(e) => { - /// println!("Error: {}", e); + /// println!("Error: {e}"); /// println!("Caused by: {}", e.source().unwrap()); /// } /// _ => println!("No error"), @@ -139,7 +139,7 @@ pub trait Error: Debug + Display { /// ``` /// if let Err(e) = "xc".parse::() { /// // Print `e` itself, no need for description(). - /// eprintln!("Error: {}", e); + /// eprintln!("Error: {e}"); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -1074,7 +1074,7 @@ impl Report { /// /// let error = SuperError { source: SuperErrorSideKick }; /// let report = Report::new(error).pretty(true); - /// eprintln!("Error: {:?}", report); + /// eprintln!("Error: {report:?}"); /// ``` /// /// This example produces the following output: @@ -1135,7 +1135,7 @@ impl Report { /// let source = SuperErrorSideKick { source }; /// let error = SuperError { source }; /// let report = Report::new(error).pretty(true); - /// eprintln!("Error: {:?}", report); + /// eprintln!("Error: {report:?}"); /// ``` /// /// This example produces the following output: @@ -1210,7 +1210,7 @@ impl Report { /// let source = SuperErrorSideKick::new(); /// let error = SuperError { source }; /// let report = Report::new(error).pretty(true).show_backtrace(true); - /// eprintln!("Error: {:?}", report); + /// eprintln!("Error: {report:?}"); /// ``` /// /// This example produces something similar to the following output: @@ -1267,7 +1267,7 @@ where let sources = self.error.source().into_iter().flat_map(::chain); for cause in sources { - write!(f, ": {}", cause)?; + write!(f, ": {cause}")?; } Ok(()) @@ -1278,7 +1278,7 @@ where fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let error = &self.error; - write!(f, "{}", error)?; + write!(f, "{error}")?; if let Some(cause) = error.source() { write!(f, "\n\nCaused by:")?; @@ -1289,9 +1289,9 @@ where writeln!(f)?; let mut indented = Indented { inner: f }; if multiple { - write!(indented, "{: >4}: {}", ind, error)?; + write!(indented, "{ind: >4}: {error}")?; } else { - write!(indented, " {}", error)?; + write!(indented, " {error}")?; } } } @@ -1333,7 +1333,7 @@ impl Report> { let sources = self.error.source().into_iter().flat_map(::chain); for cause in sources { - write!(f, ": {}", cause)?; + write!(f, ": {cause}")?; } Ok(()) @@ -1344,7 +1344,7 @@ impl Report> { fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let error = &self.error; - write!(f, "{}", error)?; + write!(f, "{error}")?; if let Some(cause) = error.source() { write!(f, "\n\nCaused by:")?; @@ -1355,9 +1355,9 @@ impl Report> { writeln!(f)?; let mut indented = Indented { inner: f }; if multiple { - write!(indented, "{: >4}: {}", ind, error)?; + write!(indented, "{ind: >4}: {error}")?; } else { - write!(indented, " {}", error)?; + write!(indented, " {error}")?; } } } diff --git a/library/std/src/error/tests.rs b/library/std/src/error/tests.rs index eae5f43ff3cfb..a2a35d96ec918 100644 --- a/library/std/src/error/tests.rs +++ b/library/std/src/error/tests.rs @@ -130,7 +130,7 @@ Stack backtrace: error.backtrace = Some(trace); let report = Report::new(error).pretty(true).show_backtrace(true); - println!("Error: {}", report); + println!("Error: {report}"); assert_eq!(expected.trim_end(), report.to_string()); } @@ -155,7 +155,7 @@ Stack backtrace: let error = GenericError::new_with_source("Error with two sources", error); let report = Report::new(error).pretty(true).show_backtrace(true); - println!("Error: {}", report); + println!("Error: {report}"); assert_eq!(expected.trim_end(), report.to_string()); } @@ -355,7 +355,7 @@ Caused by: 1: The message goes on and on."; let actual = report.to_string(); - println!("{}", actual); + println!("{actual}"); assert_eq!(expected, actual); } diff --git a/library/std/src/ffi/c_str.rs b/library/std/src/ffi/c_str.rs index 1678367290e51..b833d0e2ca507 100644 --- a/library/std/src/ffi/c_str.rs +++ b/library/std/src/ffi/c_str.rs @@ -1120,7 +1120,7 @@ impl fmt::Display for FromBytesWithNulError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.description())?; if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind { - write!(f, " at byte pos {}", pos)?; + write!(f, " at byte pos {pos}")?; } Ok(()) } @@ -1134,7 +1134,7 @@ impl fmt::Display for FromVecWithNulError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.error_kind { FromBytesWithNulErrorKind::InteriorNul(pos) => { - write!(f, "data provided contains an interior nul byte at pos {}", pos) + write!(f, "data provided contains an interior nul byte at pos {pos}") } FromBytesWithNulErrorKind::NotNulTerminated => { write!(f, "data provided is not nul terminated") diff --git a/library/std/src/ffi/c_str/tests.rs b/library/std/src/ffi/c_str/tests.rs index 00ba5460821ff..8d603229315c0 100644 --- a/library/std/src/ffi/c_str/tests.rs +++ b/library/std/src/ffi/c_str/tests.rs @@ -35,7 +35,7 @@ fn build_with_zero2() { #[test] fn formatted() { let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap(); - assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#); + assert_eq!(format!("{s:?}"), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#); } #[test] diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index 0b65336a5a7da..c99d9b279a928 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -1123,7 +1123,7 @@ impl Metadata { /// let metadata = fs::metadata("foo.txt")?; /// /// if let Ok(time) = metadata.modified() { - /// println!("{:?}", time); + /// println!("{time:?}"); /// } else { /// println!("Not supported on this platform"); /// } @@ -1158,7 +1158,7 @@ impl Metadata { /// let metadata = fs::metadata("foo.txt")?; /// /// if let Ok(time) = metadata.accessed() { - /// println!("{:?}", time); + /// println!("{time:?}"); /// } else { /// println!("Not supported on this platform"); /// } @@ -1190,7 +1190,7 @@ impl Metadata { /// let metadata = fs::metadata("foo.txt")?; /// /// if let Ok(time) = metadata.created() { - /// println!("{:?}", time); + /// println!("{time:?}"); /// } else { /// println!("Not supported on this platform or filesystem"); /// } diff --git a/library/std/src/fs/tests.rs b/library/std/src/fs/tests.rs index 16b8bf68242ef..88d87fc532e3c 100644 --- a/library/std/src/fs/tests.rs +++ b/library/std/src/fs/tests.rs @@ -30,7 +30,7 @@ macro_rules! check { ($e:expr) => { match $e { Ok(t) => t, - Err(e) => panic!("{} failed with: {}", stringify!($e), e), + Err(e) => panic!("{} failed with: {e}", stringify!($e)), } }; } @@ -470,7 +470,7 @@ fn file_test_directoryinfo_readdir() { check!(fs::create_dir(dir)); let prefix = "foo"; for n in 0..3 { - let f = dir.join(&format!("{}.txt", n)); + let f = dir.join(&format!("{n}.txt")); let mut w = check!(File::create(&f)); let msg_str = format!("{}{}", prefix, n.to_string()); let msg = msg_str.as_bytes(); @@ -1329,7 +1329,7 @@ fn dir_entry_methods() { assert!(file.file_type().unwrap().is_file()); assert!(file.metadata().unwrap().is_file()); } - f => panic!("unknown file name: {:?}", f), + f => panic!("unknown file name: {f:?}"), } } } @@ -1340,7 +1340,7 @@ fn dir_entry_debug() { File::create(&tmpdir.join("b")).unwrap(); let mut read_dir = tmpdir.path().read_dir().unwrap(); let dir_entry = read_dir.next().unwrap().unwrap(); - let actual = format!("{:?}", dir_entry); + let actual = format!("{dir_entry:?}"); let expected = format!("DirEntry({:?})", dir_entry.0.path()); assert_eq!(actual, expected); } @@ -1409,7 +1409,7 @@ fn metadata_access_times() { || e1.kind() == ErrorKind::Unsupported && e2.kind() == ErrorKind::Unsupported => {} (a, b) => { - panic!("creation time must be always supported or not supported: {:?} {:?}", a, b,) + panic!("creation time must be always supported or not supported: {a:?} {b:?}") } } } diff --git a/library/std/src/io/buffered/bufreader.rs b/library/std/src/io/buffered/bufreader.rs index e7eee4436249b..989cec976b72f 100644 --- a/library/std/src/io/buffered/bufreader.rs +++ b/library/std/src/io/buffered/bufreader.rs @@ -41,7 +41,7 @@ use crate::mem::MaybeUninit; /// /// let mut line = String::new(); /// let len = reader.read_line(&mut line)?; -/// println!("First line is {} bytes long", len); +/// println!("First line is {len} bytes long"); /// Ok(()) /// } /// ``` diff --git a/library/std/src/io/error.rs b/library/std/src/io/error.rs index 17e2b97545a94..4a50e647c640e 100644 --- a/library/std/src/io/error.rs +++ b/library/std/src/io/error.rs @@ -457,7 +457,7 @@ impl From for Error { /// /// let not_found = ErrorKind::NotFound; /// let error = Error::from(not_found); - /// assert_eq!("entity not found", format!("{}", error)); + /// assert_eq!("entity not found", format!("{error}")); /// ``` #[inline] fn from(kind: ErrorKind) -> Error { @@ -561,7 +561,7 @@ impl Error { /// use std::io::Error; /// /// let os_error = Error::last_os_error(); - /// println!("last OS error: {:?}", os_error); + /// println!("last OS error: {os_error:?}"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[must_use] @@ -618,7 +618,7 @@ impl Error { /// /// fn print_os_error(err: &Error) { /// if let Some(raw_os_err) = err.raw_os_error() { - /// println!("raw OS error: {:?}", raw_os_err); + /// println!("raw OS error: {raw_os_err:?}"); /// } else { /// println!("Not an OS error"); /// } @@ -657,7 +657,7 @@ impl Error { /// /// fn print_error(err: &Error) { /// if let Some(inner_err) = err.get_ref() { - /// println!("Inner error: {:?}", inner_err); + /// println!("Inner error: {inner_err:?}"); /// } else { /// println!("No inner error"); /// } @@ -731,7 +731,7 @@ impl Error { /// /// fn print_error(err: &Error) { /// if let Some(inner_err) = err.get_ref() { - /// println!("Inner error: {}", inner_err); + /// println!("Inner error: {inner_err}"); /// } else { /// println!("No inner error"); /// } @@ -770,7 +770,7 @@ impl Error { /// /// fn print_error(err: Error) { /// if let Some(inner_err) = err.into_inner() { - /// println!("Inner error: {}", inner_err); + /// println!("Inner error: {inner_err}"); /// } else { /// println!("No inner error"); /// } @@ -852,7 +852,7 @@ impl fmt::Display for Error { match self.repr.data() { ErrorData::Os(code) => { let detail = sys::os::error_string(code); - write!(fmt, "{} (os error {})", detail, code) + write!(fmt, "{detail} (os error {code})") } ErrorData::Custom(ref c) => c.error.fmt(fmt), ErrorData::Simple(kind) => write!(fmt, "{}", kind.as_str()), diff --git a/library/std/src/io/error/repr_bitpacked.rs b/library/std/src/io/error/repr_bitpacked.rs index 4301e941b3dce..1a0538f861a1e 100644 --- a/library/std/src/io/error/repr_bitpacked.rs +++ b/library/std/src/io/error/repr_bitpacked.rs @@ -161,8 +161,7 @@ impl Repr { // only run in libstd's tests, unless the user uses -Zbuild-std) debug_assert!( matches!(res.data(), ErrorData::Os(c) if c == code), - "repr(os) encoding failed for {}", - code, + "repr(os) encoding failed for {code}" ); res } diff --git a/library/std/src/io/error/tests.rs b/library/std/src/io/error/tests.rs index c2c51553b208c..6fd15fa80488b 100644 --- a/library/std/src/io/error/tests.rs +++ b/library/std/src/io/error/tests.rs @@ -33,7 +33,7 @@ fn test_debug_error() { }}", code, kind, msg ); - assert_eq!(format!("{:?}", err), expected); + assert_eq!(format!("{err:?}"), expected); } #[test] @@ -65,8 +65,8 @@ fn test_const() { assert_eq!(E.kind(), ErrorKind::NotFound); assert_eq!(E.to_string(), "hello"); - assert!(format!("{:?}", E).contains("\"hello\"")); - assert!(format!("{:?}", E).contains("NotFound")); + assert!(format!("{E:?}").contains("\"hello\"")); + assert!(format!("{E:?}").contains("NotFound")); } #[test] @@ -101,7 +101,7 @@ fn test_simple_message_packing() { let e = &$err; // Check that the public api is right. assert_eq!(e.kind(), $kind); - assert!(format!("{:?}", e).contains($msg)); + assert!(format!("{e:?}").contains($msg)); // and we got what we expected assert_matches!( e.repr.data(), diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs index 3fa965d08e698..6005270a75fec 100644 --- a/library/std/src/io/mod.rs +++ b/library/std/src/io/mod.rs @@ -91,7 +91,7 @@ //! // read a line into buffer //! reader.read_line(&mut buffer)?; //! -//! println!("{}", buffer); +//! println!("{buffer}"); //! Ok(()) //! } //! ``` @@ -1035,7 +1035,7 @@ pub trait Read { /// fn main() -> io::Result<()> { /// let stdin = io::read_to_string(io::stdin())?; /// println!("Stdin was:"); -/// println!("{}", stdin); +/// println!("{stdin}"); /// Ok(()) /// } /// ``` @@ -1761,7 +1761,7 @@ pub trait Seek { /// .open("foo.txt").unwrap(); /// /// let hello = "Hello!\n"; - /// write!(f, "{}", hello).unwrap(); + /// write!(f, "{hello}").unwrap(); /// f.rewind().unwrap(); /// /// let mut buf = String::new(); @@ -1804,7 +1804,7 @@ pub trait Seek { /// let mut f = File::open("foo.txt")?; /// /// let len = f.stream_len()?; - /// println!("The file is currently {} bytes long", len); + /// println!("The file is currently {len} bytes long"); /// Ok(()) /// } /// ``` @@ -1988,7 +1988,7 @@ pub trait BufRead: Read { /// let buffer = stdin.fill_buf().unwrap(); /// /// // work with buffer - /// println!("{:?}", buffer); + /// println!("{buffer:?}"); /// /// // ensure the bytes we worked with aren't returned again later /// let length = buffer.len(); @@ -2042,7 +2042,7 @@ pub trait BufRead: Read { /// let mut line = String::new(); /// stdin.read_line(&mut line).unwrap(); /// // work with line - /// println!("{:?}", line); + /// println!("{line:?}"); /// } /// ``` #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")] diff --git a/library/std/src/io/stdio.rs b/library/std/src/io/stdio.rs index 5414ff648d4d5..50344e602a958 100644 --- a/library/std/src/io/stdio.rs +++ b/library/std/src/io/stdio.rs @@ -349,10 +349,10 @@ impl Stdin { /// let mut input = String::new(); /// match io::stdin().read_line(&mut input) { /// Ok(n) => { - /// println!("{} bytes read", n); - /// println!("{}", input); + /// println!("{n} bytes read"); + /// println!("{input}"); /// } - /// Err(error) => println!("error: {}", error), + /// Err(error) => println!("error: {error}"), /// } /// ``` /// @@ -953,7 +953,7 @@ where } if let Err(e) = global_s().write_fmt(args) { - panic!("failed printing to {}: {}", label, e); + panic!("failed printing to {label}: {e}"); } } diff --git a/library/std/src/keyword_docs.rs b/library/std/src/keyword_docs.rs index 5b76259afc11d..542b793f6da05 100644 --- a/library/std/src/keyword_docs.rs +++ b/library/std/src/keyword_docs.rs @@ -64,7 +64,7 @@ mod as_keyword {} /// } /// /// assert_eq!(last, 12); -/// println!("{}", last); +/// println!("{last}"); /// ``` /// /// A break expression is normally associated with the innermost loop enclosing the @@ -72,10 +72,10 @@ mod as_keyword {} /// ///```rust /// 'outer: for i in 1..=5 { -/// println!("outer iteration (i): {}", i); +/// println!("outer iteration (i): {i}"); /// /// '_inner: for j in 1..=200 { -/// println!(" inner iteration (j): {}", j); +/// println!(" inner iteration (j): {j}"); /// if j >= 3 { /// // breaks from inner loop, lets outer loop continue. /// break; @@ -106,7 +106,7 @@ mod as_keyword {} /// }; /// // first number in Fibonacci sequence over 10: /// assert_eq!(result, 13); -/// println!("{}", result); +/// println!("{result}"); /// ``` /// /// For more details consult the [Reference on "break expression"] and the [Reference on "break and @@ -200,7 +200,7 @@ mod const_keyword {} /// if number % 2 == 0 { /// continue; /// } -/// println!("{}", number); +/// println!("{number}"); /// } ///``` /// @@ -515,7 +515,7 @@ mod fn_keyword {} /// } /// /// for i in std::iter::repeat(5) { -/// println!("turns out {} never stops being 5", i); +/// println!("turns out {i} never stops being 5"); /// break; // would loop forever otherwise /// } /// @@ -776,7 +776,7 @@ mod in_keyword {} /// let shadowing_example = true; /// let shadowing_example = 123.4; /// let shadowing_example = shadowing_example as u32; -/// let mut shadowing_example = format!("cool! {}", shadowing_example); +/// let mut shadowing_example = format!("cool! {shadowing_example}"); /// shadowing_example += " something else!"; // not shadowing /// ``` /// @@ -805,7 +805,7 @@ mod let_keyword {} /// let mut counter = 0; /// /// while counter < 10 { -/// println!("{}", counter); +/// println!("{counter}"); /// counter += 1; /// } /// ``` @@ -836,7 +836,7 @@ mod let_keyword {} /// if i == 10 { /// counter = None; /// } else { -/// println!("{}", i); +/// println!("{i}"); /// counter = Some (i + 1); /// } /// } @@ -866,7 +866,7 @@ mod while_keyword {} /// /// let mut i = 1; /// loop { -/// println!("i is {}", i); +/// println!("i is {i}"); /// if i > 100 { /// break; /// } @@ -920,8 +920,8 @@ mod loop_keyword {} /// /// let a_number = Option::Some(10); /// match a_number { -/// Some(x) if x <= 5 => println!("0 to 5 num = {}", x), -/// Some(x @ 6..=10) => println!("6 to 10 num = {}", x), +/// Some(x) if x <= 5 => println!("0 to 5 num = {x}"), +/// Some(x @ 6..=10) => println!("6 to 10 num = {x}"), /// None => panic!(), /// // all other numbers /// _ => panic!(), @@ -940,8 +940,8 @@ mod loop_keyword {} /// /// let get_inner = Outer::Double(None, Some(String::new())); /// match get_inner { -/// Outer::Double(None, Some(st)) => println!("{}", st), -/// Outer::Single(opt) => println!("{:?}", opt), +/// Outer::Double(None, Some(st)) => println!("{st}"), +/// Outer::Single(opt) => println!("{opt:?}"), /// _ => panic!(), /// } /// ``` @@ -988,7 +988,7 @@ mod mod_keyword {} /// /// ```rust /// let data = vec![1, 2, 3]; -/// let closure = move || println!("captured {:?} by value", data); +/// let closure = move || println!("captured {data:?} by value"); /// /// // data is no longer available, it is owned by the closure /// ``` @@ -1001,7 +1001,7 @@ mod mod_keyword {} /// ```rust /// fn create_fn() -> impl Fn() { /// let text = "Fn".to_owned(); -/// move || println!("This is a: {}", text) +/// move || println!("This is a: {text}") /// } /// /// let fn_plain = create_fn(); @@ -1014,7 +1014,7 @@ mod mod_keyword {} /// let data = vec![1, 2, 3]; /// /// std::thread::spawn(move || { -/// println!("captured {:?} by value", data) +/// println!("captured {data:?} by value") /// }).join().unwrap(); /// /// // data was moved to the spawned thread, so we cannot use it here @@ -1025,7 +1025,7 @@ mod mod_keyword {} /// ```rust /// let capture = "hello".to_owned(); /// let block = async move { -/// println!("rust says {} from async block", capture); +/// println!("rust says {capture} from async block"); /// }; /// ``` /// @@ -1124,7 +1124,7 @@ mod pub_keyword {} /// let maybe_name = Some(String::from("Alice")); /// // The variable 'maybe_name' is consumed here ... /// match maybe_name { -/// Some(n) => println!("Hello, {}", n), +/// Some(n) => println!("Hello, {n}"), /// _ => println!("Hello, world"), /// } /// // ... and is now unavailable. @@ -1138,7 +1138,7 @@ mod pub_keyword {} /// let maybe_name = Some(String::from("Alice")); /// // Using `ref`, the value is borrowed, not moved ... /// match maybe_name { -/// Some(ref n) => println!("Hello, {}", n), +/// Some(ref n) => println!("Hello, {n}"), /// _ => println!("Hello, world"), /// } /// // ... so it's available here! @@ -1423,7 +1423,7 @@ mod self_upper_keyword {} /// // With a strictly read-only static, references will have the same address /// assert_eq!(r1, r2); /// // A static item can be used just like a variable in many cases -/// println!("{:?}", FOO); +/// println!("{FOO:?}"); /// ``` /// /// # Mutable `static`s @@ -1675,7 +1675,7 @@ mod super_keyword {} /// # #![allow(dead_code)] /// fn debug_iter(it: I) where I::Item: std::fmt::Debug { /// for elem in it { -/// println!("{:#?}", elem); +/// println!("{elem:#?}"); /// } /// } /// @@ -2313,7 +2313,7 @@ mod dyn_keyword {} /// match u { /// IntOrFloat { i: 10 } => println!("Found exactly ten!"), /// // Matching the field `f` provides an `f32`. -/// IntOrFloat { f } => println!("Found f = {} !", f), +/// IntOrFloat { f } => println!("Found f = {f} !"), /// } /// } /// ``` @@ -2337,7 +2337,7 @@ mod dyn_keyword {} /// let i = unsafe { &mut u.i }; /// /// *i = 10; -/// println!("f = {} and i = {}", f, i); +/// println!("f = {f} and i = {i}"); /// ``` /// /// See the [Reference][union] for more informations on `union`s. diff --git a/library/std/src/net/addr/tests.rs b/library/std/src/net/addr/tests.rs index 40f5a84bcd520..585a17451a0b7 100644 --- a/library/std/src/net/addr/tests.rs +++ b/library/std/src/net/addr/tests.rs @@ -169,30 +169,30 @@ fn is_v6() { fn socket_v4_to_str() { let socket = SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 8080); - assert_eq!(format!("{}", socket), "192.168.0.1:8080"); - assert_eq!(format!("{:<20}", socket), "192.168.0.1:8080 "); - assert_eq!(format!("{:>20}", socket), " 192.168.0.1:8080"); - assert_eq!(format!("{:^20}", socket), " 192.168.0.1:8080 "); - assert_eq!(format!("{:.10}", socket), "192.168.0."); + assert_eq!(format!("{socket}"), "192.168.0.1:8080"); + assert_eq!(format!("{socket:<20}"), "192.168.0.1:8080 "); + assert_eq!(format!("{socket:>20}"), " 192.168.0.1:8080"); + assert_eq!(format!("{socket:^20}"), " 192.168.0.1:8080 "); + assert_eq!(format!("{socket:.10}"), "192.168.0."); } #[test] fn socket_v6_to_str() { let mut socket = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53, 0, 0); - assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1]:53"); - assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1]:53 "); - assert_eq!(format!("{:>24}", socket), " [2a02:6b8:0:1::1]:53"); - assert_eq!(format!("{:^24}", socket), " [2a02:6b8:0:1::1]:53 "); - assert_eq!(format!("{:.15}", socket), "[2a02:6b8:0:1::"); + assert_eq!(format!("{socket}"), "[2a02:6b8:0:1::1]:53"); + assert_eq!(format!("{socket:<24}"), "[2a02:6b8:0:1::1]:53 "); + assert_eq!(format!("{socket:>24}"), " [2a02:6b8:0:1::1]:53"); + assert_eq!(format!("{socket:^24}"), " [2a02:6b8:0:1::1]:53 "); + assert_eq!(format!("{socket:.15}"), "[2a02:6b8:0:1::"); socket.set_scope_id(5); - assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1%5]:53"); - assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1%5]:53 "); - assert_eq!(format!("{:>24}", socket), " [2a02:6b8:0:1::1%5]:53"); - assert_eq!(format!("{:^24}", socket), " [2a02:6b8:0:1::1%5]:53 "); - assert_eq!(format!("{:.18}", socket), "[2a02:6b8:0:1::1%5"); + assert_eq!(format!("{socket}"), "[2a02:6b8:0:1::1%5]:53"); + assert_eq!(format!("{socket:<24}"), "[2a02:6b8:0:1::1%5]:53 "); + assert_eq!(format!("{socket:>24}"), " [2a02:6b8:0:1::1%5]:53"); + assert_eq!(format!("{socket:^24}"), " [2a02:6b8:0:1::1%5]:53 "); + assert_eq!(format!("{socket:.18}"), "[2a02:6b8:0:1::1%5"); } #[test] diff --git a/library/std/src/net/tcp.rs b/library/std/src/net/tcp.rs index cc4e4fd4fdc77..f5d3c4905e081 100644 --- a/library/std/src/net/tcp.rs +++ b/library/std/src/net/tcp.rs @@ -595,10 +595,10 @@ impl TcpStream { /// // via platform-specific APIs such as epoll or IOCP /// wait_for_fd(); /// } - /// Err(e) => panic!("encountered IO error: {}", e), + /// Err(e) => panic!("encountered IO error: {e}"), /// }; /// }; - /// println!("bytes: {:?}", buf); + /// println!("bytes: {buf:?}"); /// ``` #[stable(feature = "net2_mutators", since = "1.9.0")] pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { @@ -799,8 +799,8 @@ impl TcpListener { /// /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); /// match listener.accept() { - /// Ok((_socket, addr)) => println!("new client: {:?}", addr), - /// Err(e) => println!("couldn't get client: {:?}", e), + /// Ok((_socket, addr)) => println!("new client: {addr:?}"), + /// Err(e) => println!("couldn't get client: {e:?}"), /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -991,7 +991,7 @@ impl TcpListener { /// wait_for_fd(); /// continue; /// } - /// Err(e) => panic!("encountered IO error: {}", e), + /// Err(e) => panic!("encountered IO error: {e}"), /// } /// } /// ``` diff --git a/library/std/src/net/tcp/tests.rs b/library/std/src/net/tcp/tests.rs index 4d5cf658def0d..8c0adcfb0ebbb 100644 --- a/library/std/src/net/tcp/tests.rs +++ b/library/std/src/net/tcp/tests.rs @@ -142,8 +142,7 @@ fn write_close() { e.kind() == ErrorKind::ConnectionReset || e.kind() == ErrorKind::BrokenPipe || e.kind() == ErrorKind::ConnectionAborted, - "unknown error: {}", - e + "unknown error: {e}" ); } } @@ -655,7 +654,7 @@ fn debug() { inner_name, render_inner(&listener) ); - assert_eq!(format!("{:?}", listener), compare); + assert_eq!(format!("{listener:?}"), compare); let stream = t!(TcpStream::connect(&("localhost", socket_addr.port()))); let compare = format!( @@ -665,7 +664,7 @@ fn debug() { inner_name, render_inner(&stream) ); - assert_eq!(format!("{:?}", stream), compare); + assert_eq!(format!("{stream:?}"), compare); } // FIXME: re-enabled openbsd tests once their socket timeout code @@ -832,7 +831,7 @@ fn set_nonblocking() { match stream.read(&mut buf) { Ok(_) => panic!("expected error"), Err(ref e) if e.kind() == ErrorKind::WouldBlock => {} - Err(e) => panic!("unexpected error {}", e), + Err(e) => panic!("unexpected error {e}"), } } @@ -862,7 +861,7 @@ fn peek() { match c.peek(&mut b) { Ok(_) => panic!("expected error"), Err(ref e) if e.kind() == ErrorKind::WouldBlock => {} - Err(e) => panic!("unexpected error {}", e), + Err(e) => panic!("unexpected error {e}"), } t!(txdone.send(())); }) diff --git a/library/std/src/net/udp.rs b/library/std/src/net/udp.rs index 11a696e92c825..864e1b0f3450a 100644 --- a/library/std/src/net/udp.rs +++ b/library/std/src/net/udp.rs @@ -605,9 +605,9 @@ impl UdpSocket { /// /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address"); /// match socket.take_error() { - /// Ok(Some(error)) => println!("UdpSocket error: {:?}", error), + /// Ok(Some(error)) => println!("UdpSocket error: {error:?}"), /// Ok(None) => println!("No error"), - /// Err(error) => println!("UdpSocket.take_error failed: {:?}", error), + /// Err(error) => println!("UdpSocket.take_error failed: {error:?}"), /// } /// ``` #[stable(feature = "net2_mutators", since = "1.9.0")] @@ -686,8 +686,8 @@ impl UdpSocket { /// socket.connect("127.0.0.1:8080").expect("connect function failed"); /// let mut buf = [0; 10]; /// match socket.recv(&mut buf) { - /// Ok(received) => println!("received {} bytes {:?}", received, &buf[..received]), - /// Err(e) => println!("recv function failed: {:?}", e), + /// Ok(received) => println!("received {received} bytes {:?}", &buf[..received]), + /// Err(e) => println!("recv function failed: {e:?}"), /// } /// ``` #[stable(feature = "net2_mutators", since = "1.9.0")] @@ -726,8 +726,8 @@ impl UdpSocket { /// socket.connect("127.0.0.1:8080").expect("connect function failed"); /// let mut buf = [0; 10]; /// match socket.peek(&mut buf) { - /// Ok(received) => println!("received {} bytes", received), - /// Err(e) => println!("peek function failed: {:?}", e), + /// Ok(received) => println!("received {received} bytes"), + /// Err(e) => println!("peek function failed: {e:?}"), /// } /// ``` #[stable(feature = "peek", since = "1.18.0")] @@ -770,7 +770,7 @@ impl UdpSocket { /// // via platform-specific APIs such as epoll or IOCP /// wait_for_fd(); /// } - /// Err(e) => panic!("encountered IO error: {}", e), + /// Err(e) => panic!("encountered IO error: {e}"), /// } /// }; /// println!("bytes: {:?}", &buf[..num_bytes_read]); diff --git a/library/std/src/net/udp/tests.rs b/library/std/src/net/udp/tests.rs index a51113dd9e749..f82904ffbbf77 100644 --- a/library/std/src/net/udp/tests.rs +++ b/library/std/src/net/udp/tests.rs @@ -173,8 +173,8 @@ fn debug() { let udpsock = t!(UdpSocket::bind(&socket_addr)); let udpsock_inner = udpsock.0.socket().as_raw(); - let compare = format!("UdpSocket {{ addr: {:?}, {}: {:?} }}", socket_addr, name, udpsock_inner); - assert_eq!(format!("{:?}", udpsock), compare); + let compare = format!("UdpSocket {{ addr: {socket_addr:?}, {name}: {udpsock_inner:?} }}"); + assert_eq!(format!("{udpsock:?}"), compare); } // FIXME: re-enabled openbsd/netbsd tests once their socket timeout code @@ -359,7 +359,7 @@ fn set_nonblocking() { match socket.recv(&mut buf) { Ok(_) => panic!("expected error"), Err(ref e) if e.kind() == ErrorKind::WouldBlock => {} - Err(e) => panic!("unexpected error {}", e), + Err(e) => panic!("unexpected error {e}"), } }) } diff --git a/library/std/src/os/unix/fs.rs b/library/std/src/os/unix/fs.rs index 75d65e6d5fc03..3fc6cc44ce4c8 100644 --- a/library/std/src/os/unix/fs.rs +++ b/library/std/src/os/unix/fs.rs @@ -47,7 +47,7 @@ pub trait FileExt { /// /// // We now read 8 bytes from the offset 10. /// let num_bytes_read = file.read_at(&mut buf, 10)?; - /// println!("read {} bytes: {:?}", num_bytes_read, buf); + /// println!("read {num_bytes_read} bytes: {buf:?}"); /// Ok(()) /// } /// ``` @@ -861,7 +861,7 @@ pub trait DirEntryExt2: Sealed { /// entries.sort_unstable_by(|a, b| a.file_name_ref().cmp(b.file_name_ref())); /// /// for p in entries { - /// println!("{:?}", p); + /// println!("{p:?}"); /// } /// /// Ok(()) diff --git a/library/std/src/os/unix/net/addr.rs b/library/std/src/os/unix/net/addr.rs index 034fa301ba1ea..ba65d8f285e48 100644 --- a/library/std/src/os/unix/net/addr.rs +++ b/library/std/src/os/unix/net/addr.rs @@ -86,7 +86,7 @@ impl<'a> fmt::Display for AsciiEscaped<'a> { /// let socket = match UnixListener::bind("/tmp/sock") { /// Ok(sock) => sock, /// Err(e) => { -/// println!("Couldn't bind: {:?}", e); +/// println!("Couldn't bind: {e:?}"); /// return /// } /// }; @@ -307,7 +307,7 @@ impl SocketAddr { /// let listener = match UnixListener::bind_addr(&addr) { /// Ok(sock) => sock, /// Err(err) => { - /// println!("Couldn't bind: {:?}", err); + /// println!("Couldn't bind: {err:?}"); /// return Err(err); /// } /// }; @@ -346,7 +346,7 @@ impl fmt::Debug for SocketAddr { match self.address() { AddressKind::Unnamed => write!(fmt, "(unnamed)"), AddressKind::Abstract(name) => write!(fmt, "{} (abstract)", AsciiEscaped(name)), - AddressKind::Pathname(path) => write!(fmt, "{:?} (pathname)", path), + AddressKind::Pathname(path) => write!(fmt, "{path:?} (pathname)"), } } } diff --git a/library/std/src/os/unix/net/ancillary.rs b/library/std/src/os/unix/net/ancillary.rs index 6e6f5212b4651..fb1ff4b725ced 100644 --- a/library/std/src/os/unix/net/ancillary.rs +++ b/library/std/src/os/unix/net/ancillary.rs @@ -396,7 +396,7 @@ impl<'a> Iterator for Messages<'a> { /// for ancillary_result in ancillary.messages() { /// if let AncillaryData::ScmRights(scm_rights) = ancillary_result.unwrap() { /// for fd in scm_rights { -/// println!("receive file descriptor: {}", fd); +/// println!("receive file descriptor: {fd}"); /// } /// } /// } @@ -568,7 +568,7 @@ impl<'a> SocketAncillary<'a> { /// for ancillary_result in ancillary.messages() { /// if let AncillaryData::ScmRights(scm_rights) = ancillary_result.unwrap() { /// for fd in scm_rights { - /// println!("receive file descriptor: {}", fd); + /// println!("receive file descriptor: {fd}"); /// } /// } /// } @@ -579,7 +579,7 @@ impl<'a> SocketAncillary<'a> { /// for ancillary_result in ancillary.messages() { /// if let AncillaryData::ScmRights(scm_rights) = ancillary_result.unwrap() { /// for fd in scm_rights { - /// println!("receive file descriptor: {}", fd); + /// println!("receive file descriptor: {fd}"); /// } /// } /// } diff --git a/library/std/src/os/unix/net/datagram.rs b/library/std/src/os/unix/net/datagram.rs index a2caccc784917..59c91e9a82e1a 100644 --- a/library/std/src/os/unix/net/datagram.rs +++ b/library/std/src/os/unix/net/datagram.rs @@ -95,7 +95,7 @@ impl UnixDatagram { /// let sock = match UnixDatagram::bind("/path/to/the/socket") { /// Ok(sock) => sock, /// Err(e) => { - /// println!("Couldn't bind: {:?}", e); + /// println!("Couldn't bind: {e:?}"); /// return /// } /// }; @@ -127,7 +127,7 @@ impl UnixDatagram { /// let sock2 = match UnixDatagram::bind_addr(&addr) { /// Ok(sock) => sock, /// Err(err) => { - /// println!("Couldn't bind: {:?}", err); + /// println!("Couldn't bind: {err:?}"); /// return Err(err); /// } /// }; @@ -157,7 +157,7 @@ impl UnixDatagram { /// let sock = match UnixDatagram::unbound() { /// Ok(sock) => sock, /// Err(e) => { - /// println!("Couldn't unbound: {:?}", e); + /// println!("Couldn't unbound: {e:?}"); /// return /// } /// }; @@ -180,7 +180,7 @@ impl UnixDatagram { /// let (sock1, sock2) = match UnixDatagram::pair() { /// Ok((sock1, sock2)) => (sock1, sock2), /// Err(e) => { - /// println!("Couldn't unbound: {:?}", e); + /// println!("Couldn't unbound: {e:?}"); /// return /// } /// }; @@ -210,7 +210,7 @@ impl UnixDatagram { /// match sock.connect("/path/to/the/socket") { /// Ok(sock) => sock, /// Err(e) => { - /// println!("Couldn't connect: {:?}", e); + /// println!("Couldn't connect: {e:?}"); /// return Err(e) /// } /// }; @@ -243,7 +243,7 @@ impl UnixDatagram { /// match sock.connect_addr(&addr) { /// Ok(sock) => sock, /// Err(e) => { - /// println!("Couldn't connect: {:?}", e); + /// println!("Couldn't connect: {e:?}"); /// return Err(e) /// } /// }; @@ -367,7 +367,7 @@ impl UnixDatagram { /// let sock = UnixDatagram::unbound()?; /// let mut buf = vec![0; 10]; /// let (size, sender) = sock.recv_from(buf.as_mut_slice())?; - /// println!("received {} bytes from {:?}", size, sender); + /// println!("received {size} bytes from {sender:?}"); /// Ok(()) /// } /// ``` @@ -422,11 +422,11 @@ impl UnixDatagram { /// let mut ancillary_buffer = [0; 128]; /// let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]); /// let (size, _truncated, sender) = sock.recv_vectored_with_ancillary_from(bufs, &mut ancillary)?; - /// println!("received {}", size); + /// println!("received {size}"); /// for ancillary_result in ancillary.messages() { /// if let AncillaryData::ScmRights(scm_rights) = ancillary_result.unwrap() { /// for fd in scm_rights { - /// println!("receive file descriptor: {}", fd); + /// println!("receive file descriptor: {fd}"); /// } /// } /// } @@ -479,11 +479,11 @@ impl UnixDatagram { /// let mut ancillary_buffer = [0; 128]; /// let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]); /// let (size, _truncated) = sock.recv_vectored_with_ancillary(bufs, &mut ancillary)?; - /// println!("received {}", size); + /// println!("received {size}"); /// for ancillary_result in ancillary.messages() { /// if let AncillaryData::ScmRights(scm_rights) = ancillary_result.unwrap() { /// for fd in scm_rights { - /// println!("receive file descriptor: {}", fd); + /// println!("receive file descriptor: {fd}"); /// } /// } /// } @@ -893,7 +893,7 @@ impl UnixDatagram { /// fn main() -> std::io::Result<()> { /// let sock = UnixDatagram::unbound()?; /// if let Ok(Some(err)) = sock.take_error() { - /// println!("Got error: {:?}", err); + /// println!("Got error: {err:?}"); /// } /// Ok(()) /// } diff --git a/library/std/src/os/unix/net/listener.rs b/library/std/src/os/unix/net/listener.rs index b23dd6062f682..8e11d32f13071 100644 --- a/library/std/src/os/unix/net/listener.rs +++ b/library/std/src/os/unix/net/listener.rs @@ -63,7 +63,7 @@ impl UnixListener { /// let listener = match UnixListener::bind("/path/to/the/socket") { /// Ok(sock) => sock, /// Err(e) => { - /// println!("Couldn't connect: {:?}", e); + /// println!("Couldn't connect: {e:?}"); /// return /// } /// }; @@ -98,7 +98,7 @@ impl UnixListener { /// let listener2 = match UnixListener::bind_addr(&addr) { /// Ok(sock) => sock, /// Err(err) => { - /// println!("Couldn't bind: {:?}", err); + /// println!("Couldn't bind: {err:?}"); /// return Err(err); /// } /// }; @@ -136,8 +136,8 @@ impl UnixListener { /// let listener = UnixListener::bind("/path/to/the/socket")?; /// /// match listener.accept() { - /// Ok((socket, addr)) => println!("Got a client: {:?}", addr), - /// Err(e) => println!("accept function failed: {:?}", e), + /// Ok((socket, addr)) => println!("Got a client: {addr:?}"), + /// Err(e) => println!("accept function failed: {e:?}"), /// } /// Ok(()) /// } @@ -226,7 +226,7 @@ impl UnixListener { /// let listener = UnixListener::bind("/tmp/sock")?; /// /// if let Ok(Some(err)) = listener.take_error() { - /// println!("Got error: {:?}", err); + /// println!("Got error: {err:?}"); /// } /// Ok(()) /// } diff --git a/library/std/src/os/unix/net/stream.rs b/library/std/src/os/unix/net/stream.rs index 583f861a92535..3943b4fed0949 100644 --- a/library/std/src/os/unix/net/stream.rs +++ b/library/std/src/os/unix/net/stream.rs @@ -57,7 +57,7 @@ pub use ucred::UCred; /// stream.write_all(b"hello world")?; /// let mut response = String::new(); /// stream.read_to_string(&mut response)?; -/// println!("{}", response); +/// println!("{response}"); /// Ok(()) /// } /// ``` @@ -90,7 +90,7 @@ impl UnixStream { /// let socket = match UnixStream::connect("/tmp/sock") { /// Ok(sock) => sock, /// Err(e) => { - /// println!("Couldn't connect: {:?}", e); + /// println!("Couldn't connect: {e:?}"); /// return /// } /// }; @@ -123,7 +123,7 @@ impl UnixStream { /// let sock = match UnixStream::connect_addr(&addr) { /// Ok(sock) => sock, /// Err(e) => { - /// println!("Couldn't connect: {:?}", e); + /// println!("Couldn't connect: {e:?}"); /// return Err(e) /// } /// }; @@ -155,7 +155,7 @@ impl UnixStream { /// let (sock1, sock2) = match UnixStream::pair() { /// Ok((sock1, sock2)) => (sock1, sock2), /// Err(e) => { - /// println!("Couldn't create a pair of sockets: {:?}", e); + /// println!("Couldn't create a pair of sockets: {e:?}"); /// return /// } /// }; @@ -443,7 +443,7 @@ impl UnixStream { /// fn main() -> std::io::Result<()> { /// let socket = UnixStream::connect("/tmp/sock")?; /// if let Ok(Some(err)) = socket.take_error() { - /// println!("Got error: {:?}", err); + /// println!("Got error: {err:?}"); /// } /// Ok(()) /// } @@ -530,11 +530,11 @@ impl UnixStream { /// let mut ancillary_buffer = [0; 128]; /// let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]); /// let size = socket.recv_vectored_with_ancillary(bufs, &mut ancillary)?; - /// println!("received {}", size); + /// println!("received {size}"); /// for ancillary_result in ancillary.messages() { /// if let AncillaryData::ScmRights(scm_rights) = ancillary_result.unwrap() { /// for fd in scm_rights { - /// println!("receive file descriptor: {}", fd); + /// println!("receive file descriptor: {fd}"); /// } /// } /// } diff --git a/library/std/src/os/unix/net/tests.rs b/library/std/src/os/unix/net/tests.rs index 7ad4a02611e07..aa0df61c1920d 100644 --- a/library/std/src/os/unix/net/tests.rs +++ b/library/std/src/os/unix/net/tests.rs @@ -29,7 +29,7 @@ macro_rules! or_panic { ($e:expr) => { match $e { Ok(e) => e, - Err(e) => panic!("{}", e), + Err(e) => panic!("{e}"), } }; } @@ -161,19 +161,19 @@ fn long_path() { ); match UnixStream::connect(&socket_path) { Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {} - Err(e) => panic!("unexpected error {}", e), + Err(e) => panic!("unexpected error {e}"), Ok(_) => panic!("unexpected success"), } match UnixListener::bind(&socket_path) { Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {} - Err(e) => panic!("unexpected error {}", e), + Err(e) => panic!("unexpected error {e}"), Ok(_) => panic!("unexpected success"), } match UnixDatagram::bind(&socket_path) { Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {} - Err(e) => panic!("unexpected error {}", e), + Err(e) => panic!("unexpected error {e}"), Ok(_) => panic!("unexpected success"), } } @@ -524,7 +524,7 @@ fn test_abstract_namespace_too_long() { jklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", ) { Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {} - Err(e) => panic!("unexpected error {}", e), + Err(e) => panic!("unexpected error {e}"), Ok(_) => panic!("unexpected success"), } } @@ -564,7 +564,7 @@ fn test_unix_stream_peek() { match stream.peek(&mut buf) { Ok(_) => panic!("expected error"), Err(ref e) if e.kind() == ErrorKind::WouldBlock => {} - Err(e) => panic!("unexpected error: {}", e), + Err(e) => panic!("unexpected error: {e}"), } or_panic!(txdone.send(())); diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs index 2b9ae3210de25..03de7eed6d4c8 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -283,7 +283,7 @@ fn default_hook(info: &PanicInfo<'_>) { let name = thread.as_ref().and_then(|t| t.name()).unwrap_or(""); let write = |err: &mut dyn crate::io::Write| { - let _ = writeln!(err, "thread '{}' panicked at '{}', {}", name, msg, location); + let _ = writeln!(err, "thread '{name}' panicked at '{msg}', {location}"); static FIRST_PANIC: AtomicBool = AtomicBool::new(true); @@ -677,7 +677,7 @@ fn rust_panic_with_hook( // Unfortunately, this does not print a backtrace, because creating // a `Backtrace` will allocate, which we must to avoid here. let panicinfo = PanicInfo::internal_constructor(message, location, can_unwind); - rtprintpanic!("{}\npanicked after panic::always_abort(), aborting.\n", panicinfo); + rtprintpanic!("{panicinfo}\npanicked after panic::always_abort(), aborting.\n"); } crate::sys::abort_internal(); } @@ -745,5 +745,5 @@ fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! { let obj = &mut msg as *mut &mut dyn BoxMeUp; __rust_start_panic(obj) }; - rtabort!("failed to initiate panic, error {}", code) + rtabort!("failed to initiate panic, error {code}") } diff --git a/library/std/src/path.rs b/library/std/src/path.rs index e544608f83c29..bcf5c9328b79c 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -592,7 +592,7 @@ impl AsRef for Component<'_> { /// let path = Path::new("/tmp/foo/bar.txt"); /// /// for component in path.components() { -/// println!("{:?}", component); +/// println!("{component:?}"); /// } /// ``` /// diff --git a/library/std/src/path/tests.rs b/library/std/src/path/tests.rs index 6e863787b7f39..c8dc768d3fc8e 100644 --- a/library/std/src/path/tests.rs +++ b/library/std/src/path/tests.rs @@ -1586,17 +1586,17 @@ fn test_components_debug() { let mut components = path.components(); let expected = "Components([RootDir, Normal(\"tmp\")])"; - let actual = format!("{:?}", components); + let actual = format!("{components:?}"); assert_eq!(expected, actual); let _ = components.next().unwrap(); let expected = "Components([Normal(\"tmp\")])"; - let actual = format!("{:?}", components); + let actual = format!("{components:?}"); assert_eq!(expected, actual); let _ = components.next().unwrap(); let expected = "Components([])"; - let actual = format!("{:?}", components); + let actual = format!("{components:?}"); assert_eq!(expected, actual); } @@ -1608,17 +1608,17 @@ fn test_iter_debug() { let mut iter = path.iter(); let expected = "Iter([\"/\", \"tmp\"])"; - let actual = format!("{:?}", iter); + let actual = format!("{iter:?}"); assert_eq!(expected, actual); let _ = iter.next().unwrap(); let expected = "Iter([\"tmp\"])"; - let actual = format!("{:?}", iter); + let actual = format!("{iter:?}"); assert_eq!(expected, actual); let _ = iter.next().unwrap(); let expected = "Iter([])"; - let actual = format!("{:?}", iter); + let actual = format!("{iter:?}"); assert_eq!(expected, actual); } @@ -1770,7 +1770,7 @@ fn test_windows_absolute() { fn bench_path_cmp_fast_path_buf_sort(b: &mut test::Bencher) { let prefix = "my/home"; let mut paths: Vec<_> = - (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {}.rs", num))).collect(); + (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); paths.sort(); @@ -1783,7 +1783,7 @@ fn bench_path_cmp_fast_path_buf_sort(b: &mut test::Bencher) { fn bench_path_cmp_fast_path_long(b: &mut test::Bencher) { let prefix = "/my/home/is/my/castle/and/my/castle/has/a/rusty/workbench/"; let paths: Vec<_> = - (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {}.rs", num))).collect(); + (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); let mut set = BTreeSet::new(); @@ -1801,7 +1801,7 @@ fn bench_path_cmp_fast_path_long(b: &mut test::Bencher) { fn bench_path_cmp_fast_path_short(b: &mut test::Bencher) { let prefix = "my/home"; let paths: Vec<_> = - (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {}.rs", num))).collect(); + (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); let mut set = BTreeSet::new(); @@ -1819,7 +1819,7 @@ fn bench_path_cmp_fast_path_short(b: &mut test::Bencher) { fn bench_path_hashset(b: &mut test::Bencher) { let prefix = "/my/home/is/my/castle/and/my/castle/has/a/rusty/workbench/"; let paths: Vec<_> = - (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {}.rs", num))).collect(); + (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); let mut set = HashSet::new(); @@ -1837,7 +1837,7 @@ fn bench_path_hashset(b: &mut test::Bencher) { fn bench_path_hashset_miss(b: &mut test::Bencher) { let prefix = "/my/home/is/my/castle/and/my/castle/has/a/rusty/workbench/"; let paths: Vec<_> = - (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {}.rs", num))).collect(); + (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); let mut set = HashSet::new(); diff --git a/library/std/src/primitive_docs.rs b/library/std/src/primitive_docs.rs index ebb1d8971b99d..225a679efd221 100644 --- a/library/std/src/primitive_docs.rs +++ b/library/std/src/primitive_docs.rs @@ -607,7 +607,7 @@ mod prim_pointer {} /// /// // This loop prints: 0 1 2 /// for x in array { -/// print!("{} ", x); +/// print!("{x} "); /// } /// ``` /// @@ -646,19 +646,19 @@ mod prim_pointer {} /// // This creates a slice iterator, producing references to each value. /// for item in array.into_iter().enumerate() { /// let (i, x): (usize, &i32) = item; -/// println!("array[{}] = {}", i, x); +/// println!("array[{i}] = {x}"); /// } /// /// // The `array_into_iter` lint suggests this change for future compatibility: /// for item in array.iter().enumerate() { /// let (i, x): (usize, &i32) = item; -/// println!("array[{}] = {}", i, x); +/// println!("array[{i}] = {x}"); /// } /// /// // You can explicitly iterate an array by value using `IntoIterator::into_iter` /// for item in IntoIterator::into_iter(array).enumerate() { /// let (i, x): (usize, i32) = item; -/// println!("array[{}] = {}", i, x); +/// println!("array[{i}] = {x}"); /// } /// ``` /// @@ -673,13 +673,13 @@ mod prim_pointer {} /// // This iterates by reference: /// for item in array.iter().enumerate() { /// let (i, x): (usize, &i32) = item; -/// println!("array[{}] = {}", i, x); +/// println!("array[{i}] = {x}"); /// } /// /// // This iterates by value: /// for item in array.into_iter().enumerate() { /// let (i, x): (usize, i32) = item; -/// println!("array[{}] = {}", i, x); +/// println!("array[{i}] = {x}"); /// } /// ``` /// @@ -702,26 +702,26 @@ mod prim_pointer {} /// // This iterates by reference: /// for item in array.iter() { /// let x: &i32 = item; -/// println!("{}", x); +/// println!("{x}"); /// } /// /// // This iterates by value: /// for item in IntoIterator::into_iter(array) { /// let x: i32 = item; -/// println!("{}", x); +/// println!("{x}"); /// } /// /// // This iterates by value: /// for item in array { /// let x: i32 = item; -/// println!("{}", x); +/// println!("{x}"); /// } /// /// // IntoIter can also start a chain. /// // This iterates by value: /// for item in IntoIterator::into_iter(array).enumerate() { /// let (i, x): (usize, i32) = item; -/// println!("array[{}] = {}", i, x); +/// println!("array[{i}] = {x}"); /// } /// ``` /// diff --git a/library/std/src/process.rs b/library/std/src/process.rs index e3fff155e4722..d88ab6253712a 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -915,7 +915,7 @@ impl Command { /// .status() /// .expect("failed to execute process"); /// - /// println!("process finished with: {}", status); + /// println!("process finished with: {status}"); /// /// assert!(status.success()); /// ``` @@ -1434,7 +1434,7 @@ impl ExitStatus { /// .status() /// .expect("ls could not be executed"); /// - /// println!("ls: {}", status); + /// println!("ls: {status}"); /// status.exit_ok().expect_err("/dev/nonexistent could be listed!"); /// # } // cfg!(unix) /// ``` @@ -1459,7 +1459,7 @@ impl ExitStatus { /// if status.success() { /// println!("'projects/' directory created"); /// } else { - /// println!("failed to create 'projects/' directory: {}", status); + /// println!("failed to create 'projects/' directory: {status}"); /// } /// ``` #[must_use] @@ -1490,7 +1490,7 @@ impl ExitStatus { /// .expect("failed to execute mkdir"); /// /// match status.code() { - /// Some(code) => println!("Exited with status code: {}", code), + /// Some(code) => println!("Exited with status code: {code}"), /// None => println!("Process terminated by signal") /// } /// ``` @@ -1806,13 +1806,13 @@ impl Child { /// let mut child = Command::new("ls").spawn().unwrap(); /// /// match child.try_wait() { - /// Ok(Some(status)) => println!("exited with: {}", status), + /// Ok(Some(status)) => println!("exited with: {status}"), /// Ok(None) => { /// println!("status not ready yet, let's really wait"); /// let res = child.wait(); - /// println!("result: {:?}", res); + /// println!("result: {res:?}"); /// } - /// Err(e) => println!("error attempting to wait: {}", e), + /// Err(e) => println!("error attempting to wait: {e}"), /// } /// ``` #[stable(feature = "process_try_wait", since = "1.18.0")] @@ -1912,7 +1912,7 @@ impl Child { /// std::process::exit(match run_app() { /// Ok(_) => 0, /// Err(err) => { -/// eprintln!("error: {:?}", err); +/// eprintln!("error: {err:?}"); /// 1 /// } /// }); @@ -2071,7 +2071,7 @@ impl Termination for ! { impl Termination for Result { fn report(self) -> ExitCode { let Err(err) = self; - eprintln!("Error: {:?}", err); + eprintln!("Error: {err:?}"); ExitCode::FAILURE.report() } } diff --git a/library/std/src/process/tests.rs b/library/std/src/process/tests.rs index e5cdc4737068a..4f779ab4e786c 100644 --- a/library/std/src/process/tests.rs +++ b/library/std/src/process/tests.rs @@ -64,7 +64,7 @@ fn signal_reported_right() { p.kill().unwrap(); match p.wait().unwrap().signal() { Some(9) => {} - result => panic!("not terminated by signal 9 (instead, {:?})", result), + result => panic!("not terminated by signal 9 (instead, {result:?})"), } } @@ -252,8 +252,7 @@ fn test_override_env() { assert!( output.contains("RUN_TEST_NEW_ENV=123"), - "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", - output + "didn't find RUN_TEST_NEW_ENV inside of:\n\n{output}", ); } @@ -265,8 +264,7 @@ fn test_add_to_env() { assert!( output.contains("RUN_TEST_NEW_ENV=123"), - "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", - output + "didn't find RUN_TEST_NEW_ENV inside of:\n\n{output}" ); } @@ -288,13 +286,11 @@ fn test_capture_env_at_spawn() { assert!( output.contains("RUN_TEST_NEW_ENV1=123"), - "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}", - output + "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{output}" ); assert!( output.contains("RUN_TEST_NEW_ENV2=456"), - "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}", - output + "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{output}" ); } diff --git a/library/std/src/sync/mod.rs b/library/std/src/sync/mod.rs index ee35598bab5fe..87d01daeafc4c 100644 --- a/library/std/src/sync/mod.rs +++ b/library/std/src/sync/mod.rs @@ -19,7 +19,7 @@ //! B = 4; //! A = A + B; //! C = B; -//! println!("{} {} {}", A, B, C); +//! println!("{A} {B} {C}"); //! C = A; //! } //! } diff --git a/library/std/src/sync/mpsc/mod.rs b/library/std/src/sync/mpsc/mod.rs index 2e54321e127c0..e85a872396518 100644 --- a/library/std/src/sync/mpsc/mod.rs +++ b/library/std/src/sync/mpsc/mod.rs @@ -129,7 +129,7 @@ //! //! // Unbounded receiver waiting for all senders to complete. //! while let Ok(msg) = rx.recv() { -//! println!("{}", msg); +//! println!("{msg}"); //! } //! //! println!("completed"); @@ -376,7 +376,7 @@ impl !Sync for Receiver {} /// }); /// /// for x in recv.iter() { -/// println!("Got: {}", x); +/// println!("Got: {x}"); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -419,7 +419,7 @@ pub struct Iter<'a, T: 'a> { /// thread::sleep(Duration::from_secs(2)); // block for two seconds /// /// for x in receiver.try_iter() { -/// println!("Got: {}", x); +/// println!("Got: {x}"); /// } /// ``` #[stable(feature = "receiver_try_iter", since = "1.15.0")] @@ -453,7 +453,7 @@ pub struct TryIter<'a, T: 'a> { /// }); /// /// for x in recv.into_iter() { -/// println!("Got: {}", x); +/// println!("Got: {x}"); /// } /// ``` #[stable(feature = "receiver_into_iter", since = "1.1.0")] @@ -544,16 +544,16 @@ impl !Sync for Sender {} /// let mut msg; /// /// msg = receiver.recv().unwrap(); -/// println!("message {} received", msg); +/// println!("message {msg} received"); /// /// // "Thread unblocked!" will be printed now /// /// msg = receiver.recv().unwrap(); -/// println!("message {} received", msg); +/// println!("message {msg} received"); /// /// msg = receiver.recv().unwrap(); /// -/// println!("message {} received", msg); +/// println!("message {msg} received"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub struct SyncSender { @@ -996,14 +996,14 @@ impl SyncSender { /// /// let mut msg; /// msg = receiver.recv().unwrap(); - /// println!("message {} received", msg); + /// println!("message {msg} received"); /// /// msg = receiver.recv().unwrap(); - /// println!("message {} received", msg); + /// println!("message {msg} received"); /// /// // Third message may have never been sent /// match receiver.try_recv() { - /// Ok(msg) => println!("message {} received", msg), + /// Ok(msg) => println!("message {msg} received"), /// Err(_) => println!("the third message was never sent"), /// } /// ``` diff --git a/library/std/src/sync/mpsc/shared.rs b/library/std/src/sync/mpsc/shared.rs index 8487a5f8b50d3..5616265554410 100644 --- a/library/std/src/sync/mpsc/shared.rs +++ b/library/std/src/sync/mpsc/shared.rs @@ -369,7 +369,7 @@ impl Packet { match self.channels.fetch_sub(1, Ordering::SeqCst) { 1 => {} n if n > 1 => return, - n => panic!("bad number of channels left {}", n), + n => panic!("bad number of channels left {n}"), } match self.cnt.swap(DISCONNECTED, Ordering::SeqCst) { diff --git a/library/std/src/sync/mutex/tests.rs b/library/std/src/sync/mutex/tests.rs index a1b5aeddcb66a..93900566f1194 100644 --- a/library/std/src/sync/mutex/tests.rs +++ b/library/std/src/sync/mutex/tests.rs @@ -94,7 +94,7 @@ fn test_into_inner_poison() { assert!(m.is_poisoned()); match Arc::try_unwrap(m).unwrap().into_inner() { Err(e) => assert_eq!(e.into_inner(), NonCopy(10)), - Ok(x) => panic!("into_inner of poisoned Mutex is Ok: {:?}", x), + Ok(x) => panic!("into_inner of poisoned Mutex is Ok: {x:?}"), } } @@ -118,7 +118,7 @@ fn test_get_mut_poison() { assert!(m.is_poisoned()); match Arc::try_unwrap(m).unwrap().get_mut() { Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)), - Ok(x) => panic!("get_mut of poisoned Mutex is Ok: {:?}", x), + Ok(x) => panic!("get_mut of poisoned Mutex is Ok: {x:?}"), } } diff --git a/library/std/src/sync/poison.rs b/library/std/src/sync/poison.rs index fa950331e644a..07a90da449c9d 100644 --- a/library/std/src/sync/poison.rs +++ b/library/std/src/sync/poison.rs @@ -73,7 +73,7 @@ pub struct Guard { /// Ok(_) => unreachable!(), /// Err(p_err) => { /// let data = p_err.get_ref(); -/// println!("recovered: {}", data); +/// println!("recovered: {data}"); /// } /// }; /// ``` diff --git a/library/std/src/sync/rwlock/tests.rs b/library/std/src/sync/rwlock/tests.rs index e9b74fb3ecc86..53aa2b1e38a91 100644 --- a/library/std/src/sync/rwlock/tests.rs +++ b/library/std/src/sync/rwlock/tests.rs @@ -218,7 +218,7 @@ fn test_into_inner_poison() { assert!(m.is_poisoned()); match Arc::try_unwrap(m).unwrap().into_inner() { Err(e) => assert_eq!(e.into_inner(), NonCopy(10)), - Ok(x) => panic!("into_inner of poisoned RwLock is Ok: {:?}", x), + Ok(x) => panic!("into_inner of poisoned RwLock is Ok: {x:?}"), } } @@ -242,6 +242,6 @@ fn test_get_mut_poison() { assert!(m.is_poisoned()); match Arc::try_unwrap(m).unwrap().get_mut() { Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)), - Ok(x) => panic!("get_mut of poisoned RwLock is Ok: {:?}", x), + Ok(x) => panic!("get_mut of poisoned RwLock is Ok: {x:?}"), } } diff --git a/library/std/src/sys/sgx/abi/mod.rs b/library/std/src/sys/sgx/abi/mod.rs index 5df08a4ff593c..9508c38741551 100644 --- a/library/std/src/sys/sgx/abi/mod.rs +++ b/library/std/src/sys/sgx/abi/mod.rs @@ -95,7 +95,7 @@ extern "C" fn entry(p1: u64, p2: u64, p3: u64, secondary: bool, p4: u64, p5: u64 pub(super) fn exit_with_code(code: isize) -> ! { if code != 0 { if let Some(mut out) = panic::SgxPanicOutput::new() { - let _ = write!(out, "Exited with status code {}", code); + let _ = write!(out, "Exited with status code {code}"); } } usercalls::exit(code != 0); diff --git a/library/std/src/sys/sgx/abi/usercalls/mod.rs b/library/std/src/sys/sgx/abi/usercalls/mod.rs index a6a659df291fc..4030355f13518 100644 --- a/library/std/src/sys/sgx/abi/usercalls/mod.rs +++ b/library/std/src/sys/sgx/abi/usercalls/mod.rs @@ -83,7 +83,7 @@ pub fn close(fd: Fd) { fn string_from_bytebuffer(buf: &alloc::UserRef, usercall: &str, arg: &str) -> String { String::from_utf8(buf.copy_user_buffer()) - .unwrap_or_else(|_| rtabort!("Usercall {}: expected {} to be valid UTF-8", usercall, arg)) + .unwrap_or_else(|_| rtabort!("Usercall {usercall}: expected {arg} to be valid UTF-8")) } /// Usercall `bind_stream`. See the ABI documentation for more information. @@ -287,7 +287,7 @@ fn check_os_error(err: Result) -> i32 { { err } else { - rtabort!("Usercall: returned invalid error value {}", err) + rtabort!("Usercall: returned invalid error value {err}") } } diff --git a/library/std/src/sys/sgx/abi/usercalls/raw.rs b/library/std/src/sys/sgx/abi/usercalls/raw.rs index b0e6a6aaed7b9..4267b96ccd504 100644 --- a/library/std/src/sys/sgx/abi/usercalls/raw.rs +++ b/library/std/src/sys/sgx/abi/usercalls/raw.rs @@ -132,7 +132,7 @@ impl RegisterArgument for Option> { impl ReturnValue for ! { fn from_registers(call: &'static str, _regs: (Register, Register)) -> Self { - rtabort!("Usercall {}: did not expect to be re-entered", call); + rtabort!("Usercall {call}: did not expect to be re-entered"); } } diff --git a/library/std/src/sys/sgx/net.rs b/library/std/src/sys/sgx/net.rs index d14990c6877af..feb0b62dcd1f7 100644 --- a/library/std/src/sys/sgx/net.rs +++ b/library/std/src/sys/sgx/net.rs @@ -501,7 +501,7 @@ impl<'a> TryFrom<(&'a str, u16)> for LookupHost { type Error = io::Error; fn try_from((host, port): (&'a str, u16)) -> io::Result { - LookupHost::new(format!("{}:{}", host, port)) + LookupHost::new(format!("{host}:{port}")) } } diff --git a/library/std/src/sys/sgx/os.rs b/library/std/src/sys/sgx/os.rs index 5f8b8def7c670..5da0257f35de5 100644 --- a/library/std/src/sys/sgx/os.rs +++ b/library/std/src/sys/sgx/os.rs @@ -22,7 +22,7 @@ pub fn error_string(errno: i32) -> String { if errno == RESULT_SUCCESS { "operation successful".into() } else if ((Error::UserRangeStart as _)..=(Error::UserRangeEnd as _)).contains(&errno) { - format!("user-specified error {:08x}", errno) + format!("user-specified error {errno:08x}") } else { decode_error_kind(errno).as_str().into() } diff --git a/library/std/src/sys/sgx/stdio.rs b/library/std/src/sys/sgx/stdio.rs index 8ccf043b5b57f..2e680e740fde3 100644 --- a/library/std/src/sys/sgx/stdio.rs +++ b/library/std/src/sys/sgx/stdio.rs @@ -83,6 +83,6 @@ pub unsafe extern "C" fn __rust_print_err(m: *mut u8, s: i32) { } let buf = unsafe { slice::from_raw_parts(m as *const u8, s as _) }; if let Ok(s) = str::from_utf8(&buf[..buf.iter().position(|&b| b == 0).unwrap_or(buf.len())]) { - eprint!("{}", s); + eprint!("{s}"); } } diff --git a/library/std/src/sys/solid/mod.rs b/library/std/src/sys/solid/mod.rs index 2082c9401535e..049460755d65a 100644 --- a/library/std/src/sys/solid/mod.rs +++ b/library/std/src/sys/solid/mod.rs @@ -87,7 +87,7 @@ pub fn hashmap_random_keys() -> (u64, u64) { unsafe { let mut out = crate::mem::MaybeUninit::<[u64; 2]>::uninit(); let result = abi::SOLID_RNG_SampleRandomBytes(out.as_mut_ptr() as *mut u8, 16); - assert_eq!(result, 0, "SOLID_RNG_SampleRandomBytes failed: {}", result); + assert_eq!(result, 0, "SOLID_RNG_SampleRandomBytes failed: {result}"); let [x1, x2] = out.assume_init(); (x1, x2) } diff --git a/library/std/src/sys/solid/net.rs b/library/std/src/sys/solid/net.rs index a43407bd0f865..faeda5a854d9f 100644 --- a/library/std/src/sys/solid/net.rs +++ b/library/std/src/sys/solid/net.rs @@ -157,7 +157,7 @@ pub fn cvt_gai(err: c_int) -> io::Result<()> { }; Err(io::Error::new( io::ErrorKind::Uncategorized, - &format!("failed to lookup address information: {}", msg)[..], + &format!("failed to lookup address information: {msg}")[..], )) } } diff --git a/library/std/src/sys/solid/os.rs b/library/std/src/sys/solid/os.rs index 22239e1fa8ebc..127cca3accad9 100644 --- a/library/std/src/sys/solid/os.rs +++ b/library/std/src/sys/solid/os.rs @@ -26,7 +26,7 @@ pub fn errno() -> i32 { } pub fn error_string(errno: i32) -> String { - if let Some(name) = error::error_name(errno) { name.to_owned() } else { format!("{}", errno) } + if let Some(name) = error::error_name(errno) { name.to_owned() } else { format!("{errno}") } } pub fn getcwd() -> io::Result { diff --git a/library/std/src/sys/unix/net.rs b/library/std/src/sys/unix/net.rs index 61c15ecd85de3..e6fd9a0c827e2 100644 --- a/library/std/src/sys/unix/net.rs +++ b/library/std/src/sys/unix/net.rs @@ -54,7 +54,7 @@ pub fn cvt_gai(err: c_int) -> io::Result<()> { Err(io::Error::new( io::ErrorKind::Uncategorized, - &format!("failed to lookup address information: {}", detail)[..], + &format!("failed to lookup address information: {detail}")[..], )) } diff --git a/library/std/src/sys/unix/os_str/tests.rs b/library/std/src/sys/unix/os_str/tests.rs index 3796737815573..213277f01f2a6 100644 --- a/library/std/src/sys/unix/os_str/tests.rs +++ b/library/std/src/sys/unix/os_str/tests.rs @@ -4,7 +4,7 @@ use super::*; fn slice_debug_output() { let input = Slice::from_u8_slice(b"\xF0hello,\tworld"); let expected = r#""\xF0hello,\tworld""#; - let output = format!("{:?}", input); + let output = format!("{input:?}"); assert_eq!(output, expected); } diff --git a/library/std/src/sys/unix/process/process_fuchsia.rs b/library/std/src/sys/unix/process/process_fuchsia.rs index 09bfd9680f5b2..e3347ab12a730 100644 --- a/library/std/src/sys/unix/process/process_fuchsia.rs +++ b/library/std/src/sys/unix/process/process_fuchsia.rs @@ -211,7 +211,7 @@ impl Process { return Ok(None); } _ => { - panic!("Failed to wait on process handle: {}", status); + panic!("Failed to wait on process handle: {status}"); } } zx_cvt(zx_object_get_info( diff --git a/library/std/src/sys/unix/process/process_unix.rs b/library/std/src/sys/unix/process/process_unix.rs index 07a0339c066bc..9c477e5addc44 100644 --- a/library/std/src/sys/unix/process/process_unix.rs +++ b/library/std/src/sys/unix/process/process_unix.rs @@ -120,7 +120,7 @@ impl Command { Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => { assert!(p.wait().is_ok(), "wait() should either return Ok or panic"); - panic!("the CLOEXEC pipe failed: {:?}", e) + panic!("the CLOEXEC pipe failed: {e:?}") } Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic @@ -682,15 +682,15 @@ impl From for ExitStatus { impl fmt::Display for ExitStatus { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(code) = self.code() { - write!(f, "exit status: {}", code) + write!(f, "exit status: {code}") } else if let Some(signal) = self.signal() { if self.core_dumped() { - write!(f, "signal: {} (core dumped)", signal) + write!(f, "signal: {signal} (core dumped)") } else { - write!(f, "signal: {}", signal) + write!(f, "signal: {signal}") } } else if let Some(signal) = self.stopped_signal() { - write!(f, "stopped (not terminated) by signal: {}", signal) + write!(f, "stopped (not terminated) by signal: {signal}") } else if self.continued() { write!(f, "continued (WIFCONTINUED)") } else { diff --git a/library/std/src/sys/unix/process/process_vxworks.rs b/library/std/src/sys/unix/process/process_vxworks.rs index 56ed6cfeb6a6b..016bc20ec0a47 100644 --- a/library/std/src/sys/unix/process/process_vxworks.rs +++ b/library/std/src/sys/unix/process/process_vxworks.rs @@ -239,10 +239,10 @@ impl From for ExitStatus { impl fmt::Display for ExitStatus { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(code) = self.code() { - write!(f, "exit code: {}", code) + write!(f, "exit code: {code}") } else { let signal = self.signal().unwrap(); - write!(f, "signal: {}", signal) + write!(f, "signal: {signal}") } } } diff --git a/library/std/src/sys/unix/rand.rs b/library/std/src/sys/unix/rand.rs index 7a3f6b0d95a09..17e8efbe097ce 100644 --- a/library/std/src/sys/unix/rand.rs +++ b/library/std/src/sys/unix/rand.rs @@ -82,7 +82,7 @@ mod imp { } else if err == libc::EAGAIN { return false; } else { - panic!("unexpected getrandom error: {}", err); + panic!("unexpected getrandom error: {err}"); } } else { read += result as usize; diff --git a/library/std/src/sys/windows/os.rs b/library/std/src/sys/windows/os.rs index 5f8556c3bc376..450bceae00081 100644 --- a/library/std/src/sys/windows/os.rs +++ b/library/std/src/sys/windows/os.rs @@ -64,7 +64,7 @@ pub fn error_string(mut errnum: i32) -> String { if res == 0 { // Sometimes FormatMessageW can fail e.g., system doesn't like langId, let fm_err = errno(); - return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err); + return format!("OS Error {errnum} (FormatMessageW() returned error {fm_err})"); } match String::from_utf16(&buf[..res]) { diff --git a/library/std/src/sys/windows/process/tests.rs b/library/std/src/sys/windows/process/tests.rs index d18c3d855bcce..d8c9beb0c1975 100644 --- a/library/std/src/sys/windows/process/tests.rs +++ b/library/std/src/sys/windows/process/tests.rs @@ -121,9 +121,7 @@ fn windows_env_unicode_case() { assert_eq!( env::var(key).ok(), value.map(|s| s.to_string_lossy().into_owned()), - "command environment mismatch: {} {}", - a, - b + "command environment mismatch: {a} {b}", ); } } diff --git a/library/std/src/sys/windows/thread_parker.rs b/library/std/src/sys/windows/thread_parker.rs index 5a8011a958808..5888ee8e34bfb 100644 --- a/library/std/src/sys/windows/thread_parker.rs +++ b/library/std/src/sys/windows/thread_parker.rs @@ -230,7 +230,7 @@ fn keyed_event_handle() -> c::HANDLE { 0, ) { c::STATUS_SUCCESS => {} - r => panic!("Unable to create keyed event handle: error {}", r), + r => panic!("Unable to create keyed event handle: error {r}"), } } match HANDLE.compare_exchange(INVALID, handle as usize, Relaxed, Relaxed) { diff --git a/library/std/src/sys_common/backtrace.rs b/library/std/src/sys_common/backtrace.rs index b0b55592f6f37..31164afdc7b54 100644 --- a/library/std/src/sys_common/backtrace.rs +++ b/library/std/src/sys_common/backtrace.rs @@ -174,7 +174,7 @@ pub fn output_filename( if let Some(cwd) = cwd { if let Ok(stripped) = file.strip_prefix(&cwd) { if let Some(s) = stripped.to_str() { - return write!(fmt, ".{}{}", path::MAIN_SEPARATOR, s); + return write!(fmt, ".{}{s}", path::MAIN_SEPARATOR); } } } diff --git a/library/std/src/sys_common/net/tests.rs b/library/std/src/sys_common/net/tests.rs index 7d45621e09ae4..ac75d9ebfc855 100644 --- a/library/std/src/sys_common/net/tests.rs +++ b/library/std/src/sys_common/net/tests.rs @@ -6,7 +6,7 @@ fn no_lookup_host_duplicates() { let mut addrs = HashMap::new(); let lh = match LookupHost::try_from(("localhost", 0)) { Ok(lh) => lh, - Err(e) => panic!("couldn't resolve `localhost': {}", e), + Err(e) => panic!("couldn't resolve `localhost': {e}"), }; for sa in lh { *addrs.entry(sa).or_insert(0) += 1; diff --git a/library/std/src/sys_common/thread_parker/generic.rs b/library/std/src/sys_common/thread_parker/generic.rs index d99e901bb5f83..ffb61200e15f9 100644 --- a/library/std/src/sys_common/thread_parker/generic.rs +++ b/library/std/src/sys_common/thread_parker/generic.rs @@ -84,7 +84,7 @@ impl Parker { match self.state.swap(EMPTY, SeqCst) { NOTIFIED => {} // got a notification, hurray! PARKED => {} // no notification, alas - n => panic!("inconsistent park_timeout state: {}", n), + n => panic!("inconsistent park_timeout state: {n}"), } } diff --git a/library/std/src/sys_common/wtf8.rs b/library/std/src/sys_common/wtf8.rs index 7a6e6246357d1..10ef6662115c1 100644 --- a/library/std/src/sys_common/wtf8.rs +++ b/library/std/src/sys_common/wtf8.rs @@ -830,7 +830,7 @@ pub unsafe fn slice_unchecked(s: &Wtf8, begin: usize, end: usize) -> &Wtf8 { #[inline(never)] pub fn slice_error_fail(s: &Wtf8, begin: usize, end: usize) -> ! { assert!(begin <= end); - panic!("index {} and/or {} in `{:?}` do not lie on character boundary", begin, end, s); + panic!("index {begin} and/or {end} in `{s:?}` do not lie on character boundary"); } /// Iterator for the code points of a WTF-8 string. diff --git a/library/std/src/sys_common/wtf8/tests.rs b/library/std/src/sys_common/wtf8/tests.rs index 1bafbaa693922..931996791fbe5 100644 --- a/library/std/src/sys_common/wtf8/tests.rs +++ b/library/std/src/sys_common/wtf8/tests.rs @@ -266,7 +266,7 @@ fn wtf8buf_extend() { fn wtf8buf_show() { let mut string = Wtf8Buf::from_str("a\té \u{7f}💩\r"); string.push(CodePoint::from_u32(0xD800).unwrap()); - assert_eq!(format!("{:?}", string), "\"a\\té \\u{7f}\u{1f4a9}\\r\\u{d800}\""); + assert_eq!(format!("{string:?}"), "\"a\\té \\u{7f}\u{1f4a9}\\r\\u{d800}\""); } #[test] @@ -278,7 +278,7 @@ fn wtf8buf_as_slice() { fn wtf8buf_show_str() { let text = "a\té 💩\r"; let string = Wtf8Buf::from_str(text); - assert_eq!(format!("{:?}", text), format!("{:?}", string)); + assert_eq!(format!("{text:?}"), format!("{string:?}")); } #[test] diff --git a/library/std/src/thread/mod.rs b/library/std/src/thread/mod.rs index 5ffc86b4560fc..8f38271eb5df9 100644 --- a/library/std/src/thread/mod.rs +++ b/library/std/src/thread/mod.rs @@ -613,7 +613,7 @@ impl Builder { /// /// let receiver = thread::spawn(move || { /// let value = rx.recv().expect("Unable to receive from channel"); -/// println!("{}", value); +/// println!("{value}"); /// }); /// /// sender.join().expect("The sender thread has panicked"); @@ -633,7 +633,7 @@ impl Builder { /// }); /// /// let result = computation.join().unwrap(); -/// println!("{}", result); +/// println!("{result}"); /// ``` /// /// [`channels`]: crate::sync::mpsc @@ -979,7 +979,7 @@ pub fn park_timeout_ms(ms: u32) { /// if elapsed >= timeout { /// break; /// } -/// println!("restarting park_timeout after {:?}", elapsed); +/// println!("restarting park_timeout after {elapsed:?}"); /// timeout_remaining = timeout - elapsed; /// } /// ``` diff --git a/library/std/src/thread/scoped.rs b/library/std/src/thread/scoped.rs index c4847b529a361..07e113f3b6222 100644 --- a/library/std/src/thread/scoped.rs +++ b/library/std/src/thread/scoped.rs @@ -22,7 +22,7 @@ pub struct Scope<'scope, 'env: 'scope> { /// std::thread::scope(|s| { /// s.spawn(|| { /// let a = String::from("abcd"); - /// s.spawn(|| println!("{:?}", a)); // might run after `a` is dropped + /// s.spawn(|| println!("{a:?}")); // might run after `a` is dropped /// }); /// }); /// ``` diff --git a/library/std/src/time.rs b/library/std/src/time.rs index df8a726e64ecb..2f8eb557b4f74 100644 --- a/library/std/src/time.rs +++ b/library/std/src/time.rs @@ -191,7 +191,7 @@ pub struct Instant(time::Instant); /// } /// Err(e) => { /// // an error occurred! -/// println!("Error: {:?}", e); +/// println!("Error: {e:?}"); /// } /// } /// } @@ -513,7 +513,7 @@ impl SystemTime { /// let new_sys_time = SystemTime::now(); /// let difference = new_sys_time.duration_since(sys_time) /// .expect("Clock may have gone backwards"); - /// println!("{:?}", difference); + /// println!("{difference:?}"); /// ``` #[stable(feature = "time2", since = "1.8.0")] pub fn duration_since(&self, earlier: SystemTime) -> Result { diff --git a/library/std/src/time/tests.rs b/library/std/src/time/tests.rs index d1a69ff8697c6..d710a574465ce 100644 --- a/library/std/src/time/tests.rs +++ b/library/std/src/time/tests.rs @@ -55,10 +55,10 @@ fn instant_elapsed() { fn instant_math() { let a = Instant::now(); let b = Instant::now(); - println!("a: {:?}", a); - println!("b: {:?}", b); + println!("a: {a:?}"); + println!("b: {b:?}"); let dur = b.duration_since(a); - println!("dur: {:?}", dur); + println!("dur: {dur:?}"); assert_almost_eq!(b - dur, a); assert_almost_eq!(a + dur, b); diff --git a/library/test/src/cli.rs b/library/test/src/cli.rs index b39701a3d4288..000f5fa3f5860 100644 --- a/library/test/src/cli.rs +++ b/library/test/src/cli.rs @@ -149,7 +149,7 @@ fn optgroups() -> getopts::Options { } fn usage(binary: &str, options: &getopts::Options) { - let message = format!("Usage: {} [OPTIONS] [FILTERS...]", binary); + let message = format!("Usage: {binary} [OPTIONS] [FILTERS...]"); println!( r#"{usage} @@ -360,7 +360,7 @@ fn get_shuffle_seed(matches: &getopts::Matches, allow_unstable: bool) -> OptPart shuffle_seed = match env::var("RUST_TEST_SHUFFLE_SEED") { Ok(val) => match val.parse::() { Ok(n) => Some(n), - Err(_) => panic!("RUST_TEST_SHUFFLE_SEED is `{}`, should be a number.", val), + Err(_) => panic!("RUST_TEST_SHUFFLE_SEED is `{val}`, should be a number."), }, Err(_) => None, }; diff --git a/library/test/src/console.rs b/library/test/src/console.rs index 22fcd77dccc52..c7e8507113e0c 100644 --- a/library/test/src/console.rs +++ b/library/test/src/console.rs @@ -114,11 +114,11 @@ impl ConsoleTestState { match *result { TestResult::TrOk => "ok".to_owned(), TestResult::TrFailed => "failed".to_owned(), - TestResult::TrFailedMsg(ref msg) => format!("failed: {}", msg), + TestResult::TrFailedMsg(ref msg) => format!("failed: {msg}"), TestResult::TrIgnored => { #[cfg(not(bootstrap))] if let Some(msg) = ignore_message { - format!("ignored, {}", msg) + format!("ignored, {msg}") } else { "ignored".to_owned() } @@ -132,7 +132,7 @@ impl ConsoleTestState { ) })?; if let Some(exec_time) = exec_time { - self.write_log(|| format!(" <{}>", exec_time))?; + self.write_log(|| format!(" <{exec_time}>"))?; } self.write_log(|| "\n") } @@ -171,14 +171,14 @@ pub fn list_tests_console(opts: &TestOpts, tests: Vec) -> io::Res } }; - writeln!(output, "{}: {}", name, fntype)?; - st.write_log(|| format!("{} {}\n", fntype, name))?; + writeln!(output, "{name}: {fntype}")?; + st.write_log(|| format!("{fntype} {name}\n"))?; } fn plural(count: u32, s: &str) -> String { match count { - 1 => format!("{} {}", 1, s), - n => format!("{} {}s", n, s), + 1 => format!("1 {s}"), + n => format!("{n} {s}s"), } } @@ -218,7 +218,7 @@ fn handle_test_result(st: &mut ConsoleTestState, completed_test: CompletedTest) TestResult::TrFailedMsg(msg) => { st.failed += 1; let mut stdout = stdout; - stdout.extend_from_slice(format!("note: {}", msg).as_bytes()); + stdout.extend_from_slice(format!("note: {msg}").as_bytes()); st.failures.push((test, stdout)); } TestResult::TrTimedFail => { diff --git a/library/test/src/formatters/junit.rs b/library/test/src/formatters/junit.rs index 54e9860ab5487..e6fb4f5707b35 100644 --- a/library/test/src/formatters/junit.rs +++ b/library/test/src/formatters/junit.rs @@ -97,7 +97,7 @@ impl OutputFormatter for JunitFormatter { test_name, duration.as_secs_f64() ))?; - self.write_message(&*format!("", m))?; + self.write_message(&*format!(""))?; self.write_message("")?; } diff --git a/library/test/src/formatters/pretty.rs b/library/test/src/formatters/pretty.rs index 041df5216d7b3..f55d390aa5621 100644 --- a/library/test/src/formatters/pretty.rs +++ b/library/test/src/formatters/pretty.rs @@ -96,7 +96,7 @@ impl PrettyFormatter { exec_time: Option<&time::TestExecTime>, ) -> io::Result<()> { if let (Some(opts), Some(time)) = (self.time_options, exec_time) { - let time_str = format!(" <{}>", time); + let time_str = format!(" <{time}>"); let color = if self.use_color { if opts.is_critical(desc, time) { @@ -124,7 +124,7 @@ impl PrettyFormatter { inputs: &Vec<(TestDesc, Vec)>, results_type: &str, ) -> io::Result<()> { - let results_out_str = format!("\n{}:\n", results_type); + let results_out_str = format!("\n{results_type}:\n"); self.write_plain(&results_out_str)?; @@ -147,7 +147,7 @@ impl PrettyFormatter { self.write_plain(&results_out_str)?; results.sort(); for name in &results { - self.write_plain(&format!(" {}\n", name))?; + self.write_plain(&format!(" {name}\n"))?; } Ok(()) } @@ -167,9 +167,9 @@ impl PrettyFormatter { fn write_test_name(&mut self, desc: &TestDesc) -> io::Result<()> { let name = desc.padded_name(self.max_name_len, desc.name.padding()); if let Some(test_mode) = desc.test_mode() { - self.write_plain(&format!("test {} - {} ... ", name, test_mode))?; + self.write_plain(&format!("test {name} - {test_mode} ... "))?; } else { - self.write_plain(&format!("test {} ... ", name))?; + self.write_plain(&format!("test {name} ... "))?; } Ok(()) @@ -180,11 +180,11 @@ impl OutputFormatter for PrettyFormatter { fn write_run_start(&mut self, test_count: usize, shuffle_seed: Option) -> io::Result<()> { let noun = if test_count != 1 { "tests" } else { "test" }; let shuffle_seed_msg = if let Some(shuffle_seed) = shuffle_seed { - format!(" (shuffle seed: {})", shuffle_seed) + format!(" (shuffle seed: {shuffle_seed})") } else { String::new() }; - self.write_plain(&format!("\nrunning {} {}{}\n", test_count, noun, shuffle_seed_msg)) + self.write_plain(&format!("\nrunning {test_count} {noun}{shuffle_seed_msg}\n")) } fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> { @@ -266,7 +266,7 @@ impl OutputFormatter for PrettyFormatter { self.write_plain(&s)?; if let Some(ref exec_time) = state.exec_time { - let time_str = format!("; finished in {}", exec_time); + let time_str = format!("; finished in {exec_time}"); self.write_plain(&time_str)?; } diff --git a/library/test/src/formatters/terse.rs b/library/test/src/formatters/terse.rs index 12aca7cd9a42d..fb40f86b42e19 100644 --- a/library/test/src/formatters/terse.rs +++ b/library/test/src/formatters/terse.rs @@ -122,7 +122,7 @@ impl TerseFormatter { self.write_plain("\nsuccesses:\n")?; successes.sort(); for name in &successes { - self.write_plain(&format!(" {}\n", name))?; + self.write_plain(&format!(" {name}\n"))?; } Ok(()) } @@ -148,7 +148,7 @@ impl TerseFormatter { self.write_plain("\nfailures:\n")?; failures.sort(); for name in &failures { - self.write_plain(&format!(" {}\n", name))?; + self.write_plain(&format!(" {name}\n"))?; } Ok(()) } @@ -156,9 +156,9 @@ impl TerseFormatter { fn write_test_name(&mut self, desc: &TestDesc) -> io::Result<()> { let name = desc.padded_name(self.max_name_len, desc.name.padding()); if let Some(test_mode) = desc.test_mode() { - self.write_plain(&format!("test {} - {} ... ", name, test_mode))?; + self.write_plain(&format!("test {name} - {test_mode} ... "))?; } else { - self.write_plain(&format!("test {} ... ", name))?; + self.write_plain(&format!("test {name} ... "))?; } Ok(()) @@ -170,11 +170,11 @@ impl OutputFormatter for TerseFormatter { self.total_test_count = test_count; let noun = if test_count != 1 { "tests" } else { "test" }; let shuffle_seed_msg = if let Some(shuffle_seed) = shuffle_seed { - format!(" (shuffle seed: {})", shuffle_seed) + format!(" (shuffle seed: {shuffle_seed})") } else { String::new() }; - self.write_plain(&format!("\nrunning {} {}{}\n", test_count, noun, shuffle_seed_msg)) + self.write_plain(&format!("\nrunning {test_count} {noun}{shuffle_seed_msg}\n")) } fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> { @@ -247,7 +247,7 @@ impl OutputFormatter for TerseFormatter { self.write_plain(&s)?; if let Some(ref exec_time) = state.exec_time { - let time_str = format!("; finished in {}", exec_time); + let time_str = format!("; finished in {exec_time}"); self.write_plain(&time_str)?; } diff --git a/library/test/src/helpers/concurrency.rs b/library/test/src/helpers/concurrency.rs index e25f524ec0566..eb211157371b5 100644 --- a/library/test/src/helpers/concurrency.rs +++ b/library/test/src/helpers/concurrency.rs @@ -6,7 +6,7 @@ pub fn get_concurrency() -> usize { if let Ok(value) = env::var("RUST_TEST_THREADS") { match value.parse::().ok() { Some(n) => n.get(), - _ => panic!("RUST_TEST_THREADS is `{}`, should be a positive integer.", value), + _ => panic!("RUST_TEST_THREADS is `{value}`, should be a positive integer."), } } else { thread::available_parallelism().map(|n| n.get()).unwrap_or(1) diff --git a/library/test/src/helpers/exit_code.rs b/library/test/src/helpers/exit_code.rs index 50bb260762a70..f762f88819da5 100644 --- a/library/test/src/helpers/exit_code.rs +++ b/library/test/src/helpers/exit_code.rs @@ -13,7 +13,7 @@ pub fn get_exit_code(status: ExitStatus) -> Result { match status.code() { Some(code) => Ok(code), None => match status.signal() { - Some(signal) => Err(format!("child process exited with signal {}", signal)), + Some(signal) => Err(format!("child process exited with signal {signal}")), None => Err("child process exited with unknown signal".into()), }, } diff --git a/library/test/src/lib.rs b/library/test/src/lib.rs index 8fc2b4ed748c2..088e3a23ea4d9 100644 --- a/library/test/src/lib.rs +++ b/library/test/src/lib.rs @@ -99,7 +99,7 @@ pub fn test_main(args: &[String], tests: Vec, options: Option o, Some(Err(msg)) => { - eprintln!("error: {}", msg); + eprintln!("error: {msg}"); process::exit(ERROR_EXIT_CODE); } None => return, @@ -109,7 +109,7 @@ pub fn test_main(args: &[String], tests: Vec, options: Option, options: Option {} Ok(false) => process::exit(ERROR_EXIT_CODE), Err(e) => { - eprintln!("error: io error when listing tests: {:?}", e); + eprintln!("error: io error when listing tests: {e:?}"); process::exit(ERROR_EXIT_CODE); } } @@ -153,7 +153,7 @@ pub fn test_main_static_abort(tests: &[&TestDescAndFn]) { .filter(|test| test.desc.name.as_slice() == name) .map(make_owned_test) .next() - .unwrap_or_else(|| panic!("couldn't find a test with the provided name '{}'", name)); + .unwrap_or_else(|| panic!("couldn't find a test with the provided name '{name}'")); let TestDescAndFn { desc, testfn } = test; let testfn = match testfn { StaticTestFn(f) => f, @@ -524,7 +524,7 @@ pub fn run_test( Arc::get_mut(&mut runtest).unwrap().get_mut().unwrap().take().unwrap()(); None } - Err(e) => panic!("failed to spawn thread to run test: {}", e), + Err(e) => panic!("failed to spawn thread to run test: {e}"), } } else { runtest(); @@ -678,7 +678,7 @@ fn run_test_in_spawned_subprocess(desc: TestDesc, testfn: Box state = SeekIfEnd(0), ';' => (), - _ => return Err(format!("unrecognized format option {}", cur)), + _ => return Err(format!("unrecognized format option {cur}")), } } PushParam => { diff --git a/library/test/src/term/terminfo/parm/tests.rs b/library/test/src/term/terminfo/parm/tests.rs index 256d1aaf446d9..c738f3ba04fce 100644 --- a/library/test/src/term/terminfo/parm/tests.rs +++ b/library/test/src/term/terminfo/parm/tests.rs @@ -78,15 +78,15 @@ fn test_push_bad_param() { fn test_comparison_ops() { let v = [('<', [1u8, 0u8, 0u8]), ('=', [0u8, 1u8, 0u8]), ('>', [0u8, 0u8, 1u8])]; for &(op, bs) in v.iter() { - let s = format!("%{{1}}%{{2}}%{}%d", op); + let s = format!("%{{1}}%{{2}}%{op}%d"); let res = expand(s.as_bytes(), &[], &mut Variables::new()); assert!(res.is_ok(), "{}", res.unwrap_err()); assert_eq!(res.unwrap(), vec![b'0' + bs[0]]); - let s = format!("%{{1}}%{{1}}%{}%d", op); + let s = format!("%{{1}}%{{1}}%{op}%d"); let res = expand(s.as_bytes(), &[], &mut Variables::new()); assert!(res.is_ok(), "{}", res.unwrap_err()); assert_eq!(res.unwrap(), vec![b'0' + bs[1]]); - let s = format!("%{{2}}%{{1}}%{}%d", op); + let s = format!("%{{2}}%{{1}}%{op}%d"); let res = expand(s.as_bytes(), &[], &mut Variables::new()); assert!(res.is_ok(), "{}", res.unwrap_err()); assert_eq!(res.unwrap(), vec![b'0' + bs[2]]); diff --git a/library/test/src/term/terminfo/parser/compiled.rs b/library/test/src/term/terminfo/parser/compiled.rs index b24f3f8b05e70..5d40b7988b52d 100644 --- a/library/test/src/term/terminfo/parser/compiled.rs +++ b/library/test/src/term/terminfo/parser/compiled.rs @@ -198,7 +198,7 @@ pub(crate) fn parse(file: &mut dyn io::Read, longnames: bool) -> Result false, 0o01036 => true, - _ => return Err(format!("invalid magic number, found {:o}", magic)), + _ => return Err(format!("invalid magic number, found {magic:o}")), }; // According to the spec, these fields must be >= -1 where -1 means that the feature is not diff --git a/library/test/src/test_result.rs b/library/test/src/test_result.rs index 8c216a1e0e70e..7f44d6e3d0f12 100644 --- a/library/test/src/test_result.rs +++ b/library/test/src/test_result.rs @@ -89,7 +89,7 @@ pub fn get_result_from_exit_code( let result = match code { TR_OK => TestResult::TrOk, TR_FAILED => TestResult::TrFailed, - _ => TestResult::TrFailedMsg(format!("got unexpected return code {}", code)), + _ => TestResult::TrFailedMsg(format!("got unexpected return code {code}")), }; // If test is already failed (or allowed to fail), do not change the result. diff --git a/src/doc/rustdoc/src/how-to-write-documentation.md b/src/doc/rustdoc/src/how-to-write-documentation.md index f89495cca3a31..38fd1db5c21e8 100644 --- a/src/doc/rustdoc/src/how-to-write-documentation.md +++ b/src/doc/rustdoc/src/how-to-write-documentation.md @@ -126,7 +126,7 @@ use std::env; // Prints each argument on a separate line for argument in env::args() { - println!("{}", argument); + println!("{argument}"); } ``` diff --git a/src/doc/unstable-book/src/compiler-flags/sanitizer.md b/src/doc/unstable-book/src/compiler-flags/sanitizer.md index 457851b0cc7a4..735521e667c91 100644 --- a/src/doc/unstable-book/src/compiler-flags/sanitizer.md +++ b/src/doc/unstable-book/src/compiler-flags/sanitizer.md @@ -240,7 +240,7 @@ fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { fn main() { let answer = do_twice(add_one, 5); - println!("The answer is: {}", answer); + println!("The answer is: {answer}"); println!("With CFI enabled, you should not see the next answer"); let f: fn(i32) -> i32 = unsafe { @@ -250,7 +250,7 @@ fn main() { }; let next_answer = do_twice(f, 5); - println!("The next answer is: {}", next_answer); + println!("The next answer is: {next_answer}"); } ``` Fig. 1. Modified example from the [Advanced Functions and @@ -303,14 +303,14 @@ fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { fn main() { let answer = do_twice(add_one, 5); - println!("The answer is: {}", answer); + println!("The answer is: {answer}"); println!("With CFI enabled, you should not see the next answer"); let f: fn(i32) -> i32 = unsafe { mem::transmute::<*const u8, fn(i32) -> i32>(add_two as *const u8) }; let next_answer = do_twice(f, 5); - println!("The next answer is: {}", next_answer); + println!("The next answer is: {next_answer}"); } ``` Fig. 4. Another modified example from the [Advanced Functions and diff --git a/src/doc/unstable-book/src/language-features/box-patterns.md b/src/doc/unstable-book/src/language-features/box-patterns.md index bf0819ec920b7..584f4295cba0f 100644 --- a/src/doc/unstable-book/src/language-features/box-patterns.md +++ b/src/doc/unstable-book/src/language-features/box-patterns.md @@ -18,10 +18,10 @@ fn main() { let b = Some(Box::new(5)); match b { Some(box n) if n < 0 => { - println!("Box contains negative number {}", n); + println!("Box contains negative number {n}"); }, Some(box n) if n >= 0 => { - println!("Box contains non-negative number {}", n); + println!("Box contains non-negative number {n}"); }, None => { println!("No box"); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 29c11c7b28a5f..fa0030a936030 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -829,7 +829,7 @@ fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attrib .values .insert(a as _, Argument { name, type_: *ty, is_const: true }); } else { - panic!("unexpected non const in position {}", pos); + panic!("unexpected non const in position {pos}"); } } _ => panic!("invalid arg index"), diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 63a8e85f7c540..e9efeba02997f 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -197,7 +197,7 @@ crate fn run(options: RustdocOptions) -> Result<(), ErrorGuaranteed> { .to_string(); let uext = UnusedExterns { lint_level, unused_extern_names }; let unused_extern_json = serde_json::to_string(&uext).unwrap(); - eprintln!("{}", unused_extern_json); + eprintln!("{unused_extern_json}"); } } @@ -430,7 +430,7 @@ fn run_test( // We used to check if the output contained "error[{}]: " but since we added the // colored output, we can't anymore because of the color escape characters before // the ":". - lang_string.error_codes.retain(|err| !out.contains(&format!("error[{}]", err))); + lang_string.error_codes.retain(|err| !out.contains(&format!("error[{err}]"))); if !lang_string.error_codes.is_empty() { return Err(TestFailure::MissingErrorCodes(lang_string.error_codes)); @@ -510,7 +510,7 @@ crate fn make_test( // Next, any attributes that came from the crate root via #![doc(test(attr(...)))]. for attr in &opts.attrs { - prog.push_str(&format!("#![{}]\n", attr)); + prog.push_str(&format!("#![{attr}]\n")); line_offset += 1; } @@ -647,7 +647,7 @@ crate fn make_test( // parse the source, but only has false positives, not false // negatives. if s.contains(crate_name) { - prog.push_str(&format!("extern crate r#{};\n", crate_name)); + prog.push_str(&format!("extern crate r#{crate_name};\n")); line_offset += 1; } } @@ -661,7 +661,7 @@ crate fn make_test( // Give each doctest main function a unique name. // This is for example needed for the tooling around `-C instrument-coverage`. let inner_fn_name = if let Some(test_id) = test_id { - format!("_doctest_main_{}", test_id) + format!("_doctest_main_{test_id}") } else { "_inner".into() }; @@ -669,15 +669,14 @@ crate fn make_test( let (main_pre, main_post) = if returns_result { ( format!( - "fn main() {{ {}fn {}() -> Result<(), impl core::fmt::Debug> {{\n", - inner_attr, inner_fn_name + "fn main() {{ {inner_attr}fn {inner_fn_name}() -> Result<(), impl core::fmt::Debug> {{\n", ), - format!("\n}} {}().unwrap() }}", inner_fn_name), + format!("\n}} {inner_fn_name}().unwrap() }}"), ) } else if test_id.is_some() { ( - format!("fn main() {{ {}fn {}() {{\n", inner_attr, inner_fn_name), - format!("\n}} {}() }}", inner_fn_name), + format!("fn main() {{ {inner_attr}fn {inner_fn_name}() {{\n",), + format!("\n}} {inner_fn_name}() }}"), ) } else { ("fn main() {\n".into(), "\n}".into()) @@ -695,7 +694,7 @@ crate fn make_test( prog.extend([&main_pre, everything_else, &main_post].iter().cloned()); } - debug!("final doctest:\n{}", prog); + debug!("final doctest:\n{prog}"); (prog, line_offset, supports_color) } @@ -763,9 +762,9 @@ fn partition_source(s: &str) -> (String, String, String) { } } - debug!("before:\n{}", before); - debug!("crates:\n{}", crates); - debug!("after:\n{}", after); + debug!("before:\n{before}"); + debug!("crates:\n{crates}"); + debug!("after:\n{after}"); (before, after, crates) } @@ -940,7 +939,7 @@ impl Tester for Collector { ) }; - debug!("creating test {}: {}", name, test); + debug!("creating test {name}: {test}"); self.tests.push(test::TestDescAndFn { desc: test::TestDesc { name: test::DynTestName(name), @@ -994,19 +993,19 @@ impl Tester for Collector { eprint!("Some expected error codes were not found: {:?}", codes); } TestFailure::ExecutionError(err) => { - eprint!("Couldn't run the test: {}", err); + eprint!("Couldn't run the test: {err}"); if err.kind() == io::ErrorKind::PermissionDenied { eprint!(" - maybe your tempdir is mounted with noexec?"); } } TestFailure::ExecutionFailure(out) => { let reason = if let Some(code) = out.status.code() { - format!("exit code {}", code) + format!("exit code {code}") } else { String::from("terminated by signal") }; - eprintln!("Test executable failed ({}).", reason); + eprintln!("Test executable failed ({reason})."); // FIXME(#12309): An unfortunate side-effect of capturing the test // executable's output is that the relative ordering between the test's @@ -1024,11 +1023,11 @@ impl Tester for Collector { eprintln!(); if !stdout.is_empty() { - eprintln!("stdout:\n{}", stdout); + eprintln!("stdout:\n{stdout}"); } if !stderr.is_empty() { - eprintln!("stderr:\n{}", stderr); + eprintln!("stderr:\n{stderr}"); } } } diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 7061a9674e4fb..98dc625b36d18 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -1314,7 +1314,7 @@ crate fn markdown_links(md: &str) -> Vec { for ev in iter { if let Event::Start(Tag::Link(kind, dest, _)) = ev.0 { - debug!("found link: {}", dest); + debug!("found link: {dest}"); let span = span_for_link(&dest, ev.1); links.borrow_mut().push(MarkdownLink { kind, link: dest.into_string(), range: span }); } diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index 906b8f8a24570..a1f92afad46a6 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -51,7 +51,7 @@ crate fn render>( let mut css = String::new(); for name in &options.markdown_css { - let s = format!("\n", name); + let s = format!("\n"); css.push_str(&s) } diff --git a/src/tools/tidy/src/bins.rs b/src/tools/tidy/src/bins.rs index 1d5ec5c31c67f..503df53704793 100644 --- a/src/tools/tidy/src/bins.rs +++ b/src/tools/tidy/src/bins.rs @@ -117,7 +117,7 @@ mod os_impl { .stderr(Stdio::null()) .output() .unwrap_or_else(|e| { - panic!("could not run git ls-files: {}", e); + panic!("could not run git ls-files: {e}"); }); let path_bytes = rel_path.as_os_str().as_bytes(); if output.status.success() && output.stdout.starts_with(path_bytes) { diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 52429fee46150..d6e36c2e7db40 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -340,8 +340,8 @@ fn check_exceptions( } Some(pkg_license) => { if pkg_license.as_str() != *license { - println!("dependency exception `{}` license has changed", name); - println!(" previously `{}` now `{}`", license, pkg_license); + println!("dependency exception `{name}` license has changed"); + println!(" previously `{license}` now `{pkg_license}`"); println!(" update EXCEPTIONS for the new license"); *bad = true; } @@ -418,7 +418,7 @@ fn check_dependencies( if !unapproved.is_empty() { tidy_error!(bad, "Dependencies not explicitly permitted:"); for dep in unapproved { - println!("* {}", dep); + println!("* {dep}"); } } } @@ -501,7 +501,7 @@ fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> Vec<&'a Package .nodes .iter() .find(|n| &n.id == pkg_id) - .unwrap_or_else(|| panic!("could not find `{}` in resolve", pkg_id)); + .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve")); node.deps .iter() .map(|dep| { @@ -516,8 +516,8 @@ fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> Vec<&'a Package fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package { let mut i = metadata.packages.iter().filter(|p| p.name == name); let result = - i.next().unwrap_or_else(|| panic!("could not find package `{}` in package list", name)); - assert!(i.next().is_none(), "more than one package found for `{}`", name); + i.next().unwrap_or_else(|| panic!("could not find package `{name}` in package list")); + assert!(i.next().is_none(), "more than one package found for `{name}`"); result } @@ -545,7 +545,7 @@ fn normal_deps_of_r<'a>( .nodes .iter() .find(|n| &n.id == pkg_id) - .unwrap_or_else(|| panic!("could not find `{}` in resolve", pkg_id)); + .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve")); for dep in &node.deps { normal_deps_of_r(resolve, &dep.pkg, result); } diff --git a/src/tools/tidy/src/error_codes_check.rs b/src/tools/tidy/src/error_codes_check.rs index f6be550283a21..281773b0569c5 100644 --- a/src/tools/tidy/src/error_codes_check.rs +++ b/src/tools/tidy/src/error_codes_check.rs @@ -260,7 +260,7 @@ pub fn check(paths: &[&Path], bad: &mut bool) { for (err_code, error_status) in &error_codes { if !error_status.has_test && !EXEMPTED_FROM_TEST.contains(&err_code.as_str()) { - errors.push(format!("Error code {} needs to have at least one UI test!", err_code)); + errors.push(format!("Error code {err_code} needs to have at least one UI test!")); } else if error_status.has_test && EXEMPTED_FROM_TEST.contains(&err_code.as_str()) { errors.push(format!( "Error code {} has a UI test, it shouldn't be listed into EXEMPTED_FROM_TEST!", @@ -309,7 +309,7 @@ pub fn check(paths: &[&Path], bad: &mut bool) { } errors.sort(); for err in &errors { - eprintln!("{}", err); + eprintln!("{err}"); } println!("Found {} error(s) in error codes", errors.len()); if !errors.is_empty() { diff --git a/src/tools/tidy/src/features.rs b/src/tools/tidy/src/features.rs index 9b6037c6a4ba7..2f22c081a54b5 100644 --- a/src/tools/tidy/src/features.rs +++ b/src/tools/tidy/src/features.rs @@ -157,7 +157,7 @@ pub fn check( .collect::>(); for &(name, _) in gate_untested.iter() { - println!("Expected a gate test for the feature '{}'.", name); + println!("Expected a gate test for the feature '{name}'."); println!( "Hint: create a failing test file named 'feature-gate-{}.rs'\ \n in the 'ui' test suite, with its failures due to\ @@ -186,7 +186,7 @@ pub fn check( lines.sort(); for line in lines { - println!("* {}", line); + println!("* {line}"); } } else { println!("* {} features", features.len()); @@ -221,7 +221,7 @@ fn find_attr_val<'a>(line: &'a str, attr: &str) -> Option<&'a str> { "issue" => &*ISSUE, "feature" => &*FEATURE, "since" => &*SINCE, - _ => unimplemented!("{} not handled", attr), + _ => unimplemented!("{attr} not handled"), }; r.captures(line).and_then(|c| c.get(1)).map(|m| m.as_str()) @@ -231,7 +231,7 @@ fn test_filen_gate(filen_underscore: &str, features: &mut Features) -> bool { let prefix = "feature_gate_"; if filen_underscore.starts_with(prefix) { for (n, f) in features.iter_mut() { - // Equivalent to filen_underscore == format!("feature_gate_{}", n) + // Equivalent to filen_underscore == format!("feature_gate_{n}") if &filen_underscore[prefix.len()..] == n { f.has_gate_test = true; return true; diff --git a/src/tools/tidy/src/primitive_docs.rs b/src/tools/tidy/src/primitive_docs.rs index 8476650d9b5f7..f3200e0afd71a 100644 --- a/src/tools/tidy/src/primitive_docs.rs +++ b/src/tools/tidy/src/primitive_docs.rs @@ -8,10 +8,10 @@ pub fn check(library_path: &Path, bad: &mut bool) { let std_name = "std/src/primitive_docs.rs"; let core_name = "core/src/primitive_docs.rs"; let std_contents = std::fs::read_to_string(library_path.join(std_name)) - .unwrap_or_else(|e| panic!("failed to read library/{}: {}", std_name, e)); + .unwrap_or_else(|e| panic!("failed to read library/{std_name}: {e}")); let core_contents = std::fs::read_to_string(library_path.join(core_name)) - .unwrap_or_else(|e| panic!("failed to read library/{}: {}", core_name, e)); + .unwrap_or_else(|e| panic!("failed to read library/{core_name}: {e}")); if std_contents != core_contents { - tidy_error!(bad, "library/{} and library/{} have different contents", core_name, std_name); + tidy_error!(bad, "library/{core_name} and library/{std_name} have different contents"); } } diff --git a/src/tools/tidy/src/style.rs b/src/tools/tidy/src/style.rs index c197acd4828a1..9861cba410df2 100644 --- a/src/tools/tidy/src/style.rs +++ b/src/tools/tidy/src/style.rs @@ -153,9 +153,9 @@ fn contains_ignore_directive(can_contain: bool, contents: &str, check: &str) -> return Directive::Deny; } // Update `can_contain` when changing this - if contents.contains(&format!("// ignore-tidy-{}", check)) - || contents.contains(&format!("# ignore-tidy-{}", check)) - || contents.contains(&format!("/* ignore-tidy-{} */", check)) + if contents.contains(&format!("// ignore-tidy-{check}")) + || contents.contains(&format!("# ignore-tidy-{check}")) + || contents.contains(&format!("/* ignore-tidy-{check} */")) { Directive::Ignore(false) } else { @@ -294,7 +294,7 @@ pub fn check(path: &Path, bad: &mut bool) { suppressible_tidy_err!( err, skip_line_length, - &format!("line longer than {} chars", max_columns) + &format!("line longer than {max_columns} chars") ); } if !is_style_file && line.contains('\t') { @@ -381,7 +381,7 @@ pub fn check(path: &Path, bad: &mut bool) { n => suppressible_tidy_err!( err, skip_trailing_newlines, - &format!("too many trailing newlines ({})", n) + &format!("too many trailing newlines ({n})") ), }; if lines > LINES { diff --git a/src/tools/tidy/src/target_specific_tests.rs b/src/tools/tidy/src/target_specific_tests.rs index 8e1749196d2ec..723684bfa4cda 100644 --- a/src/tools/tidy/src/target_specific_tests.rs +++ b/src/tools/tidy/src/target_specific_tests.rs @@ -20,7 +20,7 @@ fn iter_header<'a>(contents: &'a str, it: &mut dyn FnMut(Option<&'a str>, &'a st let lncfg = &ln[open_brace + 1..close_brace]; it(Some(lncfg), ln[(close_brace + 1)..].trim_start()); } else { - panic!("malformed condition directive: expected `//[foo]`, found `{}`", ln) + panic!("malformed condition directive: expected `//[foo]`, found `{ln}`") } } else if ln.starts_with(COMMENT) { it(None, ln[COMMENT.len()..].trim_start()); @@ -61,7 +61,7 @@ pub fn check(path: &Path, bad: &mut bool) { let info = header_map.entry(cfg).or_insert(RevisionInfo::default()); info.target_arch.replace(arch); } else { - eprintln!("{}: seems to have a malformed --target value", file); + eprintln!("{file}: seems to have a malformed --target value"); *bad = true; } } diff --git a/src/tools/unicode-table-generator/src/main.rs b/src/tools/unicode-table-generator/src/main.rs index 218e9668df4ae..4720ee7020f89 100644 --- a/src/tools/unicode-table-generator/src/main.rs +++ b/src/tools/unicode-table-generator/src/main.rs @@ -277,7 +277,7 @@ fn main() { for (name, contents) in modules { table_file.push_str("#[rustfmt::skip]\n"); - table_file.push_str(&format!("pub mod {} {{\n", name)); + table_file.push_str(&format!("pub mod {name} {{\n")); for line in contents.lines() { if !line.trim().is_empty() { table_file.push_str(" "); @@ -290,7 +290,7 @@ fn main() { std::fs::write(&write_location, format!("{}\n", table_file.trim_end())).unwrap(); - println!("Total table sizes: {} bytes", total_bytes); + println!("Total table sizes: {total_bytes} bytes"); } fn version() -> String { @@ -308,7 +308,7 @@ fn version() -> String { readme[start..end].split('.').map(|v| v.parse::().expect(&v)).collect::>(); let [major, minor, micro] = [version[0], version[1], version[2]]; - out.push_str(&format!("({}, {}, {});\n", major, minor, micro)); + out.push_str(&format!("({major}, {minor}, {micro});\n")); out } @@ -322,7 +322,7 @@ fn fmt_list(values: impl IntoIterator) -> String { } else { out.push_str(line.trim_end()); out.push('\n'); - line = format!(" {}", piece); + line = format!(" {piece}"); } } out.push_str(line.trim_end()); @@ -335,7 +335,7 @@ fn generate_tests(data_path: &str, ranges: &[(&str, Vec>)]) -> String s.push_str("#![allow(incomplete_features, unused)]\n"); s.push_str("#![feature(const_generics)]\n\n"); s.push_str("\n#[allow(unused)]\nuse std::hint;\n"); - s.push_str(&format!("#[path = \"{}\"]\n", data_path)); + s.push_str(&format!("#[path = \"{data_path}\"]\n")); s.push_str("mod unicode_data;\n\n"); s.push_str("\nfn main() {\n"); diff --git a/src/tools/unicode-table-generator/src/unicode_download.rs b/src/tools/unicode-table-generator/src/unicode_download.rs index fa57f650ac082..9b2e0a25891c7 100644 --- a/src/tools/unicode-table-generator/src/unicode_download.rs +++ b/src/tools/unicode-table-generator/src/unicode_download.rs @@ -13,13 +13,12 @@ pub fn fetch_latest() { let directory = Path::new(UNICODE_DIRECTORY); if directory.exists() { eprintln!( - "Not refetching unicode data, already exists, please delete {:?} to regenerate", - directory + "Not refetching unicode data, already exists, please delete {directory:?} to regenerate", ); return; } if let Err(e) = std::fs::create_dir_all(directory) { - panic!("Failed to create {:?}: {}", UNICODE_DIRECTORY, e); + panic!("Failed to create {UNICODE_DIRECTORY:?}: {e}"); } let output = Command::new("curl").arg(URL_PREFIX.to_owned() + README).output().unwrap(); if !output.status.success() { diff --git a/src/tools/unstable-book-gen/src/main.rs b/src/tools/unstable-book-gen/src/main.rs index e10f72a47b2c4..5a0477b4b941e 100644 --- a/src/tools/unstable-book-gen/src/main.rs +++ b/src/tools/unstable-book-gen/src/main.rs @@ -67,7 +67,7 @@ fn generate_unstable_book_files(src: &Path, out: &Path, features: &Features) { t!(fs::create_dir_all(&out)); for feature_name in &unstable_features - &unstable_section_file_names { let feature_name_underscore = feature_name.replace('-', "_"); - let file_name = format!("{}.md", feature_name); + let file_name = format!("{feature_name}.md"); let out_file_path = out.join(&file_name); let feature = &features[&feature_name_underscore]; diff --git a/src/tools/x/src/main.rs b/src/tools/x/src/main.rs index 6c0311433d676..8c47559b36939 100644 --- a/src/tools/x/src/main.rs +++ b/src/tools/x/src/main.rs @@ -58,7 +58,7 @@ fn main() { let current = match env::current_dir() { Ok(dir) => dir, Err(err) => { - eprintln!("Failed to get current directory: {}", err); + eprintln!("Failed to get current directory: {err}"); process::exit(1); } }; From 5d830f4804ef9fb6d8ebcb678c7c683b0c1c6e38 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 10 Mar 2022 17:49:50 +0100 Subject: [PATCH 11/11] Update browser-ui-test version --- src/ci/docker/host-x86_64/x86_64-gnu-tools/Dockerfile | 2 +- src/tools/rustdoc-gui/tester.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ci/docker/host-x86_64/x86_64-gnu-tools/Dockerfile b/src/ci/docker/host-x86_64/x86_64-gnu-tools/Dockerfile index f1c42b248f4bd..9b92bed1f02b3 100644 --- a/src/ci/docker/host-x86_64/x86_64-gnu-tools/Dockerfile +++ b/src/ci/docker/host-x86_64/x86_64-gnu-tools/Dockerfile @@ -72,7 +72,7 @@ ENV PATH="/node-v14.4.0-linux-x64/bin:${PATH}" # https://github.com/puppeteer/puppeteer/issues/375 # # We also specify the version in case we need to update it to go around cache limitations. -RUN npm install -g browser-ui-test@0.7.2 --unsafe-perm=true +RUN npm install -g browser-ui-test@0.8.0 --unsafe-perm=true ENV RUST_CONFIGURE_ARGS \ --build=x86_64-unknown-linux-gnu \ diff --git a/src/tools/rustdoc-gui/tester.js b/src/tools/rustdoc-gui/tester.js index 32340ec7eecf2..841c0f2b9395e 100644 --- a/src/tools/rustdoc-gui/tester.js +++ b/src/tools/rustdoc-gui/tester.js @@ -138,7 +138,7 @@ async function main(argv) { try { // This is more convenient that setting fields one by one. let args = [ - "--no-screenshot", + "--no-screenshot-comparison", "--variable", "DOC_PATH", opts["doc_folder"], ]; if (opts["debug"]) {