From 08f7e32a6ec132649aee2b586a9356a95320c5d8 Mon Sep 17 00:00:00 2001 From: Kor Nielsen Date: Wed, 26 Apr 2023 23:56:55 -0700 Subject: [PATCH 1/8] Support RISC-V unaligned-scalar-mem target feature This adds `unaligned-scalar-mem` as an allowed RISC-V target feature. Some RISC-V cores support unaligned access to memory without trapping. On such cores, the compiler could significantly improve code-size and performance when using functions like core::ptr::read_unaligned by emitting a single load or store instruction with an unaligned address, rather than a long sequence of byte load/store/bitmanip instructions. Enabling the `unaligned-scalar-mem` target feature allows LLVM to do this optimization. Fixes #110883 --- compiler/rustc_codegen_ssa/src/target_features.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index 611dd3d1cd18a..df3d0811879cf 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -252,6 +252,7 @@ const RISCV_ALLOWED_FEATURES: &[(&str, Option)] = &[ ("f", Some(sym::riscv_target_feature)), ("m", Some(sym::riscv_target_feature)), ("relax", Some(sym::riscv_target_feature)), + ("unaligned-scalar-mem", Some(sym::riscv_target_feature)), ("v", Some(sym::riscv_target_feature)), ("zba", Some(sym::riscv_target_feature)), ("zbb", Some(sym::riscv_target_feature)), From fd80ab7f135f34332cc78673c18565f65b074297 Mon Sep 17 00:00:00 2001 From: DaniPopes <57450786+DaniPopes@users.noreply.github.com> Date: Thu, 4 May 2023 00:43:17 +0200 Subject: [PATCH 2/8] Specialize ToString implementation for fmt::Arguments --- library/alloc/src/string.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index cf16a3424a092..026425a52015a 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -2614,6 +2614,15 @@ impl ToString for String { } } +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "fmt_arguments_to_string_specialization", since = "CURRENT_RUSTC_VERSION")] +impl ToString for fmt::Arguments<'_> { + #[inline] + fn to_string(&self) -> String { + crate::fmt::format(*self) + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl AsRef for String { #[inline] From 1d640e5338c16964132f0995b93a9d0915668888 Mon Sep 17 00:00:00 2001 From: Collin Baker Date: Wed, 3 May 2023 16:45:43 -0400 Subject: [PATCH 3/8] Update serde in workspace and non-synced dependencies The main workspace, bootstrap, cargo, miri, and rust-analyzer all lock serde to different versions. It's preferable to share the same version where possible, so update it. Rustfmt is synced from another repository and has its own Cargo.lock, but since it's added to the overall workspace it should respect the version here. Cargo is already at the latest version. Miri and rust-analyzer would require upstream updates. --- Cargo.lock | 12 ++++++------ src/bootstrap/Cargo.lock | 16 ++++++++-------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 724587a4a71c1..bcf53be2f4db4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2660,9 +2660,9 @@ checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" [[package]] name = "proc-macro2" -version = "1.0.53" +version = "1.0.56" source = "registry+/~https://github.com/rust-lang/crates.io-index" -checksum = "ba466839c78239c09faf015484e5cc04860f88242cff4d03eb038f04b4699b73" +checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435" dependencies = [ "unicode-ident", ] @@ -4435,18 +4435,18 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.159" +version = "1.0.160" source = "registry+/~https://github.com/rust-lang/crates.io-index" -checksum = "3c04e8343c3daeec41f58990b9d77068df31209f2af111e059e9fe9646693065" +checksum = "bb2f3770c8bce3bcda7e149193a069a0f4365bda1fa5cd88e03bca26afc1216c" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.159" +version = "1.0.160" source = "registry+/~https://github.com/rust-lang/crates.io-index" -checksum = "4c614d17805b093df4b147b51339e7e44bf05ef59fba1e45d83500bcfb4d8585" +checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df" dependencies = [ "proc-macro2", "quote", diff --git a/src/bootstrap/Cargo.lock b/src/bootstrap/Cargo.lock index dfe6bb7f0572e..24714e38ec04b 100644 --- a/src/bootstrap/Cargo.lock +++ b/src/bootstrap/Cargo.lock @@ -128,7 +128,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.15", + "syn 2.0.8", ] [[package]] @@ -637,19 +637,19 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" [[package]] name = "serde" -version = "1.0.137" +version = "1.0.160" source = "registry+/~https://github.com/rust-lang/crates.io-index" -checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" +checksum = "bb2f3770c8bce3bcda7e149193a069a0f4365bda1fa5cd88e03bca26afc1216c" [[package]] name = "serde_derive" -version = "1.0.137" +version = "1.0.160" source = "registry+/~https://github.com/rust-lang/crates.io-index" -checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" +checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df" dependencies = [ "proc-macro2", "quote", - "syn 1.0.102", + "syn 2.0.8", ] [[package]] @@ -687,9 +687,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.15" +version = "2.0.8" source = "registry+/~https://github.com/rust-lang/crates.io-index" -checksum = "a34fcf3e8b60f57e6a14301a2e916d323af98b0ea63c599441eec8558660c822" +checksum = "bcc02725fd69ab9f26eab07fad303e2497fad6fb9eba4f96c4d1687bdf704ad9" dependencies = [ "proc-macro2", "quote", From e33d5169e81ee8991b03f58550254a17c547fffc Mon Sep 17 00:00:00 2001 From: kirk Date: Sat, 13 May 2023 06:26:37 +0000 Subject: [PATCH 4/8] add examples of port 0 binding behavior --- library/std/src/net/tcp.rs | 9 +++++++++ library/std/src/net/udp.rs | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/library/std/src/net/tcp.rs b/library/std/src/net/tcp.rs index 541e95d229b62..141a18a42dde6 100644 --- a/library/std/src/net/tcp.rs +++ b/library/std/src/net/tcp.rs @@ -756,6 +756,15 @@ impl TcpListener { /// ]; /// let listener = TcpListener::bind(&addrs[..]).unwrap(); /// ``` + /// + /// Creates a TCP listener bound to a port assigned by the operating system + /// at `127.0.0.1`. + /// + /// ```no_run + /// use std::net::TcpListener; + /// + /// let socket = TcpListener::bind("127.0.0.1:0").unwrap(); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn bind(addr: A) -> io::Result { super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener) diff --git a/library/std/src/net/udp.rs b/library/std/src/net/udp.rs index 9628bcc51083d..5ca4ed832f340 100644 --- a/library/std/src/net/udp.rs +++ b/library/std/src/net/udp.rs @@ -90,6 +90,15 @@ impl UdpSocket { /// ]; /// let socket = UdpSocket::bind(&addrs[..]).expect("couldn't bind to address"); /// ``` + /// + /// Creates a UDP socket bound to a port assigned by the operating system + /// at `127.0.0.1`. + /// + /// ```no_run + /// use std::net::UdpSocket; + /// + /// let socket = UdpSocket::bind("127.0.0.1:0").unwrap(); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn bind(addr: A) -> io::Result { super::each_addr(addr, net_imp::UdpSocket::bind).map(UdpSocket) From 6b7b7758d00710d093c542d3f8dbbf434cb26df3 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sun, 14 May 2023 07:13:00 -0700 Subject: [PATCH 5/8] Include better context for "already exists" error in compiletest --- Cargo.lock | 1 + src/tools/compiletest/Cargo.toml | 1 + src/tools/compiletest/src/runtest.rs | 7 ++++++- 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 60686c87359d9..e71d97a6303e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -723,6 +723,7 @@ dependencies = [ name = "compiletest" version = "0.0.0" dependencies = [ + "anyhow", "build_helper", "colored", "diff", diff --git a/src/tools/compiletest/Cargo.toml b/src/tools/compiletest/Cargo.toml index 0d42504c7f4ca..e5297d41a6119 100644 --- a/src/tools/compiletest/Cargo.toml +++ b/src/tools/compiletest/Cargo.toml @@ -20,6 +20,7 @@ once_cell = "1.16.0" walkdir = "2" glob = "0.3.0" lazycell = "1.3.0" +anyhow = "1" [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 4ede46037894b..5bc4d16426551 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -32,6 +32,7 @@ use std::process::{Child, Command, ExitStatus, Output, Stdio}; use std::str; use std::sync::Arc; +use anyhow::Context; use glob::glob; use once_cell::sync::Lazy; use tracing::*; @@ -131,7 +132,11 @@ pub fn run(config: Arc, testpaths: &TestPaths, revision: Option<&str>) { } let cx = TestCx { config: &config, props: &props, testpaths, revision }; - create_dir_all(&cx.output_base_dir()).unwrap(); + create_dir_all(&cx.output_base_dir()) + .with_context(|| { + format!("failed to create output base directory {}", cx.output_base_dir().display()) + }) + .unwrap(); if props.incremental { cx.init_incremental_test(); } From 87a2bc027c4cfd126bc95f864d229d5cb5f7f00c Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 4 May 2023 12:51:29 +1000 Subject: [PATCH 6/8] Remove `Session::span_err_or_warn`. It's unused. --- compiler/rustc_session/src/session.rs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index a988d7f28e6cb..151325fcb08a5 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -490,20 +490,6 @@ impl Session { } #[rustc_lint_diagnostics] #[track_caller] - pub fn span_err_or_warn>( - &self, - is_warning: bool, - sp: S, - msg: impl Into, - ) { - if is_warning { - self.span_warn(sp, msg); - } else { - self.span_err(sp, msg); - } - } - #[rustc_lint_diagnostics] - #[track_caller] pub fn span_err>( &self, sp: S, From 01e33a3600789b0e96511c4ac95fc114b507c79e Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 16 May 2023 16:04:03 +1000 Subject: [PATCH 7/8] Avoid `&format("...")` calls in error message code. Error message all end up passing into a function as an `impl Into<{D,Subd}iagnosticMessage>`. If an error message is creatd as `&format("...")` that means we allocate a string (in the `format!` call), then take a reference, and then clone (allocating again) the reference to produce the `{D,Subd}iagnosticMessage`, which is silly. This commit removes the leading `&` from a lot of these cases. This means the original `String` is moved into the `{D,Subd}iagnosticMessage`, avoiding the double allocations. This requires changing some function argument types from `&str` to `String` (when all arguments are `String`) or `impl Into<{D,Subd}iagnosticMessage>` (when some arguments are `String` and some are `&str`). --- compiler/rustc_abi/src/layout.rs | 4 +- compiler/rustc_borrowck/src/nll.rs | 4 +- compiler/rustc_borrowck/src/type_check/mod.rs | 4 +- compiler/rustc_builtin_macros/src/asm.rs | 6 +- .../src/deriving/clone.rs | 8 +-- .../src/deriving/generic/mod.rs | 2 +- compiler/rustc_builtin_macros/src/format.rs | 2 +- .../rustc_builtin_macros/src/source_util.rs | 6 +- .../src/pretty_clif.rs | 2 +- compiler/rustc_driver_impl/src/args.rs | 2 +- compiler/rustc_driver_impl/src/lib.rs | 12 ++-- compiler/rustc_expand/src/base.rs | 11 ++-- compiler/rustc_expand/src/expand.rs | 2 +- compiler/rustc_expand/src/mbe/diagnostics.rs | 4 +- compiler/rustc_expand/src/mbe/macro_check.rs | 13 ++-- compiler/rustc_expand/src/mbe/transcribe.rs | 2 +- .../src/astconv/generics.rs | 4 +- .../rustc_hir_analysis/src/collect/type_of.rs | 12 ++-- compiler/rustc_hir_typeck/src/expr.rs | 2 +- .../rustc_hir_typeck/src/method/confirm.rs | 2 +- compiler/rustc_hir_typeck/src/method/mod.rs | 4 +- compiler/rustc_hir_typeck/src/writeback.rs | 2 +- compiler/rustc_interface/src/interface.rs | 7 +-- compiler/rustc_interface/src/util.rs | 14 ++--- compiler/rustc_metadata/src/creader.rs | 2 +- compiler/rustc_middle/src/ty/context.rs | 8 ++- compiler/rustc_middle/src/ty/layout.rs | 2 +- compiler/rustc_parse/src/lexer/mod.rs | 2 +- compiler/rustc_parse/src/validate_attr.rs | 2 +- compiler/rustc_session/src/config.rs | 61 +++++++++---------- compiler/rustc_session/src/options.rs | 6 +- compiler/rustc_session/src/parse.rs | 4 +- compiler/rustc_session/src/session.rs | 15 +++-- .../src/traits/project.rs | 2 +- src/librustdoc/html/markdown.rs | 4 +- src/librustdoc/lib.rs | 8 +-- .../passes/collect_intra_doc_links.rs | 25 ++++---- 37 files changed, 139 insertions(+), 133 deletions(-) diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index 3d97d9b489508..f11c1c77f9cfc 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -12,7 +12,7 @@ use tracing::debug; pub trait LayoutCalculator { type TargetDataLayoutRef: Borrow; - fn delay_bug(&self, txt: &str); + fn delay_bug(&self, txt: String); fn current_data_layout(&self) -> Self::TargetDataLayoutRef; fn scalar_pair(&self, a: Scalar, b: Scalar) -> LayoutS { @@ -969,7 +969,7 @@ fn univariant( for &i in &inverse_memory_index { let field = &fields[i]; if !sized { - this.delay_bug(&format!( + this.delay_bug(format!( "univariant: field #{} comes after unsized field", offsets.len(), )); diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs index a4394ddc01c5a..b6ccf924a5c88 100644 --- a/compiler/rustc_borrowck/src/nll.rs +++ b/compiler/rustc_borrowck/src/nll.rs @@ -430,7 +430,7 @@ pub(super) fn dump_annotation<'tcx>( fn for_each_region_constraint<'tcx>( tcx: TyCtxt<'tcx>, closure_region_requirements: &ClosureRegionRequirements<'tcx>, - with_msg: &mut dyn FnMut(&str) -> io::Result<()>, + with_msg: &mut dyn FnMut(String) -> io::Result<()>, ) -> io::Result<()> { for req in &closure_region_requirements.outlives_requirements { let subject = match req.subject { @@ -439,7 +439,7 @@ fn for_each_region_constraint<'tcx>( format!("{:?}", ty.instantiate(tcx, |vid| tcx.mk_re_var(vid))) } }; - with_msg(&format!("where {}: {:?}", subject, req.outlived_free_region,))?; + with_msg(format!("where {}: {:?}", subject, req.outlived_free_region,))?; } Ok(()) } diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index 33b24b68f7cfc..fa4bc926f2739 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -71,7 +71,7 @@ macro_rules! span_mirbug { $crate::type_check::mirbug( $context.tcx(), $context.last_span, - &format!( + format!( "broken MIR in {:?} ({:?}): {}", $context.body().source.def_id(), $elem, @@ -274,7 +274,7 @@ fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) { } #[track_caller] -fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) { +fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: String) { // We sometimes see MIR failures (notably predicate failures) due to // the fact that we check rvalue sized predicates here. So use `delay_span_bug` // to avoid reporting bugs in those cases. diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs index bb059a120df37..5217e317adfee 100644 --- a/compiler/rustc_builtin_macros/src/asm.rs +++ b/compiler/rustc_builtin_macros/src/asm.rs @@ -550,7 +550,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option, args: AsmArgs) -> Option, args: AsmArgs) -> Option cx.span_bug( trait_span, - &format!("unexpected substructure in simple `derive({})`", name), + format!("unexpected substructure in simple `derive({})`", name), ), } } @@ -179,10 +179,10 @@ fn cs_clone( vdata = &variant.data; } EnumTag(..) | AllFieldlessEnum(..) => { - cx.span_bug(trait_span, &format!("enum tags in `derive({})`", name,)) + cx.span_bug(trait_span, format!("enum tags in `derive({})`", name,)) } StaticEnum(..) | StaticStruct(..) => { - cx.span_bug(trait_span, &format!("associated function in `derive({})`", name)) + cx.span_bug(trait_span, format!("associated function in `derive({})`", name)) } } @@ -194,7 +194,7 @@ fn cs_clone( let Some(ident) = field.name else { cx.span_bug( trait_span, - &format!("unnamed field in normal struct in `derive({})`", name,), + format!("unnamed field in normal struct in `derive({})`", name,), ); }; let call = subcall(cx, field); diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index caced3d644724..4ba09335cb7ab 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -1591,7 +1591,7 @@ impl<'a> TraitDef<'a> { BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE, sp, ast::CRATE_NODE_ID, - &format!( + format!( "{} slice in a packed struct that derives a built-in trait", ty ), diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index adc12ec84f514..c59a733c05568 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -814,7 +814,7 @@ fn report_invalid_references( }; e = ecx.struct_span_err( span, - &format!("invalid reference to positional {} ({})", arg_list, num_args_desc), + format!("invalid reference to positional {} ({})", arg_list, num_args_desc), ); e.note("positional arguments are zero-based"); } diff --git a/compiler/rustc_builtin_macros/src/source_util.rs b/compiler/rustc_builtin_macros/src/source_util.rs index b8a24f1102daf..e613b904d2eaf 100644 --- a/compiler/rustc_builtin_macros/src/source_util.rs +++ b/compiler/rustc_builtin_macros/src/source_util.rs @@ -188,12 +188,12 @@ pub fn expand_include_str( base::MacEager::expr(cx.expr_str(sp, interned_src)) } Err(_) => { - cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display())); + cx.span_err(sp, format!("{} wasn't a utf-8 file", file.display())); DummyResult::any(sp) } }, Err(e) => { - cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e)); + cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e)); DummyResult::any(sp) } } @@ -221,7 +221,7 @@ pub fn expand_include_bytes( base::MacEager::expr(expr) } Err(e) => { - cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e)); + cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e)); DummyResult::any(sp) } } diff --git a/compiler/rustc_codegen_cranelift/src/pretty_clif.rs b/compiler/rustc_codegen_cranelift/src/pretty_clif.rs index 27e21183c5567..1007b33eca42d 100644 --- a/compiler/rustc_codegen_cranelift/src/pretty_clif.rs +++ b/compiler/rustc_codegen_cranelift/src/pretty_clif.rs @@ -227,7 +227,7 @@ pub(crate) fn write_ir_file( // Using early_warn as no Session is available here rustc_session::early_warn( rustc_session::config::ErrorOutputType::default(), - &format!("error writing ir file: {}", err), + format!("error writing ir file: {}", err), ); } } diff --git a/compiler/rustc_driver_impl/src/args.rs b/compiler/rustc_driver_impl/src/args.rs index 42c97cc6a9d74..a713affa09919 100644 --- a/compiler/rustc_driver_impl/src/args.rs +++ b/compiler/rustc_driver_impl/src/args.rs @@ -25,7 +25,7 @@ pub fn arg_expand_all(at_args: &[String]) -> Vec { Ok(arg) => args.extend(arg), Err(err) => rustc_session::early_error( rustc_session::config::ErrorOutputType::default(), - &format!("Failed to load argument file: {err}"), + format!("Failed to load argument file: {err}"), ), } } diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 80a9dfd251a79..cf2ab3c2d2ad1 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -322,7 +322,7 @@ fn run_compiler( 1 => panic!("make_input should have provided valid inputs"), _ => early_error( config.opts.error_format, - &format!( + format!( "multiple input filenames provided (first two filenames are `{}` and `{}`)", matches.free[0], matches.free[1], ), @@ -527,7 +527,7 @@ fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) { } } Err(InvalidErrorCode) => { - early_error(output, &format!("{code} is not a valid error code")); + early_error(output, format!("{code} is not a valid error code")); } } } @@ -1102,7 +1102,7 @@ pub fn handle_options(args: &[String]) -> Option { .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")), _ => None, }; - early_error(ErrorOutputType::default(), &msg.unwrap_or_else(|| e.to_string())); + early_error(ErrorOutputType::default(), msg.unwrap_or_else(|| e.to_string())); }); // For all options we just parsed, we check a few aspects: @@ -1250,7 +1250,7 @@ pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&Handler)) #[cfg(windows)] if let Some(msg) = info.payload().downcast_ref::() { if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)") { - early_error_no_abort(ErrorOutputType::default(), &msg); + early_error_no_abort(ErrorOutputType::default(), msg.as_str()); return; } }; @@ -1342,7 +1342,7 @@ pub fn init_rustc_env_logger() { /// other than `RUSTC_LOG`. pub fn init_env_logger(env: &str) { if let Err(error) = rustc_log::init_env_logger(env) { - early_error(ErrorOutputType::default(), &error.to_string()); + early_error(ErrorOutputType::default(), error.to_string()); } } @@ -1409,7 +1409,7 @@ pub fn main() -> ! { arg.into_string().unwrap_or_else(|arg| { early_error( ErrorOutputType::default(), - &format!("argument {i} is not valid Unicode: {arg:?}"), + format!("argument {i} is not valid Unicode: {arg:?}"), ) }) }) diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index e03576c55f436..fd72174906647 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -15,7 +15,8 @@ use rustc_attr::{self as attr, Deprecation, Stability}; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::sync::{self, Lrc}; use rustc_errors::{ - Applicability, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, MultiSpan, PResult, + Applicability, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed, IntoDiagnostic, + MultiSpan, PResult, }; use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT; use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, RegisteredTools}; @@ -1110,7 +1111,7 @@ impl<'a> ExtCtxt<'a> { pub fn struct_span_err>( &self, sp: S, - msg: &str, + msg: impl Into, ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg) } @@ -1132,14 +1133,14 @@ impl<'a> ExtCtxt<'a> { /// Compilation will be stopped in the near future (at the end of /// the macro expansion phase). #[rustc_lint_diagnostics] - pub fn span_err>(&self, sp: S, msg: &str) { + pub fn span_err>(&self, sp: S, msg: impl Into) { self.sess.parse_sess.span_diagnostic.span_err(sp, msg); } #[rustc_lint_diagnostics] - pub fn span_warn>(&self, sp: S, msg: &str) { + pub fn span_warn>(&self, sp: S, msg: impl Into) { self.sess.parse_sess.span_diagnostic.span_warn(sp, msg); } - pub fn span_bug>(&self, sp: S, msg: &str) -> ! { + pub fn span_bug>(&self, sp: S, msg: impl Into) -> ! { self.sess.parse_sess.span_diagnostic.span_bug(sp, msg); } pub fn trace_macros_diag(&mut self) { diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 7c78970345ad5..1f77e687bb18d 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -1664,7 +1664,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { &UNUSED_ATTRIBUTES, attr.span, self.cx.current_expansion.lint_node_id, - &format!("unused attribute `{}`", attr_name), + format!("unused attribute `{}`", attr_name), BuiltinLintDiagnostics::UnusedBuiltinAttribute { attr_name, macro_name: pprust::path_to_string(&call.path), diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index 35572292271c4..cb8b4899e485c 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -48,7 +48,7 @@ pub(super) fn failed_to_match_macro<'cx>( let span = token.span.substitute_dummy(sp); - let mut err = cx.struct_span_err(span, &parse_failure_msg(&token)); + let mut err = cx.struct_span_err(span, parse_failure_msg(&token)); err.span_label(span, label); if !def_span.is_dummy() && !cx.source_map().is_imported(def_span) { err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro"); @@ -170,7 +170,7 @@ impl<'a, 'cx, 'matcher> Tracker<'matcher> for CollectTrackerAndEmitter<'a, 'cx, } Error(err_sp, msg) => { let span = err_sp.substitute_dummy(self.root_span); - self.cx.struct_span_err(span, msg).emit(); + self.cx.struct_span_err(span, msg.as_str()).emit(); self.result = Some(DummyResult::any(span)); } ErrorReported(_) => self.result = Some(DummyResult::any(self.root_span)), diff --git a/compiler/rustc_expand/src/mbe/macro_check.rs b/compiler/rustc_expand/src/mbe/macro_check.rs index 75b6396f0be38..34f998274e995 100644 --- a/compiler/rustc_expand/src/mbe/macro_check.rs +++ b/compiler/rustc_expand/src/mbe/macro_check.rs @@ -110,7 +110,7 @@ use crate::mbe::{KleeneToken, TokenTree}; use rustc_ast::token::{Delimiter, Token, TokenKind}; use rustc_ast::{NodeId, DUMMY_NODE_ID}; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::MultiSpan; +use rustc_errors::{DiagnosticMessage, MultiSpan}; use rustc_session::lint::builtin::{META_VARIABLE_MISUSE, MISSING_FRAGMENT_SPECIFIER}; use rustc_session::parse::ParseSess; use rustc_span::symbol::kw; @@ -593,7 +593,7 @@ fn check_ops_is_prefix( return; } } - buffer_lint(sess, span.into(), node_id, &format!("unknown macro variable `{}`", name)); + buffer_lint(sess, span.into(), node_id, format!("unknown macro variable `{}`", name)); } /// Returns whether `binder_ops` is a prefix of `occurrence_ops`. @@ -626,7 +626,7 @@ fn ops_is_prefix( if i >= occurrence_ops.len() { let mut span = MultiSpan::from_span(span); span.push_span_label(binder.span, "expected repetition"); - let message = &format!("variable '{}' is still repeating at this depth", name); + let message = format!("variable '{}' is still repeating at this depth", name); buffer_lint(sess, span, node_id, message); return; } @@ -642,7 +642,12 @@ fn ops_is_prefix( } } -fn buffer_lint(sess: &ParseSess, span: MultiSpan, node_id: NodeId, message: &str) { +fn buffer_lint( + sess: &ParseSess, + span: MultiSpan, + node_id: NodeId, + message: impl Into, +) { // Macros loaded from other crates have dummy node ids. if node_id != DUMMY_NODE_ID { sess.buffer_lint(&META_VARIABLE_MISUSE, span, node_id, message); diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index a07cb65170dca..d523d3eacbeb9 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -510,7 +510,7 @@ fn out_of_bounds_err<'a>( must be less than {max}" ) }; - cx.struct_span_err(span, &msg) + cx.struct_span_err(span, msg) } fn transcribe_metavar_expr<'a>( diff --git a/compiler/rustc_hir_analysis/src/astconv/generics.rs b/compiler/rustc_hir_analysis/src/astconv/generics.rs index ed011b9086a19..39d1d1f2de52a 100644 --- a/compiler/rustc_hir_analysis/src/astconv/generics.rs +++ b/compiler/rustc_hir_analysis/src/astconv/generics.rs @@ -24,7 +24,7 @@ fn generic_arg_mismatch_err( arg: &GenericArg<'_>, param: &GenericParamDef, possible_ordering_error: bool, - help: Option<&str>, + help: Option, ) -> ErrorGuaranteed { let sess = tcx.sess; let mut err = struct_span_err!( @@ -300,7 +300,7 @@ pub fn create_substs_for_generic_args<'tcx, 'a>( arg, param, !args_iter.clone().is_sorted_by_key(|arg| arg.to_ord()), - Some(&format!( + Some(format!( "reorder the arguments: {}: `<{}>`", param_types_present .into_iter() diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 6c7c2b9eea258..ca430a5e86324 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -164,7 +164,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { let Some(type_dependent_def) = tables.type_dependent_def_id(parent_node_id) else { return tcx.ty_error_with_message( tcx.def_span(def_id), - &format!("unable to find type-dependent def for {:?}", parent_node_id), + format!("unable to find type-dependent def for {:?}", parent_node_id), ); }; let idx = segment @@ -205,14 +205,14 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { } else { return tcx.ty_error_with_message( tcx.def_span(def_id), - &format!("unable to find const parent for {} in pat {:?}", hir_id, pat), + format!("unable to find const parent for {} in pat {:?}", hir_id, pat), ); } } _ => { return tcx.ty_error_with_message( tcx.def_span(def_id), - &format!("unexpected const parent path {:?}", parent_node), + format!("unexpected const parent path {:?}", parent_node), ); } }; @@ -243,7 +243,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { None => { return tcx.ty_error_with_message( tcx.def_span(def_id), - &format!("unexpected anon const res {:?} in path: {:?}", segment.res, path), + format!("unexpected anon const res {:?} in path: {:?}", segment.res, path), ); } }; @@ -253,7 +253,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { _ => return tcx.ty_error_with_message( tcx.def_span(def_id), - &format!("unexpected const parent in type_of(): {parent_node:?}"), + format!("unexpected const parent in type_of(): {parent_node:?}"), ), }; @@ -279,7 +279,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { } else { return tcx.ty_error_with_message( tcx.def_span(def_id), - &format!("const generic parameter not found in {generics:?} at position {arg_idx:?}"), + format!("const generic parameter not found in {generics:?} at position {arg_idx:?}"), ); } } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index bba049c381934..5edffb50a2bac 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -2468,7 +2468,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { self.suggest_method_call( &mut err, - &format!("a method `{field}` also exists, call it with parentheses"), + format!("a method `{field}` also exists, call it with parentheses"), field, expr_t, expr, diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 9155a3d8daa19..59bf45f0ed210 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -158,7 +158,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { let Some((ty, n)) = autoderef.nth(pick.autoderefs) else { return self.tcx.ty_error_with_message( rustc_span::DUMMY_SP, - &format!("failed autoderef {}", pick.autoderefs), + format!("failed autoderef {}", pick.autoderefs), ); }; assert_eq!(n, pick.autoderefs); diff --git a/compiler/rustc_hir_typeck/src/method/mod.rs b/compiler/rustc_hir_typeck/src/method/mod.rs index cf9290c1a4841..6f4d674ba103b 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -13,7 +13,7 @@ pub use self::MethodError::*; use crate::errors::OpMethodGenericParams; use crate::FnCtxt; use rustc_data_structures::sync::Lrc; -use rustc_errors::{Applicability, Diagnostic}; +use rustc_errors::{Applicability, Diagnostic, SubdiagnosticMessage}; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Namespace}; use rustc_hir::def_id::DefId; @@ -130,7 +130,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub(crate) fn suggest_method_call( &self, err: &mut Diagnostic, - msg: &str, + msg: impl Into + std::fmt::Debug, method_name: Ident, self_ty: Ty<'tcx>, call_expr: &hir::Expr<'tcx>, diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index 59bee69cfffac..eed3c65eccc0e 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -237,7 +237,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { // error has been emitted. (#64638) self.fcx.tcx.ty_error_with_message( e.span, - &format!("bad index {:?} for base: `{:?}`", index, base), + format!("bad index {:?} for base: `{:?}`", index, base), ) }); let index_ty = self.fcx.resolve_vars_if_possible(index_ty); diff --git a/compiler/rustc_interface/src/interface.rs b/compiler/rustc_interface/src/interface.rs index c9e857141c92a..681819703c298 100644 --- a/compiler/rustc_interface/src/interface.rs +++ b/compiler/rustc_interface/src/interface.rs @@ -80,7 +80,7 @@ pub fn parse_cfgspecs(cfgspecs: Vec) -> FxHashSet<(String, Option { early_error( ErrorOutputType::default(), - &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s), + format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s), ); }; } @@ -139,10 +139,7 @@ pub fn parse_check_cfg(specs: Vec) -> CheckCfg { ($reason: expr) => { early_error( ErrorOutputType::default(), - &format!( - concat!("invalid `--check-cfg` argument: `{}` (", $reason, ")"), - s - ), + format!(concat!("invalid `--check-cfg` argument: `{}` (", $reason, ")"), s), ) }; } diff --git a/compiler/rustc_interface/src/util.rs b/compiler/rustc_interface/src/util.rs index 8d37b1053d800..910cafff769fd 100644 --- a/compiler/rustc_interface/src/util.rs +++ b/compiler/rustc_interface/src/util.rs @@ -88,7 +88,7 @@ pub fn create_session( ) { Ok(bundle) => bundle, Err(e) => { - early_error(sopts.error_format, &format!("failed to load fluent bundle: {e}")); + early_error(sopts.error_format, format!("failed to load fluent bundle: {e}")); } }; @@ -220,13 +220,13 @@ pub(crate) fn run_in_thread_pool_with_globals R + Send, R: Send>( fn load_backend_from_dylib(path: &Path) -> MakeBackendFn { let lib = unsafe { Library::new(path) }.unwrap_or_else(|err| { let err = format!("couldn't load codegen backend {path:?}: {err}"); - early_error(ErrorOutputType::default(), &err); + early_error(ErrorOutputType::default(), err); }); let backend_sym = unsafe { lib.get::(b"__rustc_codegen_backend") } .unwrap_or_else(|e| { let err = format!("couldn't load codegen backend: {e}"); - early_error(ErrorOutputType::default(), &err); + early_error(ErrorOutputType::default(), err); }); // Intentionally leak the dynamic library. We can't ever unload it @@ -320,7 +320,7 @@ fn get_codegen_sysroot(maybe_sysroot: &Option, backend_name: &str) -> M "failed to find a `codegen-backends` folder \ in the sysroot candidates:\n* {candidates}" ); - early_error(ErrorOutputType::default(), &err); + early_error(ErrorOutputType::default(), err); }); info!("probing {} for a codegen backend", sysroot.display()); @@ -331,7 +331,7 @@ fn get_codegen_sysroot(maybe_sysroot: &Option, backend_name: &str) -> M sysroot.display(), e ); - early_error(ErrorOutputType::default(), &err); + early_error(ErrorOutputType::default(), err); }); let mut file: Option = None; @@ -359,7 +359,7 @@ fn get_codegen_sysroot(maybe_sysroot: &Option, backend_name: &str) -> M prev.display(), path.display() ); - early_error(ErrorOutputType::default(), &err); + early_error(ErrorOutputType::default(), err); } file = Some(path.clone()); } @@ -368,7 +368,7 @@ fn get_codegen_sysroot(maybe_sysroot: &Option, backend_name: &str) -> M Some(ref s) => load_backend_from_dylib(s), None => { let err = format!("unsupported builtin codegen backend `{backend_name}`"); - early_error(ErrorOutputType::default(), &err); + early_error(ErrorOutputType::default(), err); } } } diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index e6e7d25773e67..98ea9dc750127 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -943,7 +943,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { lint::builtin::UNUSED_CRATE_DEPENDENCIES, span, ast::CRATE_NODE_ID, - &format!( + format!( "external crate `{}` unused in `{}`: remove the dependency or add `use {} as _;`", name, self.tcx.crate_name(LOCAL_CRATE), diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 097bfb71a6fc8..314f698f49889 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -702,7 +702,11 @@ impl<'tcx> TyCtxt<'tcx> { /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg` to /// ensure it gets used. #[track_caller] - pub fn ty_error_with_message>(self, span: S, msg: &str) -> Ty<'tcx> { + pub fn ty_error_with_message>( + self, + span: S, + msg: impl Into, + ) -> Ty<'tcx> { let reported = self.sess.delay_span_bug(span, msg); self.mk_ty_from_kind(Error(reported)) } @@ -2435,7 +2439,7 @@ impl<'tcx> TyCtxtAt<'tcx> { /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` with the given `msg` to /// ensure it gets used. #[track_caller] - pub fn ty_error_with_message(self, msg: &str) -> Ty<'tcx> { + pub fn ty_error_with_message(self, msg: impl Into) -> Ty<'tcx> { self.tcx.ty_error_with_message(self.span, msg) } } diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 47cf48f46cf89..f5652c1c1e17c 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -268,7 +268,7 @@ pub struct LayoutCx<'tcx, C> { impl<'tcx> LayoutCalculator for LayoutCx<'tcx, TyCtxt<'tcx>> { type TargetDataLayoutRef = &'tcx TargetDataLayout; - fn delay_bug(&self, txt: &str) { + fn delay_bug(&self, txt: String) { self.tcx.sess.delay_span_bug(DUMMY_SP, txt); } diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs index 51e904890028a..c6e6b46e4551c 100644 --- a/compiler/rustc_parse/src/lexer/mod.rs +++ b/compiler/rustc_parse/src/lexer/mod.rs @@ -662,7 +662,7 @@ impl<'a> StringReader<'a> { &RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, prefix_span, ast::CRATE_NODE_ID, - &format!("prefix `{prefix}` is unknown"), + format!("prefix `{prefix}` is unknown"), BuiltinLintDiagnostics::ReservedPrefix(prefix_span), ); } diff --git a/compiler/rustc_parse/src/validate_attr.rs b/compiler/rustc_parse/src/validate_attr.rs index 982c4615affb6..928fdce313d91 100644 --- a/compiler/rustc_parse/src/validate_attr.rs +++ b/compiler/rustc_parse/src/validate_attr.rs @@ -186,7 +186,7 @@ fn emit_malformed_attribute( suggestions.push(code); } if should_warn(name) { - sess.buffer_lint(&ILL_FORMED_ATTRIBUTE_INPUT, span, ast::CRATE_NODE_ID, &msg); + sess.buffer_lint(&ILL_FORMED_ATTRIBUTE_INPUT, span, ast::CRATE_NODE_ID, msg); } else { sess.span_diagnostic .struct_span_err(span, error_msg) diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index e2b8d3eea2d42..39e255104d572 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -1319,7 +1319,7 @@ pub(super) fn build_target_config( let (target, target_warnings) = target_result.unwrap_or_else(|e| { early_error( opts.error_format, - &format!( + format!( "Error loading target specification: {}. \ Run `rustc --print target-list` for a list of built-in targets", e @@ -1327,15 +1327,14 @@ pub(super) fn build_target_config( ) }); for warning in target_warnings.warning_messages() { - early_warn(opts.error_format, &warning) + early_warn(opts.error_format, warning) } if !matches!(target.pointer_width, 16 | 32 | 64) { early_error( opts.error_format, - &format!( - "target specification was invalid: \ - unrecognized target-pointer-width {}", + format!( + "target specification was invalid: unrecognized target-pointer-width {}", target.pointer_width ), ) @@ -1599,7 +1598,7 @@ pub fn get_cmd_lint_options( let lint_cap = matches.opt_str("cap-lints").map(|cap| { lint::Level::from_str(&cap) - .unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{cap}`"))) + .unwrap_or_else(|| early_error(error_format, format!("unknown lint level: `{cap}`"))) }); (lint_opts, describe_lints, lint_cap) @@ -1616,7 +1615,7 @@ pub fn parse_color(matches: &getopts::Matches) -> ColorConfig { Some(arg) => early_error( ErrorOutputType::default(), - &format!( + format!( "argument for `--color` must be auto, \ always or never (instead was `{arg}`)" ), @@ -1691,7 +1690,7 @@ pub fn parse_json(matches: &getopts::Matches) -> JsonConfig { "future-incompat" => json_future_incompat = true, s => early_error( ErrorOutputType::default(), - &format!("unknown `--json` option `{s}`"), + format!("unknown `--json` option `{s}`"), ), } } @@ -1729,7 +1728,7 @@ pub fn parse_error_format( Some(arg) => early_error( ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)), - &format!( + format!( "argument for `--error-format` must be `human`, `json` or \ `short` (instead was `{arg}`)" ), @@ -1763,7 +1762,7 @@ pub fn parse_crate_edition(matches: &getopts::Matches) -> Edition { Some(arg) => Edition::from_str(&arg).unwrap_or_else(|_| { early_error( ErrorOutputType::default(), - &format!( + format!( "argument for `--edition` must be one of: \ {EDITION_NAME_LIST}. (instead was `{arg}`)" ), @@ -1782,7 +1781,7 @@ pub fn parse_crate_edition(matches: &getopts::Matches) -> Edition { } else { format!("edition {edition} is unstable and only available with -Z unstable-options") }; - early_error(ErrorOutputType::default(), &msg) + early_error(ErrorOutputType::default(), msg) } edition @@ -1827,7 +1826,7 @@ fn parse_output_types( let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(|| { early_error( error_format, - &format!( + format!( "unknown emission type: `{shorthand}` - expected one of: {display}", display = OutputType::shorthands_display(), ), @@ -1866,7 +1865,7 @@ fn should_override_cgus_and_disable_thinlto( for ot in &incompatible { early_warn( error_format, - &format!( + format!( "`--emit={ot}` with `-o` incompatible with \ `-C codegen-units=N` for N > 1", ), @@ -1970,7 +1969,7 @@ fn collect_print_requests( let prints = prints.join(", "); early_error( error_format, - &format!("unknown print request `{req}`. Valid print requests are: {prints}"), + format!("unknown print request `{req}`. Valid print requests are: {prints}"), ); } } @@ -1987,7 +1986,7 @@ pub fn parse_target_triple( Some(target) if target.ends_with(".json") => { let path = Path::new(&target); TargetTriple::from_path(path).unwrap_or_else(|_| { - early_error(error_format, &format!("target file {path:?} does not exist")) + early_error(error_format, format!("target file {path:?} does not exist")) }) } Some(target) => TargetTriple::TargetTriple(target), @@ -2028,7 +2027,7 @@ fn parse_opt_level( arg => { early_error( error_format, - &format!( + format!( "optimization level needs to be \ between 0-3, s or z (instead was `{arg}`)" ), @@ -2059,7 +2058,7 @@ pub(crate) fn parse_assert_incr_state( Some(s) if s.as_str() == "loaded" => Some(IncrementalStateAssertion::Loaded), Some(s) if s.as_str() == "not-loaded" => Some(IncrementalStateAssertion::NotLoaded), Some(s) => { - early_error(error_format, &format!("unexpected incremental state assertion value: {s}")) + early_error(error_format, format!("unexpected incremental state assertion value: {s}")) } None => None, } @@ -2086,13 +2085,13 @@ fn parse_native_lib_kind( } else { ", the `-Z unstable-options` flag must also be passed to use it" }; - early_error(error_format, &format!("library kind `link-arg` is unstable{why}")) + early_error(error_format, format!("library kind `link-arg` is unstable{why}")) } NativeLibKind::LinkArg } _ => early_error( error_format, - &format!( + format!( "unknown library kind `{kind}`, expected one of: static, dylib, framework, link-arg" ), ), @@ -2127,16 +2126,13 @@ fn parse_native_lib_modifiers( } else { ", the `-Z unstable-options` flag must also be passed to use it" }; - early_error( - error_format, - &format!("linking modifier `{modifier}` is unstable{why}"), - ) + early_error(error_format, format!("linking modifier `{modifier}` is unstable{why}")) } }; let assign_modifier = |dst: &mut Option| { if dst.is_some() { let msg = format!("multiple `{modifier}` modifiers in a single `-l` option"); - early_error(error_format, &msg) + early_error(error_format, msg) } else { *dst = Some(value); } @@ -2173,7 +2169,7 @@ fn parse_native_lib_modifiers( // string, like `modifiers = ""`. _ => early_error( error_format, - &format!( + format!( "unknown linking modifier `{modifier}`, expected one \ of: bundle, verbatim, whole-archive, as-needed" ), @@ -2303,7 +2299,7 @@ pub fn parse_externs( } "nounused" => nounused_dep = true, "force" => force = true, - _ => early_error(error_format, &format!("unknown --extern option `{opt}`")), + _ => early_error(error_format, format!("unknown --extern option `{opt}`")), } } } @@ -2369,7 +2365,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { let unparsed_crate_types = matches.opt_strs("crate-type"); let crate_types = parse_crate_types_from_list(unparsed_crate_types) - .unwrap_or_else(|e| early_error(error_format, &e)); + .unwrap_or_else(|e| early_error(error_format, e)); let mut unstable_opts = UnstableOptions::build(matches, error_format); let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format); @@ -2597,7 +2593,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { }; let working_dir = std::env::current_dir().unwrap_or_else(|e| { - early_error(error_format, &format!("Current directory is invalid: {e}")); + early_error(error_format, format!("Current directory is invalid: {e}")); }); let remap = FilePathMapping::new(remap_path_prefix.clone()); @@ -2669,7 +2665,7 @@ fn parse_pretty(unstable_opts: &UnstableOptions, efmt: ErrorOutputType) -> Optio "mir-cfg" => MirCFG, name => early_error( efmt, - &format!( + format!( "argument to `unpretty` must be one of `normal`, `identified`, \ `expanded`, `expanded,identified`, `expanded,hygiene`, \ `ast-tree`, `ast-tree,expanded`, `hir`, `hir,identified`, \ @@ -2747,7 +2743,7 @@ pub mod nightly_options { if opt.name != "Z" && !has_z_unstable_option { early_error( ErrorOutputType::default(), - &format!( + format!( "the `-Z unstable-options` flag must also be passed to enable \ the flag `{}`", opt.name @@ -2760,11 +2756,10 @@ pub mod nightly_options { match opt.stability { OptionStability::Unstable => { let msg = format!( - "the option `{}` is only accepted on the \ - nightly compiler", + "the option `{}` is only accepted on the nightly compiler", opt.name ); - early_error(ErrorOutputType::default(), &msg); + early_error(ErrorOutputType::default(), msg); } OptionStability::Stable => {} } diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 5976b9aa3e74a..2c4c4a7a6ce29 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -329,21 +329,21 @@ fn build_options( match value { None => early_error( error_format, - &format!( + format!( "{0} option `{1}` requires {2} ({3} {1}=)", outputname, key, type_desc, prefix ), ), Some(value) => early_error( error_format, - &format!( + format!( "incorrect value `{value}` for {outputname} option `{key}` - {type_desc} was expected" ), ), } } } - None => early_error(error_format, &format!("unknown {outputname} option: `{key}`")), + None => early_error(error_format, format!("unknown {outputname} option: `{key}`")), } } return op; diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 5cc9c62617dd5..7b396dde91ba1 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -289,7 +289,7 @@ impl ParseSess { lint: &'static Lint, span: impl Into, node_id: NodeId, - msg: &str, + msg: impl Into, ) { self.buffered_lints.with_lock(|buffered_lints| { buffered_lints.push(BufferedEarlyLint { @@ -307,7 +307,7 @@ impl ParseSess { lint: &'static Lint, span: impl Into, node_id: NodeId, - msg: &str, + msg: impl Into, diagnostic: BuiltinLintDiagnostics, ) { self.buffered_lints.with_lock(|buffered_lints| { diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 151325fcb08a5..4abe734d372d4 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -1386,10 +1386,10 @@ pub fn build_session( let target_cfg = config::build_target_config(&sopts, target_override, &sysroot); let host_triple = TargetTriple::from_triple(config::host_triple()); let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| { - early_error(sopts.error_format, &format!("Error loading host specification: {e}")) + early_error(sopts.error_format, format!("Error loading host specification: {e}")) }); for warning in target_warnings.warning_messages() { - early_warn(sopts.error_format, &warning) + early_warn(sopts.error_format, warning) } let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader)); @@ -1431,7 +1431,7 @@ pub fn build_session( match profiler { Ok(profiler) => Some(Arc::new(profiler)), Err(e) => { - early_warn(sopts.error_format, &format!("failed to create profiler: {e}")); + early_warn(sopts.error_format, format!("failed to create profiler: {e}")); None } } @@ -1727,18 +1727,21 @@ fn early_error_handler(output: config::ErrorOutputType) -> rustc_errors::Handler #[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::diagnostic_outside_of_impl)] -pub fn early_error_no_abort(output: config::ErrorOutputType, msg: &str) -> ErrorGuaranteed { +pub fn early_error_no_abort( + output: config::ErrorOutputType, + msg: impl Into, +) -> ErrorGuaranteed { early_error_handler(output).struct_err(msg).emit() } #[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::diagnostic_outside_of_impl)] -pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! { +pub fn early_error(output: config::ErrorOutputType, msg: impl Into) -> ! { early_error_handler(output).struct_fatal(msg).emit() } #[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::diagnostic_outside_of_impl)] -pub fn early_warn(output: config::ErrorOutputType, msg: &str) { +pub fn early_warn(output: config::ErrorOutputType, msg: impl Into) { early_error_handler(output).struct_warn(msg).emit() } diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 8e684b7ac239b..445ab99b28fb3 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -2260,7 +2260,7 @@ fn confirm_param_env_candidate<'cx, 'tcx>( obligation, poly_cache_entry, e, ); debug!("confirm_param_env_candidate: {}", msg); - let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg); + let err = infcx.tcx.ty_error_with_message(obligation.cause.span, msg); Progress { term: err.into(), obligations: vec![] } } } diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 4b0aee9c3add9..c9957e8e39c8f 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -773,7 +773,7 @@ impl<'tcx> ExtraInfo<'tcx> { ExtraInfo { def_id, sp, tcx } } - fn error_invalid_codeblock_attr(&self, msg: &str, help: &str) { + fn error_invalid_codeblock_attr(&self, msg: String, help: &str) { if let Some(def_id) = self.def_id.as_local() { self.tcx.struct_span_lint_hir( crate::lint::INVALID_CODEBLOCK_ATTRIBUTES, @@ -948,7 +948,7 @@ impl LangString { } { if let Some(extra) = extra { extra.error_invalid_codeblock_attr( - &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag), + format!("unknown attribute `{}`. Did you mean `{}`?", x, flag), help, ); } diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 5460bce21a512..0a56916edcd9c 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -192,11 +192,11 @@ fn init_logging() { Ok("auto") | Err(VarError::NotPresent) => io::stdout().is_terminal(), Ok(value) => early_error( ErrorOutputType::default(), - &format!("invalid log color value '{}': expected one of always, never, or auto", value), + format!("invalid log color value '{}': expected one of always, never, or auto", value), ), Err(VarError::NotUnicode(value)) => early_error( ErrorOutputType::default(), - &format!( + format!( "invalid log color value '{}': expected one of always, never, or auto", value.to_string_lossy() ), @@ -228,7 +228,7 @@ fn get_args() -> Option> { .map_err(|arg| { early_warn( ErrorOutputType::default(), - &format!("Argument {} is not valid Unicode: {:?}", i, arg), + format!("Argument {} is not valid Unicode: {:?}", i, arg), ); }) .ok() @@ -721,7 +721,7 @@ fn main_args(at_args: &[String]) -> MainResult { let matches = match options.parse(&args[1..]) { Ok(m) => m, Err(err) => { - early_error(ErrorOutputType::default(), &err.to_string()); + early_error(ErrorOutputType::default(), err.to_string()); } }; diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index a885ff0ca5e58..9381b3e0567a5 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -8,7 +8,7 @@ use rustc_data_structures::{ fx::{FxHashMap, FxHashSet}, intern::Interned, }; -use rustc_errors::{Applicability, Diagnostic}; +use rustc_errors::{Applicability, Diagnostic, DiagnosticMessage}; use rustc_hir::def::Namespace::*; use rustc_hir::def::{DefKind, Namespace, PerNS}; use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; @@ -24,6 +24,7 @@ use rustc_span::BytePos; use smallvec::{smallvec, SmallVec}; use std::borrow::Cow; +use std::fmt::Display; use std::mem; use std::ops::Range; @@ -841,7 +842,7 @@ impl PreprocessingError { match self { PreprocessingError::MultipleAnchors => report_multiple_anchors(cx, diag_info), PreprocessingError::Disambiguator(range, msg) => { - disambiguator_error(cx, diag_info, range.clone(), msg) + disambiguator_error(cx, diag_info, range.clone(), msg.as_str()) } PreprocessingError::MalformedGenerics(err, path_str) => { report_malformed_generics(cx, diag_info, *err, path_str) @@ -1185,7 +1186,7 @@ impl LinkCollector<'_, '_> { } suggest_disambiguator(resolved, diag, path_str, &ori_link.link, sp); }; - report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, diag_info, callback); + report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, callback); } fn report_rawptr_assoc_feature_gate(&self, dox: &str, ori_link: &Range, item: &Item) { @@ -1581,7 +1582,7 @@ impl Suggestion { fn report_diagnostic( tcx: TyCtxt<'_>, lint: &'static Lint, - msg: &str, + msg: impl Into + Display, DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>, decorate: impl FnOnce(&mut Diagnostic, Option), ) { @@ -1649,7 +1650,7 @@ fn resolution_failure( report_diagnostic( tcx, BROKEN_INTRA_DOC_LINKS, - &format!("unresolved link to `{}`", path_str), + format!("unresolved link to `{}`", path_str), &diag_info, |diag, sp| { let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),); @@ -1865,20 +1866,20 @@ fn resolution_failure( fn report_multiple_anchors(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) { let msg = format!("`{}` contains multiple anchors", diag_info.ori_link); - anchor_failure(cx, diag_info, &msg, 1) + anchor_failure(cx, diag_info, msg, 1) } fn report_anchor_conflict(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, def_id: DefId) { let (link, kind) = (diag_info.ori_link, Res::from_def_id(cx.tcx, def_id).descr()); let msg = format!("`{link}` contains an anchor, but links to {kind}s are already anchored"); - anchor_failure(cx, diag_info, &msg, 0) + anchor_failure(cx, diag_info, msg, 0) } /// Report an anchor failure. fn anchor_failure( cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, - msg: &str, + msg: String, anchor_idx: usize, ) { report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, sp| { @@ -1898,7 +1899,7 @@ fn disambiguator_error( cx: &DocContext<'_>, mut diag_info: DiagnosticInfo<'_>, disambiguator_range: Range, - msg: &str, + msg: impl Into + Display, ) { diag_info.link_range = disambiguator_range; report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| { @@ -1919,7 +1920,7 @@ fn report_malformed_generics( report_diagnostic( cx.tcx, BROKEN_INTRA_DOC_LINKS, - &format!("unresolved link to `{}`", path_str), + format!("unresolved link to `{}`", path_str), &diag_info, |diag, sp| { let note = match err { @@ -1994,7 +1995,7 @@ fn ambiguity_error( } } - report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| { + report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, |diag, sp| { if let Some(sp) = sp { diag.span_label(sp, "ambiguous link"); } else { @@ -2046,7 +2047,7 @@ fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: let msg = format!("public documentation for `{}` links to private item `{}`", item_name, path_str); - report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| { + report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, msg, diag_info, |diag, sp| { if let Some(sp) = sp { diag.span_label(sp, "this item is private"); } From 67c0cfe8b5578708124d9585d79ddc331758121d Mon Sep 17 00:00:00 2001 From: Amanieu d'Antras Date: Wed, 17 May 2023 13:16:28 +0200 Subject: [PATCH 8/8] Remove libs message about ACPs from triagebot The libs team is currently reworking the ACP process and we don't want to encourage people to submit new ACPs in the meantime. --- triagebot.toml | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/triagebot.toml b/triagebot.toml index a5152434d89e6..046d732bd4257 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -371,31 +371,6 @@ cc = ["@GuillaumeGomez"] message = "Some changes might have occurred in exhaustiveness checking" cc = ["@Nadrieril"] -[mentions."library"] -message = """ -Hey! It looks like you've submitted a new PR for the library teams! - -If this PR contains changes to any `rust-lang/rust` public library APIs then \ -please comment with `@rustbot label +T-libs-api -T-libs` to tag it \ -appropriately. If this PR contains changes to any unstable APIs please edit \ -the PR description to add a link to the relevant [API Change \ -Proposal](https://std-dev-guide.rust-lang.org/feature-lifecycle/api-change-proposals.html) \ -or [create one](/~https://github.com/rust-lang/libs-team/issues/new?assignees=&labels=api-change-proposal%2C+T-libs-api&template=api-change-proposal.md&title=%28My+API+Change+Proposal%29) \ -if you haven't already. If you're unsure where your change falls no worries, \ -just leave it as is and the reviewer will take a look and make a decision to \ -forward on if necessary. - -Examples of `T-libs-api` changes: - -* Stabilizing library features -* Introducing insta-stable changes such as new implementations of existing \ - stable traits on existing stable types -* Introducing new or changing existing unstable library APIs (excluding \ - permanently unstable features / features without a tracking issue) -* Changing public documentation in ways that create new stability guarantees -* Changing observable runtime behavior of library APIs -""" - [mentions."src/librustdoc/clean/types.rs"] cc = ["@camelid"]