From 0cf0f9fc74f7bd1c9f160cc1dbd67c92a9436704 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sun, 22 Jun 2025 20:27:27 +1000 Subject: Use `join_with_double_colon` in `write_shared.rs`. For consistency. Also, it's faster because `join_with_double_colon` does a better job estimating the allocation size than `join` from `itertools`. --- src/librustdoc/html/render/write_shared.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/librustdoc/html/render/write_shared.rs b/src/librustdoc/html/render/write_shared.rs index fb2b45802a6..42007c81433 100644 --- a/src/librustdoc/html/render/write_shared.rs +++ b/src/librustdoc/html/render/write_shared.rs @@ -25,7 +25,6 @@ use std::str::FromStr; use std::{fmt, fs}; use indexmap::IndexMap; -use itertools::Itertools; use regex::Regex; use rustc_data_structures::flock; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; @@ -44,6 +43,7 @@ use crate::docfs::PathError; use crate::error::Error; use crate::formats::Impl; use crate::formats::item_type::ItemType; +use crate::html::format::join_with_double_colon; use crate::html::layout; use crate::html::render::ordered_json::{EscapedJson, OrderedJson}; use crate::html::render::search_index::{SerializedSearchIndex, build_index}; @@ -612,7 +612,7 @@ impl TypeAliasPart { for &(type_alias_fqp, type_alias_item) in type_aliases { cx.id_map.borrow_mut().clear(); cx.deref_id_map.borrow_mut().clear(); - let type_alias_fqp = (*type_alias_fqp).iter().join("::"); + let type_alias_fqp = join_with_double_colon(&type_alias_fqp); if let Some(ret) = &mut ret { ret.aliases.push(type_alias_fqp); } else { -- cgit 1.4.1-3-g733a5 From 50061f3b11f51d7a6e3acd8ce793a1f17f99b597 Mon Sep 17 00:00:00 2001 From: dianne Date: Fri, 4 Jul 2025 21:17:40 -0700 Subject: always check for mixed deref pattern and normal constructors This makes it work for box patterns and in rust-analyzer. --- compiler/rustc_pattern_analysis/src/checks.rs | 50 ++++++++++++++++ compiler/rustc_pattern_analysis/src/lib.rs | 10 ++++ compiler/rustc_pattern_analysis/src/rustc.rs | 67 +++++----------------- compiler/rustc_pattern_analysis/src/usefulness.rs | 5 +- .../rustc_pattern_analysis/tests/common/mod.rs | 9 +++ .../src/diagnostics/match_check/pat_analysis.rs | 8 +++ .../ui/pattern/box-pattern-constructor-mismatch.rs | 11 ++++ .../box-pattern-constructor-mismatch.stderr | 10 ++++ 8 files changed, 117 insertions(+), 53 deletions(-) create mode 100644 compiler/rustc_pattern_analysis/src/checks.rs create mode 100644 tests/ui/pattern/box-pattern-constructor-mismatch.rs create mode 100644 tests/ui/pattern/box-pattern-constructor-mismatch.stderr (limited to 'src') diff --git a/compiler/rustc_pattern_analysis/src/checks.rs b/compiler/rustc_pattern_analysis/src/checks.rs new file mode 100644 index 00000000000..88ccaa1e0e5 --- /dev/null +++ b/compiler/rustc_pattern_analysis/src/checks.rs @@ -0,0 +1,50 @@ +//! Contains checks that must be run to validate matches before performing usefulness analysis. + +use crate::constructor::Constructor::*; +use crate::pat_column::PatternColumn; +use crate::{MatchArm, PatCx}; + +/// Validate that deref patterns and normal constructors aren't used to match on the same place. +pub(crate) fn detect_mixed_deref_pat_ctors<'p, Cx: PatCx>( + cx: &Cx, + arms: &[MatchArm<'p, Cx>], +) -> Result<(), Cx::Error> { + let pat_column = PatternColumn::new(arms); + detect_mixed_deref_pat_ctors_inner(cx, &pat_column) +} + +fn detect_mixed_deref_pat_ctors_inner<'p, Cx: PatCx>( + cx: &Cx, + column: &PatternColumn<'p, Cx>, +) -> Result<(), Cx::Error> { + let Some(ty) = column.head_ty() else { + return Ok(()); + }; + + // Check for a mix of deref patterns and normal constructors. + let mut deref_pat = None; + let mut normal_pat = None; + for pat in column.iter() { + match pat.ctor() { + // The analysis can handle mixing deref patterns with wildcards and opaque patterns. + Wildcard | Opaque(_) => {} + DerefPattern(_) => deref_pat = Some(pat), + // Nothing else can be compared to deref patterns in `Constructor::is_covered_by`. + _ => normal_pat = Some(pat), + } + } + if let Some(deref_pat) = deref_pat + && let Some(normal_pat) = normal_pat + { + return Err(cx.report_mixed_deref_pat_ctors(deref_pat, normal_pat)); + } + + // Specialize and recurse into the patterns' fields. + let set = column.analyze_ctors(cx, &ty)?; + for ctor in set.present { + for specialized_column in column.specialize(cx, &ty, &ctor).iter() { + detect_mixed_deref_pat_ctors_inner(cx, specialized_column)?; + } + } + Ok(()) +} diff --git a/compiler/rustc_pattern_analysis/src/lib.rs b/compiler/rustc_pattern_analysis/src/lib.rs index 2b85d7b26ce..129fd38725c 100644 --- a/compiler/rustc_pattern_analysis/src/lib.rs +++ b/compiler/rustc_pattern_analysis/src/lib.rs @@ -8,6 +8,7 @@ #![allow(unused_crate_dependencies)] // tidy-alphabetical-end +pub(crate) mod checks; pub mod constructor; #[cfg(feature = "rustc")] pub mod errors; @@ -107,6 +108,15 @@ pub trait PatCx: Sized + fmt::Debug { _gapped_with: &[&DeconstructedPat], ) { } + + /// The current implementation of deref patterns requires that they can't match on the same + /// place as a normal constructor. Since this isn't caught by type-checking, we check it in the + /// `PatCx` before running the analysis. This reports an error if the check fails. + fn report_mixed_deref_pat_ctors( + &self, + deref_pat: &DeconstructedPat, + normal_pat: &DeconstructedPat, + ) -> Self::Error; } /// The arm of a match expression. diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index e53cebc59ba..e9795126db6 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -1027,6 +1027,21 @@ impl<'p, 'tcx: 'p> PatCx for RustcPatCtxt<'p, 'tcx> { ); } } + + fn report_mixed_deref_pat_ctors( + &self, + deref_pat: &crate::pat::DeconstructedPat, + normal_pat: &crate::pat::DeconstructedPat, + ) -> Self::Error { + let deref_pattern_label = deref_pat.data().span; + let normal_constructor_label = normal_pat.data().span; + self.tcx.dcx().emit_err(errors::MixedDerefPatternConstructors { + spans: vec![deref_pattern_label, normal_constructor_label], + smart_pointer_ty: deref_pat.ty().inner(), + deref_pattern_label, + normal_constructor_label, + }) + } } /// Recursively expand this pattern into its subpatterns. Only useful for or-patterns. @@ -1055,13 +1070,6 @@ pub fn analyze_match<'p, 'tcx>( ) -> Result, ErrorGuaranteed> { let scrut_ty = tycx.reveal_opaque_ty(scrut_ty); - // The analysis doesn't support deref patterns mixed with normal constructors; error if present. - // FIXME(deref_patterns): This only needs to run when a deref pattern was found during lowering. - if tycx.tcx.features().deref_patterns() { - let pat_column = PatternColumn::new(arms); - detect_mixed_deref_pat_ctors(tycx, &pat_column)?; - } - let scrut_validity = PlaceValidity::from_bool(tycx.known_valid_scrutinee); let report = compute_match_usefulness( tycx, @@ -1080,48 +1088,3 @@ pub fn analyze_match<'p, 'tcx>( Ok(report) } - -// FIXME(deref_patterns): Currently it's the responsibility of the frontend (rustc or rust-analyzer) -// to ensure that deref patterns don't appear in the same column as normal constructors. Deref -// patterns aren't currently implemented in rust-analyzer, but should they be, the columnwise check -// here could be made generic and shared between frontends. -fn detect_mixed_deref_pat_ctors<'p, 'tcx>( - cx: &RustcPatCtxt<'p, 'tcx>, - column: &PatternColumn<'p, RustcPatCtxt<'p, 'tcx>>, -) -> Result<(), ErrorGuaranteed> { - let Some(&ty) = column.head_ty() else { - return Ok(()); - }; - - // Check for a mix of deref patterns and normal constructors. - let mut normal_ctor_span = None; - let mut deref_pat_span = None; - for pat in column.iter() { - match pat.ctor() { - // The analysis can handle mixing deref patterns with wildcards and opaque patterns. - Wildcard | Opaque(_) => {} - DerefPattern(_) => deref_pat_span = Some(pat.data().span), - // Nothing else can be compared to deref patterns in `Constructor::is_covered_by`. - _ => normal_ctor_span = Some(pat.data().span), - } - } - if let Some(normal_constructor_label) = normal_ctor_span - && let Some(deref_pattern_label) = deref_pat_span - { - return Err(cx.tcx.dcx().emit_err(errors::MixedDerefPatternConstructors { - spans: vec![deref_pattern_label, normal_constructor_label], - smart_pointer_ty: ty.inner(), - deref_pattern_label, - normal_constructor_label, - })); - } - - // Specialize and recurse into the patterns' fields. - let set = column.analyze_ctors(cx, &ty)?; - for ctor in set.present { - for specialized_column in column.specialize(cx, &ty, &ctor).iter() { - detect_mixed_deref_pat_ctors(cx, specialized_column)?; - } - } - Ok(()) -} diff --git a/compiler/rustc_pattern_analysis/src/usefulness.rs b/compiler/rustc_pattern_analysis/src/usefulness.rs index c348cd508f9..fb94b4afebb 100644 --- a/compiler/rustc_pattern_analysis/src/usefulness.rs +++ b/compiler/rustc_pattern_analysis/src/usefulness.rs @@ -720,7 +720,7 @@ use tracing::{debug, instrument}; use self::PlaceValidity::*; use crate::constructor::{Constructor, ConstructorSet, IntRange}; use crate::pat::{DeconstructedPat, PatId, PatOrWild, WitnessPat}; -use crate::{MatchArm, PatCx, PrivateUninhabitedField}; +use crate::{MatchArm, PatCx, PrivateUninhabitedField, checks}; #[cfg(not(feature = "rustc"))] pub fn ensure_sufficient_stack(f: impl FnOnce() -> R) -> R { f() @@ -1836,6 +1836,9 @@ pub fn compute_match_usefulness<'p, Cx: PatCx>( scrut_validity: PlaceValidity, complexity_limit: usize, ) -> Result, Cx::Error> { + // The analysis doesn't support deref patterns mixed with normal constructors; error if present. + checks::detect_mixed_deref_pat_ctors(tycx, arms)?; + let mut cx = UsefulnessCtxt { tycx, branch_usefulness: FxHashMap::default(), diff --git a/compiler/rustc_pattern_analysis/tests/common/mod.rs b/compiler/rustc_pattern_analysis/tests/common/mod.rs index 8980b644f59..0b939ef7816 100644 --- a/compiler/rustc_pattern_analysis/tests/common/mod.rs +++ b/compiler/rustc_pattern_analysis/tests/common/mod.rs @@ -1,6 +1,7 @@ use rustc_pattern_analysis::constructor::{ Constructor, ConstructorSet, IntRange, MaybeInfiniteInt, RangeEnd, VariantVisibility, }; +use rustc_pattern_analysis::pat::DeconstructedPat; use rustc_pattern_analysis::usefulness::{PlaceValidity, UsefulnessReport}; use rustc_pattern_analysis::{MatchArm, PatCx, PrivateUninhabitedField}; @@ -184,6 +185,14 @@ impl PatCx for Cx { fn complexity_exceeded(&self) -> Result<(), Self::Error> { Err(()) } + + fn report_mixed_deref_pat_ctors( + &self, + _deref_pat: &DeconstructedPat, + _normal_pat: &DeconstructedPat, + ) -> Self::Error { + panic!("`rustc_pattern_analysis::tests` currently doesn't test deref pattern errors") + } } /// Construct a single pattern; see `pats!()`. diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs index 7cf22c64d0f..2e408b1fac9 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs @@ -527,6 +527,14 @@ impl PatCx for MatchCheckCtx<'_> { fn complexity_exceeded(&self) -> Result<(), Self::Error> { Err(()) } + + fn report_mixed_deref_pat_ctors( + &self, + _deref_pat: &DeconstructedPat<'_>, + _normal_pat: &DeconstructedPat<'_>, + ) { + // FIXME(deref_patterns): This could report an error comparable to the one in rustc. + } } impl fmt::Debug for MatchCheckCtx<'_> { diff --git a/tests/ui/pattern/box-pattern-constructor-mismatch.rs b/tests/ui/pattern/box-pattern-constructor-mismatch.rs new file mode 100644 index 00000000000..8f0a19d7407 --- /dev/null +++ b/tests/ui/pattern/box-pattern-constructor-mismatch.rs @@ -0,0 +1,11 @@ +//! Test that `box _` patterns and `Box { .. }` patterns can't be used to match on the same place. +//! This is required for the current implementation of exhaustiveness analysis for deref patterns. + +#![feature(box_patterns)] + +fn main() { + match Box::new(0) { + box _ => {} //~ ERROR mix of deref patterns and normal constructors + Box { .. } => {} + } +} diff --git a/tests/ui/pattern/box-pattern-constructor-mismatch.stderr b/tests/ui/pattern/box-pattern-constructor-mismatch.stderr new file mode 100644 index 00000000000..489eefe0d21 --- /dev/null +++ b/tests/ui/pattern/box-pattern-constructor-mismatch.stderr @@ -0,0 +1,10 @@ +error: mix of deref patterns and normal constructors + --> $DIR/box-pattern-constructor-mismatch.rs:8:9 + | +LL | box _ => {} + | ^^^^^ matches on the result of dereferencing `Box` +LL | Box { .. } => {} + | ^^^^^^^^^^ matches directly on `Box` + +error: aborting due to 1 previous error + -- cgit 1.4.1-3-g733a5 From 7ec8c89c1501881d3435556148cc27e4cefa43b8 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 7 Jul 2025 10:42:08 -0700 Subject: Update intro blurb in `wasm32-wasip1` docs I was reading over this documentation in light of the effort to enlist more maintainers for Tier 2 targets and figured it was time for a refresh of this documentation now that historical renames/etc have all become a thing of the past. No new major changes to this documentation, mostly just wanted to update it and reflect the modern status quo for this target. --- .../rustc/src/platform-support/wasm32-wasip1.md | 48 +++++++++++----------- 1 file changed, 23 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/doc/rustc/src/platform-support/wasm32-wasip1.md b/src/doc/rustc/src/platform-support/wasm32-wasip1.md index 4f065a554cf..1e7447698bc 100644 --- a/src/doc/rustc/src/platform-support/wasm32-wasip1.md +++ b/src/doc/rustc/src/platform-support/wasm32-wasip1.md @@ -4,37 +4,35 @@ The `wasm32-wasip1` target is a WebAssembly compilation target which assumes that the [WASIp1] (aka "WASI preview1") set of "syscalls" are available -for use in the standard library. Historically this target in the Rust compiler -was one of the first for WebAssembly where Rust and C code are explicitly -intended to interoperate as well. - -There's a bit of history to the target and current development which is also -worth explaining before going much further. Historically this target was -originally called `wasm32-wasi` in both rustc and Clang. This was first added -to Rust in 2019. In the intervening years leading up to 2024 the WASI standard -continued to be developed and was eventually "rebased" on top of the [Component -Model]. This was a large change to the WASI specification and was released as -0.2.0 ("WASIp2" colloquially) in January 2024. The previous target's name in -rustc, `wasm32-wasi`, was then renamed to `wasm32-wasip1`, to avoid -confusion with this new target to be added to rustc as `wasm32-wasip2`. -Some more context can be found in these MCPs: - -* [Rename wasm32-wasi target to wasm32-wasip1](https://github.com/rust-lang/compiler-team/issues/607) -* [Smooth the renaming transition of wasm32-wasi](https://github.com/rust-lang/compiler-team/issues/695) - -At this point the `wasm32-wasip1` target is intended for historical -compatibility with the first version of the WASI standard. As of now (January -2024) the 0.2.0 target of WASI ("WASIp2") is relatively new. The state of -WASI will likely change in few years after which point this documentation will -probably receive another update. - -[WASI Preview1]: https://github.com/WebAssembly/WASI/tree/main/legacy/preview1 +for use in the standard library. This target explicitly supports interop with +non-Rust code such as C and C++. + +The [WASIp1] set of syscalls is standard insofar as it was written down once by +a set of folks and has not changed since then. Additionally the [WASIp1] +syscalls have been adapted and adopted into a number of runtimes and embeddings. +It is not standard in the sense that there are no formal semantics for each +syscall and APIs are no longer receiving any maintenance (e.g. no new APIs, no +new documentation, etc). After [WASIp1] was originally developed in 2019 the +WASI standard effort has since been "rebased" on top of the [Component Model]. +This was a large change to the WASI specification and was released as 0.2.0 +("WASIp2" colloquially) in January 2024. Current standardization efforts are +focused on the Component Model-based definition of WASI. At this point the +`wasm32-wasip1` Rust target is intended for historical compatibility with +[WASIp1] set of syscalls. + +[WASIp1]: https://github.com/WebAssembly/WASI/tree/main/legacy/preview1 [Component Model]: https://github.com/webassembly/component-model Today the `wasm32-wasip1` target will generate core WebAssembly modules which will import functions from the `wasi_snapshot_preview1` module for OS-related functionality (e.g. printing). +> **Note**: Prior to March 2024 this target was known as `wasm32-wasi` with some +> historical context found in old MCPs: +> +> * [Rename wasm32-wasi target to wasm32-wasip1](https://github.com/rust-lang/compiler-team/issues/607) +> * [Smooth the renaming transition of wasm32-wasi](https://github.com/rust-lang/compiler-team/issues/695) + ## Target maintainers When this target was added to the compiler platform-specific documentation here -- cgit 1.4.1-3-g733a5 From e2891c0fb9060f80e6aa24e0dc0a9c43b0861b8f Mon Sep 17 00:00:00 2001 From: Aleksey Kliger Date: Mon, 7 Jul 2025 14:54:50 -0400 Subject: configure.py: Write last key in each section The loop that writes the keys in each section of bootstrap.toml accumulates all the commented lines before a given key and emits them when it reaches the next key in the section. This ends up dropping lines accumulated for the last key --- src/bootstrap/configure.py | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/bootstrap/configure.py b/src/bootstrap/configure.py index c077555b906..bec7a1c41b4 100755 --- a/src/bootstrap/configure.py +++ b/src/bootstrap/configure.py @@ -752,6 +752,10 @@ def write_uncommented(target, f): is_comment = True continue is_comment = is_comment and line.startswith("#") + # Write the last accumulated block + if len(block) > 0 and not is_comment: + for ln in block: + f.write(ln + "\n") return f -- cgit 1.4.1-3-g733a5 From b6d21308672c9a0aa5c73beeb1d528aab3d347ed Mon Sep 17 00:00:00 2001 From: Aleksey Kliger Date: Mon, 7 Jul 2025 15:45:18 -0400 Subject: Add docstring --- src/bootstrap/configure.py | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/bootstrap/configure.py b/src/bootstrap/configure.py index bec7a1c41b4..94e02f942dc 100755 --- a/src/bootstrap/configure.py +++ b/src/bootstrap/configure.py @@ -739,6 +739,10 @@ def configure_file(sections, top_level_keys, targets, config): def write_uncommented(target, f): + """Writes each block in 'target' that is not composed entirely of comments to 'f'. + + A block is a sequence of non-empty lines separated by empty lines. + """ block = [] is_comment = True -- cgit 1.4.1-3-g733a5 From c3301503b97cd6b768a944661b81a92994e9db00 Mon Sep 17 00:00:00 2001 From: Esteban Küber Date: Sat, 21 Dec 2024 20:25:43 +0000 Subject: Make `Default` const and add some `const Default` impls Full list of `impl const Default` types: - () - bool - char - Cell - std::ascii::Char - usize - u8 - u16 - u32 - u64 - u128 - i8 - i16 - i32 - i64 - i128 - f16 - f32 - f64 - f128 - std::marker::PhantomData - Option - std::iter::Empty - std::ptr::Alignment - &[T] - &mut [T] - &str - &mut str - String - Vec --- library/alloc/src/lib.rs | 2 + library/alloc/src/string.rs | 3 +- library/alloc/src/vec/mod.rs | 3 +- library/core/src/cell.rs | 12 +++-- library/core/src/default.rs | 5 +- library/core/src/iter/sources/empty.rs | 3 +- library/core/src/marker.rs | 3 +- library/core/src/option.rs | 3 +- library/core/src/ptr/alignment.rs | 3 +- library/core/src/slice/mod.rs | 6 ++- library/core/src/str/mod.rs | 6 ++- src/tools/clippy/tests/ui/or_fun_call.fixed | 4 +- src/tools/clippy/tests/ui/or_fun_call.rs | 2 +- src/tools/clippy/tests/ui/or_fun_call.stderr | 8 +-- tests/ui/consts/rustc-impl-const-stability.rs | 8 +-- tests/ui/consts/rustc-impl-const-stability.stderr | 6 +-- .../lint/dead-code/unused-struct-derive-default.rs | 4 +- tests/ui/specialization/const_trait_impl.rs | 8 +-- tests/ui/specialization/const_trait_impl.stderr | 60 +++++++++++----------- tests/ui/traits/const-traits/const-traits-alloc.rs | 9 ++++ tests/ui/traits/const-traits/const-traits-core.rs | 46 +++++++++++++++++ .../const_derives/derive-const-gate.rs | 5 +- .../const_derives/derive-const-gate.stderr | 21 +++++--- .../const_derives/derive-const-non-const-type.rs | 8 +-- .../derive-const-non-const-type.stderr | 18 +++---- .../const-traits/const_derives/derive-const-use.rs | 2 +- .../const_derives/derive-const-use.stderr | 57 +------------------- .../traits/const-traits/std-impl-gate.gated.stderr | 18 ------- tests/ui/traits/const-traits/std-impl-gate.rs | 7 +-- .../traits/const-traits/std-impl-gate.stock.stderr | 20 ++++++-- 30 files changed, 192 insertions(+), 168 deletions(-) create mode 100644 tests/ui/traits/const-traits/const-traits-alloc.rs create mode 100644 tests/ui/traits/const-traits/const-traits-core.rs delete mode 100644 tests/ui/traits/const-traits/std-impl-gate.gated.stderr (limited to 'src') diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index 4290bb7a8a9..4ad65e678c3 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -107,8 +107,10 @@ #![feature(char_max_len)] #![feature(clone_to_uninit)] #![feature(coerce_unsized)] +#![feature(const_default)] #![feature(const_eval_select)] #![feature(const_heap)] +#![feature(const_trait_impl)] #![feature(core_intrinsics)] #![feature(deprecated_suggestion)] #![feature(deref_pure_trait)] diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 5f69f699867..84b82423202 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -2611,7 +2611,8 @@ impl_eq! { Cow<'a, str>, &'b str } impl_eq! { Cow<'a, str>, String } #[stable(feature = "rust1", since = "1.0.0")] -impl Default for String { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for String { /// Creates an empty `String`. #[inline] fn default() -> String { diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index c8341750f4d..9dac58bac4f 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -3895,7 +3895,8 @@ unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec { } #[stable(feature = "rust1", since = "1.0.0")] -impl Default for Vec { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for Vec { /// Creates an empty `Vec`. /// /// The vector will not allocate until elements are pushed onto it. diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index dfed8a00b7d..f7ea1f37a39 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -333,7 +333,8 @@ impl Clone for Cell { } #[stable(feature = "rust1", since = "1.0.0")] -impl Default for Cell { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for Cell { /// Creates a `Cell`, with the `Default` value for T. #[inline] fn default() -> Cell { @@ -1323,7 +1324,8 @@ impl Clone for RefCell { } #[stable(feature = "rust1", since = "1.0.0")] -impl Default for RefCell { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for RefCell { /// Creates a `RefCell`, with the `Default` value for T. #[inline] fn default() -> RefCell { @@ -2330,7 +2332,8 @@ impl UnsafeCell { } #[stable(feature = "unsafe_cell_default", since = "1.10.0")] -impl Default for UnsafeCell { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for UnsafeCell { /// Creates an `UnsafeCell`, with the `Default` value for T. fn default() -> UnsafeCell { UnsafeCell::new(Default::default()) @@ -2434,7 +2437,8 @@ impl SyncUnsafeCell { } #[unstable(feature = "sync_unsafe_cell", issue = "95439")] -impl Default for SyncUnsafeCell { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for SyncUnsafeCell { /// Creates an `SyncUnsafeCell`, with the `Default` value for T. fn default() -> SyncUnsafeCell { SyncUnsafeCell::new(Default::default()) diff --git a/library/core/src/default.rs b/library/core/src/default.rs index 0a15cedfb55..4d108b0c18e 100644 --- a/library/core/src/default.rs +++ b/library/core/src/default.rs @@ -103,6 +103,8 @@ use crate::ascii::Char as AsciiChar; /// ``` #[rustc_diagnostic_item = "Default"] #[stable(feature = "rust1", since = "1.0.0")] +#[const_trait] +#[rustc_const_unstable(feature = "const_default", issue = "67792")] pub trait Default: Sized { /// Returns the "default value" for a type. /// @@ -149,7 +151,8 @@ pub macro Default($item:item) { macro_rules! default_impl { ($t:ty, $v:expr, $doc:tt) => { #[stable(feature = "rust1", since = "1.0.0")] - impl Default for $t { + #[rustc_const_unstable(feature = "const_default", issue = "67792")] + impl const Default for $t { #[inline(always)] #[doc = $doc] fn default() -> $t { diff --git a/library/core/src/iter/sources/empty.rs b/library/core/src/iter/sources/empty.rs index 3c3acceded8..309962ab70c 100644 --- a/library/core/src/iter/sources/empty.rs +++ b/library/core/src/iter/sources/empty.rs @@ -81,7 +81,8 @@ impl Clone for Empty { // not #[derive] because that adds a Default bound on T, // which isn't necessary. #[stable(feature = "iter_empty", since = "1.2.0")] -impl Default for Empty { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for Empty { fn default() -> Empty { Empty(marker::PhantomData) } diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index ccbd2b00cfd..2aeb0b0c31e 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -858,7 +858,8 @@ impl Clone for PhantomData { } #[stable(feature = "rust1", since = "1.0.0")] -impl Default for PhantomData { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for PhantomData { fn default() -> Self { Self } diff --git a/library/core/src/option.rs b/library/core/src/option.rs index f2a1e901188..38eb2662b34 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -2111,7 +2111,8 @@ where impl crate::clone::UseCloned for Option where T: crate::clone::UseCloned {} #[stable(feature = "rust1", since = "1.0.0")] -impl Default for Option { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for Option { /// Returns [`None`][Option::None]. /// /// # Examples diff --git a/library/core/src/ptr/alignment.rs b/library/core/src/ptr/alignment.rs index 3e66e271f03..304cde05af9 100644 --- a/library/core/src/ptr/alignment.rs +++ b/library/core/src/ptr/alignment.rs @@ -230,7 +230,8 @@ impl hash::Hash for Alignment { /// Returns [`Alignment::MIN`], which is valid for any type. #[unstable(feature = "ptr_alignment_type", issue = "102070")] -impl Default for Alignment { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for Alignment { fn default() -> Alignment { Alignment::MIN } diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index dc09ba8d788..479fe0f1554 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -5158,7 +5158,8 @@ where } #[stable(feature = "rust1", since = "1.0.0")] -impl Default for &[T] { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for &[T] { /// Creates an empty slice. fn default() -> Self { &[] @@ -5166,7 +5167,8 @@ impl Default for &[T] { } #[stable(feature = "mut_slice_default", since = "1.5.0")] -impl Default for &mut [T] { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for &mut [T] { /// Creates a mutable empty slice. fn default() -> Self { &mut [] diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index fe64132ff22..32a22988175 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -3072,7 +3072,8 @@ impl AsRef<[u8]> for str { } #[stable(feature = "rust1", since = "1.0.0")] -impl Default for &str { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for &str { /// Creates an empty str #[inline] fn default() -> Self { @@ -3081,7 +3082,8 @@ impl Default for &str { } #[stable(feature = "default_mut_str", since = "1.28.0")] -impl Default for &mut str { +#[rustc_const_unstable(feature = "const_default", issue = "67792")] +impl const Default for &mut str { /// Creates an empty mutable str #[inline] fn default() -> Self { diff --git a/src/tools/clippy/tests/ui/or_fun_call.fixed b/src/tools/clippy/tests/ui/or_fun_call.fixed index 34f3e046841..38822bdbb30 100644 --- a/src/tools/clippy/tests/ui/or_fun_call.fixed +++ b/src/tools/clippy/tests/ui/or_fun_call.fixed @@ -406,8 +406,8 @@ fn fn_call_in_nested_expr() { val: String::from("123"), }); - let _ = opt_foo.unwrap_or_else(|| Foo { val: String::default() }); - //~^ or_fun_call + // ok, `String::default()` is now `const` + let _ = opt_foo.unwrap_or(Foo { val: String::default() }); } mod result_map_or { diff --git a/src/tools/clippy/tests/ui/or_fun_call.rs b/src/tools/clippy/tests/ui/or_fun_call.rs index dc57bd6060a..7e8647f221c 100644 --- a/src/tools/clippy/tests/ui/or_fun_call.rs +++ b/src/tools/clippy/tests/ui/or_fun_call.rs @@ -406,8 +406,8 @@ fn fn_call_in_nested_expr() { val: String::from("123"), }); + // ok, `String::default()` is now `const` let _ = opt_foo.unwrap_or(Foo { val: String::default() }); - //~^ or_fun_call } mod result_map_or { diff --git a/src/tools/clippy/tests/ui/or_fun_call.stderr b/src/tools/clippy/tests/ui/or_fun_call.stderr index 0f159fe8bff..0d88929e131 100644 --- a/src/tools/clippy/tests/ui/or_fun_call.stderr +++ b/src/tools/clippy/tests/ui/or_fun_call.stderr @@ -240,12 +240,6 @@ error: use of `unwrap_or` to construct default value LL | let _ = opt.unwrap_or({ i32::default() }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` -error: function call inside of `unwrap_or` - --> tests/ui/or_fun_call.rs:409:21 - | -LL | let _ = opt_foo.unwrap_or(Foo { val: String::default() }); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| Foo { val: String::default() })` - error: function call inside of `map_or` --> tests/ui/or_fun_call.rs:424:19 | @@ -264,5 +258,5 @@ error: function call inside of `get_or_insert` LL | let _ = x.get_or_insert(g()); | ^^^^^^^^^^^^^^^^^^ help: try: `get_or_insert_with(g)` -error: aborting due to 41 previous errors +error: aborting due to 40 previous errors diff --git a/tests/ui/consts/rustc-impl-const-stability.rs b/tests/ui/consts/rustc-impl-const-stability.rs index 0df8482bec1..93a5e8e4f45 100644 --- a/tests/ui/consts/rustc-impl-const-stability.rs +++ b/tests/ui/consts/rustc-impl-const-stability.rs @@ -2,7 +2,7 @@ //@ known-bug: #110395 #![crate_type = "lib"] -#![feature(staged_api, const_trait_impl)] +#![feature(staged_api, const_trait_impl, const_default)] #![stable(feature = "foo", since = "1.0.0")] #[stable(feature = "potato", since = "1.27.0")] @@ -12,8 +12,8 @@ pub struct Data { #[stable(feature = "potato", since = "1.27.0")] #[rustc_const_unstable(feature = "data_foo", issue = "none")] -impl const Default for Data { - fn default() -> Data { - Data { _data: 42 } +impl const std::fmt::Debug for Data { + fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { + Ok(()) } } diff --git a/tests/ui/consts/rustc-impl-const-stability.stderr b/tests/ui/consts/rustc-impl-const-stability.stderr index 19c6bb5907f..a3ef4031a13 100644 --- a/tests/ui/consts/rustc-impl-const-stability.stderr +++ b/tests/ui/consts/rustc-impl-const-stability.stderr @@ -1,8 +1,8 @@ -error: const `impl` for trait `Default` which is not marked with `#[const_trait]` +error: const `impl` for trait `Debug` which is not marked with `#[const_trait]` --> $DIR/rustc-impl-const-stability.rs:15:12 | -LL | impl const Default for Data { - | ^^^^^^^ this trait is not `const` +LL | impl const std::fmt::Debug for Data { + | ^^^^^^^^^^^^^^^ this trait is not `const` | = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change diff --git a/tests/ui/lint/dead-code/unused-struct-derive-default.rs b/tests/ui/lint/dead-code/unused-struct-derive-default.rs index f20b7cb66ee..bfbdf57b0dc 100644 --- a/tests/ui/lint/dead-code/unused-struct-derive-default.rs +++ b/tests/ui/lint/dead-code/unused-struct-derive-default.rs @@ -1,4 +1,4 @@ -#![deny(dead_code)] +#![deny(dead_code)] //~ NOTE the lint level is defined here #[derive(Default)] struct T; //~ ERROR struct `T` is never constructed @@ -7,7 +7,7 @@ struct T; //~ ERROR struct `T` is never constructed struct Used; #[derive(Default)] -enum E { +enum E { //~ NOTE variant in this enum #[default] A, B, //~ ERROR variant `B` is never constructed diff --git a/tests/ui/specialization/const_trait_impl.rs b/tests/ui/specialization/const_trait_impl.rs index 2df92dfad3b..e917263d193 100644 --- a/tests/ui/specialization/const_trait_impl.rs +++ b/tests/ui/specialization/const_trait_impl.rs @@ -2,6 +2,8 @@ #![feature(const_trait_impl, min_specialization, rustc_attrs)] +use std::fmt::Debug; + #[rustc_specialization_trait] #[const_trait] pub unsafe trait Sup { @@ -31,19 +33,19 @@ pub trait A { fn a() -> u32; } -impl const A for T { +impl const A for T { default fn a() -> u32 { 2 } } -impl const A for T { +impl const A for T { default fn a() -> u32 { 3 } } -impl const A for T { +impl const A for T { fn a() -> u32 { T::foo() } diff --git a/tests/ui/specialization/const_trait_impl.stderr b/tests/ui/specialization/const_trait_impl.stderr index ea3ec16ac1e..b9c768812c8 100644 --- a/tests/ui/specialization/const_trait_impl.stderr +++ b/tests/ui/specialization/const_trait_impl.stderr @@ -1,58 +1,58 @@ error: `[const]` can only be applied to `#[const_trait]` traits - --> $DIR/const_trait_impl.rs:34:9 + --> $DIR/const_trait_impl.rs:36:9 | -LL | impl const A for T { - | ^^^^^^^ can't be applied to `Default` +LL | impl const A for T { + | ^^^^^^^ can't be applied to `Debug` | -note: `Default` can't be used with `[const]` because it isn't annotated with `#[const_trait]` - --> $SRC_DIR/core/src/default.rs:LL:COL +note: `Debug` can't be used with `[const]` because it isn't annotated with `#[const_trait]` + --> $SRC_DIR/core/src/fmt/mod.rs:LL:COL error: `[const]` can only be applied to `#[const_trait]` traits - --> $DIR/const_trait_impl.rs:40:9 + --> $DIR/const_trait_impl.rs:42:9 | -LL | impl const A for T { - | ^^^^^^^ can't be applied to `Default` +LL | impl const A for T { + | ^^^^^^^ can't be applied to `Debug` | -note: `Default` can't be used with `[const]` because it isn't annotated with `#[const_trait]` - --> $SRC_DIR/core/src/default.rs:LL:COL +note: `Debug` can't be used with `[const]` because it isn't annotated with `#[const_trait]` + --> $SRC_DIR/core/src/fmt/mod.rs:LL:COL error: `[const]` can only be applied to `#[const_trait]` traits - --> $DIR/const_trait_impl.rs:46:9 + --> $DIR/const_trait_impl.rs:48:9 | -LL | impl const A for T { - | ^^^^^^^ can't be applied to `Default` +LL | impl const A for T { + | ^^^^^^^ can't be applied to `Debug` | -note: `Default` can't be used with `[const]` because it isn't annotated with `#[const_trait]` - --> $SRC_DIR/core/src/default.rs:LL:COL +note: `Debug` can't be used with `[const]` because it isn't annotated with `#[const_trait]` + --> $SRC_DIR/core/src/fmt/mod.rs:LL:COL error: `[const]` can only be applied to `#[const_trait]` traits - --> $DIR/const_trait_impl.rs:40:9 + --> $DIR/const_trait_impl.rs:42:9 | -LL | impl const A for T { - | ^^^^^^^ can't be applied to `Default` +LL | impl const A for T { + | ^^^^^^^ can't be applied to `Debug` | -note: `Default` can't be used with `[const]` because it isn't annotated with `#[const_trait]` - --> $SRC_DIR/core/src/default.rs:LL:COL +note: `Debug` can't be used with `[const]` because it isn't annotated with `#[const_trait]` + --> $SRC_DIR/core/src/fmt/mod.rs:LL:COL = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `[const]` can only be applied to `#[const_trait]` traits - --> $DIR/const_trait_impl.rs:34:9 + --> $DIR/const_trait_impl.rs:36:9 | -LL | impl const A for T { - | ^^^^^^^ can't be applied to `Default` +LL | impl const A for T { + | ^^^^^^^ can't be applied to `Debug` | -note: `Default` can't be used with `[const]` because it isn't annotated with `#[const_trait]` - --> $SRC_DIR/core/src/default.rs:LL:COL +note: `Debug` can't be used with `[const]` because it isn't annotated with `#[const_trait]` + --> $SRC_DIR/core/src/fmt/mod.rs:LL:COL = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `[const]` can only be applied to `#[const_trait]` traits - --> $DIR/const_trait_impl.rs:46:9 + --> $DIR/const_trait_impl.rs:48:9 | -LL | impl const A for T { - | ^^^^^^^ can't be applied to `Default` +LL | impl const A for T { + | ^^^^^^^ can't be applied to `Debug` | -note: `Default` can't be used with `[const]` because it isn't annotated with `#[const_trait]` - --> $SRC_DIR/core/src/default.rs:LL:COL +note: `Debug` can't be used with `[const]` because it isn't annotated with `#[const_trait]` + --> $SRC_DIR/core/src/fmt/mod.rs:LL:COL = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: aborting due to 6 previous errors diff --git a/tests/ui/traits/const-traits/const-traits-alloc.rs b/tests/ui/traits/const-traits/const-traits-alloc.rs new file mode 100644 index 00000000000..07725ef02f1 --- /dev/null +++ b/tests/ui/traits/const-traits/const-traits-alloc.rs @@ -0,0 +1,9 @@ +//@ run-pass +#![feature(const_trait_impl, const_default)] +#![allow(dead_code)] +// alloc::string +const STRING: String = Default::default(); +// alloc::vec +const VEC: Vec<()> = Default::default(); + +fn main() {} diff --git a/tests/ui/traits/const-traits/const-traits-core.rs b/tests/ui/traits/const-traits/const-traits-core.rs new file mode 100644 index 00000000000..6df53daae13 --- /dev/null +++ b/tests/ui/traits/const-traits/const-traits-core.rs @@ -0,0 +1,46 @@ +//@ run-pass +#![feature( + const_trait_impl, const_default, ptr_alignment_type, ascii_char, f16, f128, sync_unsafe_cell, +)] +#![allow(dead_code)] +// core::default +const UNIT: () = Default::default(); +const BOOL: bool = Default::default(); +const CHAR: char = Default::default(); +const ASCII_CHAR: std::ascii::Char = Default::default(); +const USIZE: usize = Default::default(); +const U8: u8 = Default::default(); +const U16: u16 = Default::default(); +const U32: u32 = Default::default(); +const U64: u64 = Default::default(); +const U128: u128 = Default::default(); +const I8: i8 = Default::default(); +const I16: i16 = Default::default(); +const I32: i32 = Default::default(); +const I64: i64 = Default::default(); +const I128: i128 = Default::default(); +const F16: f16 = Default::default(); +const F32: f32 = Default::default(); +const F64: f64 = Default::default(); +const F128: f128 = Default::default(); +// core::marker +const PHANTOM: std::marker::PhantomData<()> = Default::default(); +// core::option +const OPT: Option = Default::default(); +// core::iter::sources::empty +const EMPTY: std::iter::Empty<()> = Default::default(); +// core::ptr::alignment +const ALIGNMENT: std::ptr::Alignment = Default::default(); +// core::slice +const SLICE: &[()] = Default::default(); +const MUT_SLICE: &mut [()] = Default::default(); +// core::str +const STR: &str = Default::default(); +const MUT_STR: &mut str = Default::default(); +// core::cell +const CELL: std::cell::Cell<()> = Default::default(); +const REF_CELL: std::cell::RefCell<()> = Default::default(); +const UNSAFE_CELL: std::cell::UnsafeCell<()> = Default::default(); +const SYNC_UNSAFE_CELL: std::cell::SyncUnsafeCell<()> = Default::default(); + +fn main() {} diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-gate.rs b/tests/ui/traits/const-traits/const_derives/derive-const-gate.rs index a772d69c9e2..04fea1189ae 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-gate.rs +++ b/tests/ui/traits/const-traits/const_derives/derive-const-gate.rs @@ -1,5 +1,6 @@ -#[derive_const(Default)] //~ ERROR use of unstable library feature -//~^ ERROR const `impl` for trait `Default` which is not marked with `#[const_trait]` +#[derive_const(Debug)] //~ ERROR use of unstable library feature +//~^ ERROR const `impl` for trait `Debug` which is not marked with `#[const_trait]` +//~| ERROR cannot call non-const method pub struct S; fn main() {} diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-gate.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-gate.stderr index 202210a2e65..5bde358001c 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-gate.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-gate.stderr @@ -1,21 +1,30 @@ error[E0658]: use of unstable library feature `derive_const` --> $DIR/derive-const-gate.rs:1:3 | -LL | #[derive_const(Default)] +LL | #[derive_const(Debug)] | ^^^^^^^^^^^^ | = help: add `#![feature(derive_const)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error: const `impl` for trait `Default` which is not marked with `#[const_trait]` +error: const `impl` for trait `Debug` which is not marked with `#[const_trait]` --> $DIR/derive-const-gate.rs:1:16 | -LL | #[derive_const(Default)] - | ^^^^^^^ this trait is not `const` +LL | #[derive_const(Debug)] + | ^^^^^ this trait is not `const` | = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change -error: aborting due to 2 previous errors +error[E0015]: cannot call non-const method `Formatter::<'_>::write_str` in constant functions + --> $DIR/derive-const-gate.rs:1:16 + | +LL | #[derive_const(Debug)] + | ^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + +error: aborting due to 3 previous errors -For more information about this error, try `rustc --explain E0658`. +Some errors have detailed explanations: E0015, E0658. +For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.rs b/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.rs index 7bda7117a47..0bc25ce5f65 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.rs +++ b/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.rs @@ -3,11 +3,13 @@ pub struct A; -impl Default for A { - fn default() -> A { A } +impl std::fmt::Debug for A { + fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { + panic!() + } } -#[derive_const(Default)] +#[derive_const(Debug)] pub struct S(A); fn main() {} diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr index 27f4bcf46ef..c0bd360ebe5 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr @@ -1,19 +1,17 @@ -error: const `impl` for trait `Default` which is not marked with `#[const_trait]` - --> $DIR/derive-const-non-const-type.rs:10:16 +error: const `impl` for trait `Debug` which is not marked with `#[const_trait]` + --> $DIR/derive-const-non-const-type.rs:12:16 | -LL | #[derive_const(Default)] - | ^^^^^^^ this trait is not `const` +LL | #[derive_const(Debug)] + | ^^^^^ this trait is not `const` | = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change -error[E0015]: cannot call non-const associated function `::default` in constant functions - --> $DIR/derive-const-non-const-type.rs:11:14 +error[E0015]: cannot call non-const method `Formatter::<'_>::debug_tuple_field1_finish` in constant functions + --> $DIR/derive-const-non-const-type.rs:12:16 | -LL | #[derive_const(Default)] - | ------- in this derive macro expansion -LL | pub struct S(A); - | ^ +LL | #[derive_const(Debug)] + | ^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-use.rs b/tests/ui/traits/const-traits/const_derives/derive-const-use.rs index 1e447147213..1a3012de06f 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-use.rs +++ b/tests/ui/traits/const-traits/const_derives/derive-const-use.rs @@ -1,6 +1,6 @@ //@ known-bug: #110395 -#![feature(const_trait_impl, const_cmp, const_default_impls, derive_const)] +#![feature(const_trait_impl, const_default, const_cmp, derive_const)] pub struct A; diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr index ce61eb9a1ab..4ea11a0c7ed 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr @@ -1,27 +1,3 @@ -error[E0635]: unknown feature `const_default_impls` - --> $DIR/derive-const-use.rs:3:41 - | -LL | #![feature(const_trait_impl, const_cmp, const_default_impls, derive_const)] - | ^^^^^^^^^^^^^^^^^^^ - -error: const `impl` for trait `Default` which is not marked with `#[const_trait]` - --> $DIR/derive-const-use.rs:7:12 - | -LL | impl const Default for A { - | ^^^^^^^ this trait is not `const` - | - = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` - = note: adding a non-const method body in the future would be a breaking change - -error: const `impl` for trait `Default` which is not marked with `#[const_trait]` - --> $DIR/derive-const-use.rs:15:16 - | -LL | #[derive_const(Default, PartialEq)] - | ^^^^^^^ this trait is not `const` - | - = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` - = note: adding a non-const method body in the future would be a breaking change - error[E0277]: the trait bound `(): [const] PartialEq` is not satisfied --> $DIR/derive-const-use.rs:16:14 | @@ -30,35 +6,6 @@ LL | #[derive_const(Default, PartialEq)] LL | pub struct S((), A); | ^^ -error[E0015]: cannot call non-const associated function `::default` in constants - --> $DIR/derive-const-use.rs:18:35 - | -LL | const _: () = assert!(S((), A) == S::default()); - | ^^^^^^^^^^^^ - | - = note: calls in constants are limited to constant functions, tuple structs and tuple variants - -error[E0015]: cannot call non-const associated function `<() as Default>::default` in constant functions - --> $DIR/derive-const-use.rs:16:14 - | -LL | #[derive_const(Default, PartialEq)] - | ------- in this derive macro expansion -LL | pub struct S((), A); - | ^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error[E0015]: cannot call non-const associated function `::default` in constant functions - --> $DIR/derive-const-use.rs:16:18 - | -LL | #[derive_const(Default, PartialEq)] - | ------- in this derive macro expansion -LL | pub struct S((), A); - | ^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error: aborting due to 7 previous errors +error: aborting due to 1 previous error -Some errors have detailed explanations: E0015, E0277, E0635. -For more information about an error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/std-impl-gate.gated.stderr b/tests/ui/traits/const-traits/std-impl-gate.gated.stderr deleted file mode 100644 index a78cf8ce61e..00000000000 --- a/tests/ui/traits/const-traits/std-impl-gate.gated.stderr +++ /dev/null @@ -1,18 +0,0 @@ -error[E0635]: unknown feature `const_default_impls` - --> $DIR/std-impl-gate.rs:6:46 - | -LL | #![cfg_attr(gated, feature(const_trait_impl, const_default_impls))] - | ^^^^^^^^^^^^^^^^^^^ - -error[E0015]: cannot call non-const associated function ` as Default>::default` in constant functions - --> $DIR/std-impl-gate.rs:13:5 - | -LL | Default::default() - | ^^^^^^^^^^^^^^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error: aborting due to 2 previous errors - -Some errors have detailed explanations: E0015, E0635. -For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/std-impl-gate.rs b/tests/ui/traits/const-traits/std-impl-gate.rs index 84091931997..d29bccf17c9 100644 --- a/tests/ui/traits/const-traits/std-impl-gate.rs +++ b/tests/ui/traits/const-traits/std-impl-gate.rs @@ -1,9 +1,9 @@ // This tests feature gates for const impls in the standard library. //@ revisions: stock gated -//@[gated] known-bug: #110395 +//@[gated] run-pass -#![cfg_attr(gated, feature(const_trait_impl, const_default_impls))] +#![cfg_attr(gated, feature(const_trait_impl, const_default))] fn non_const_context() -> Vec { Default::default() @@ -11,7 +11,8 @@ fn non_const_context() -> Vec { const fn const_context() -> Vec { Default::default() - //[stock]~^ ERROR cannot call non-const associated function + //[stock]~^ ERROR cannot call conditionally-const associated function + //[stock]~| ERROR `Default` is not yet stable as a const trait } fn main() { diff --git a/tests/ui/traits/const-traits/std-impl-gate.stock.stderr b/tests/ui/traits/const-traits/std-impl-gate.stock.stderr index 8728f652ef9..1fa71e41a98 100644 --- a/tests/ui/traits/const-traits/std-impl-gate.stock.stderr +++ b/tests/ui/traits/const-traits/std-impl-gate.stock.stderr @@ -1,11 +1,25 @@ -error[E0015]: cannot call non-const associated function ` as Default>::default` in constant functions +error[E0658]: cannot call conditionally-const associated function ` as Default>::default` in constant functions --> $DIR/std-impl-gate.rs:13:5 | LL | Default::default() | ^^^^^^^^^^^^^^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + = note: see issue #67792 for more information + = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error: aborting due to 1 previous error +error: `Default` is not yet stable as a const trait + --> $DIR/std-impl-gate.rs:13:5 + | +LL | Default::default() + | ^^^^^^^^^^^^^^^^^^ + | +help: add `#![feature(const_default)]` to the crate attributes to enable + | +LL + #![feature(const_default)] + | + +error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0658`. -- cgit 1.4.1-3-g733a5 From 8f8099fb42f0b067cd9b6a82e704ce3cc0e63301 Mon Sep 17 00:00:00 2001 From: Esteban Küber Date: Mon, 7 Jul 2025 23:07:32 +0000 Subject: Account for const stability in clippy when checking constness --- src/tools/clippy/clippy_utils/src/visitors.rs | 6 ++++-- src/tools/clippy/tests/ui/or_fun_call.fixed | 4 ++-- src/tools/clippy/tests/ui/or_fun_call.rs | 2 +- src/tools/clippy/tests/ui/or_fun_call.stderr | 8 +++++++- 4 files changed, 14 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/tools/clippy/clippy_utils/src/visitors.rs b/src/tools/clippy/clippy_utils/src/visitors.rs index fc6e30a9804..615a0910dfd 100644 --- a/src/tools/clippy/clippy_utils/src/visitors.rs +++ b/src/tools/clippy/clippy_utils/src/visitors.rs @@ -1,5 +1,7 @@ +use crate::msrvs::Msrv; use crate::ty::needs_ordered_drop; use crate::{get_enclosing_block, path_to_local_id}; +use crate::qualify_min_const_fn::is_stable_const_fn; use core::ops::ControlFlow; use rustc_ast::visit::{VisitorResult, try_visit}; use rustc_hir::def::{CtorKind, DefKind, Res}; @@ -343,13 +345,13 @@ pub fn is_const_evaluatable<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> .cx .qpath_res(p, hir_id) .opt_def_id() - .is_some_and(|id| self.cx.tcx.is_const_fn(id)) => {}, + .is_some_and(|id| is_stable_const_fn(self.cx, id, Msrv::default())) => {}, ExprKind::MethodCall(..) if self .cx .typeck_results() .type_dependent_def_id(e.hir_id) - .is_some_and(|id| self.cx.tcx.is_const_fn(id)) => {}, + .is_some_and(|id| is_stable_const_fn(self.cx, id, Msrv::default())) => {}, ExprKind::Binary(_, lhs, rhs) if self.cx.typeck_results().expr_ty(lhs).peel_refs().is_primitive_ty() && self.cx.typeck_results().expr_ty(rhs).peel_refs().is_primitive_ty() => {}, diff --git a/src/tools/clippy/tests/ui/or_fun_call.fixed b/src/tools/clippy/tests/ui/or_fun_call.fixed index 38822bdbb30..34f3e046841 100644 --- a/src/tools/clippy/tests/ui/or_fun_call.fixed +++ b/src/tools/clippy/tests/ui/or_fun_call.fixed @@ -406,8 +406,8 @@ fn fn_call_in_nested_expr() { val: String::from("123"), }); - // ok, `String::default()` is now `const` - let _ = opt_foo.unwrap_or(Foo { val: String::default() }); + let _ = opt_foo.unwrap_or_else(|| Foo { val: String::default() }); + //~^ or_fun_call } mod result_map_or { diff --git a/src/tools/clippy/tests/ui/or_fun_call.rs b/src/tools/clippy/tests/ui/or_fun_call.rs index 7e8647f221c..dc57bd6060a 100644 --- a/src/tools/clippy/tests/ui/or_fun_call.rs +++ b/src/tools/clippy/tests/ui/or_fun_call.rs @@ -406,8 +406,8 @@ fn fn_call_in_nested_expr() { val: String::from("123"), }); - // ok, `String::default()` is now `const` let _ = opt_foo.unwrap_or(Foo { val: String::default() }); + //~^ or_fun_call } mod result_map_or { diff --git a/src/tools/clippy/tests/ui/or_fun_call.stderr b/src/tools/clippy/tests/ui/or_fun_call.stderr index 0d88929e131..0f159fe8bff 100644 --- a/src/tools/clippy/tests/ui/or_fun_call.stderr +++ b/src/tools/clippy/tests/ui/or_fun_call.stderr @@ -240,6 +240,12 @@ error: use of `unwrap_or` to construct default value LL | let _ = opt.unwrap_or({ i32::default() }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` +error: function call inside of `unwrap_or` + --> tests/ui/or_fun_call.rs:409:21 + | +LL | let _ = opt_foo.unwrap_or(Foo { val: String::default() }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| Foo { val: String::default() })` + error: function call inside of `map_or` --> tests/ui/or_fun_call.rs:424:19 | @@ -258,5 +264,5 @@ error: function call inside of `get_or_insert` LL | let _ = x.get_or_insert(g()); | ^^^^^^^^^^^^^^^^^^ help: try: `get_or_insert_with(g)` -error: aborting due to 40 previous errors +error: aborting due to 41 previous errors -- cgit 1.4.1-3-g733a5 From a58a423f9a37c614d56f86fbbfbebec414caaaf1 Mon Sep 17 00:00:00 2001 From: Jens Reidel Date: Tue, 8 Jul 2025 03:16:46 +0200 Subject: Add target maintainer information for mips64-unknown-linux-muslabi64 The mips64-unknown-linux-muslabi64 target is currently rather broken, but I'm working on getting it fixed so that it can at least be used again. While I can't commit to maintaining the LLVM side of this target, I don't mind looking into any other MIPS or musl-related issues that arise with this target. Signed-off-by: Jens Reidel --- src/doc/rustc/src/SUMMARY.md | 1 + src/doc/rustc/src/platform-support.md | 2 +- .../mips64-unknown-linux-muslabi64.md | 49 ++++++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/doc/rustc/src/platform-support/mips64-unknown-linux-muslabi64.md (limited to 'src') diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md index 9fe4c218121..e1742631f63 100644 --- a/src/doc/rustc/src/SUMMARY.md +++ b/src/doc/rustc/src/SUMMARY.md @@ -83,6 +83,7 @@ - [m68k-unknown-linux-gnu](platform-support/m68k-unknown-linux-gnu.md) - [m68k-unknown-none-elf](platform-support/m68k-unknown-none-elf.md) - [mips64-openwrt-linux-musl](platform-support/mips64-openwrt-linux-musl.md) + - [mips64-unknown-linux-muslabi64](platform-support/mips64-unknown-linux-muslabi64.md) - [mipsel-sony-psx](platform-support/mipsel-sony-psx.md) - [mipsel-unknown-linux-gnu](platform-support/mipsel-unknown-linux-gnu.md) - [mips\*-mti-none-elf](platform-support/mips-mti-none-elf.md) diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index 285b1e519b7..ed01de4c1c3 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -333,7 +333,7 @@ target | std | host | notes `mips-unknown-linux-uclibc` | ✓ | | MIPS Linux with uClibc [`mips64-openwrt-linux-musl`](platform-support/mips64-openwrt-linux-musl.md) | ? | | MIPS64 for OpenWrt Linux musl 1.2.3 `mips64-unknown-linux-gnuabi64` | ✓ | ✓ | MIPS64 Linux, N64 ABI (kernel 4.4, glibc 2.23) -`mips64-unknown-linux-muslabi64` | ✓ | | MIPS64 Linux, N64 ABI, musl 1.2.3 +[`mips64-unknown-linux-muslabi64`](platform-support/mips64-unknown-linux-muslabi64.md) | ✓ | ✓ | MIPS64 Linux, N64 ABI, musl 1.2.3 `mips64el-unknown-linux-gnuabi64` | ✓ | ✓ | MIPS64 (little endian) Linux, N64 ABI (kernel 4.4, glibc 2.23) `mips64el-unknown-linux-muslabi64` | ✓ | | MIPS64 (little endian) Linux, N64 ABI, musl 1.2.3 `mipsel-sony-psp` | * | | MIPS (LE) Sony PlayStation Portable (PSP) diff --git a/src/doc/rustc/src/platform-support/mips64-unknown-linux-muslabi64.md b/src/doc/rustc/src/platform-support/mips64-unknown-linux-muslabi64.md new file mode 100644 index 00000000000..60c0972bb3e --- /dev/null +++ b/src/doc/rustc/src/platform-support/mips64-unknown-linux-muslabi64.md @@ -0,0 +1,49 @@ +# mips64-unknown-linux-muslabi64 + +**Tier: 3** + +Target for 64-bit big endian MIPS Linux programs using musl libc and the N64 ABI. + +## Target maintainers + +[@Gelbpunkt](https://github.com/Gelbpunkt) + +## Requirements + +Building the target itself requires a 64-bit big endian MIPS compiler that is +supported by `cc-rs`. + +## Building the target + +The target can be built by enabling it for a `rustc` build. + +```toml +[build] +target = ["mips64-unknown-linux-muslabi64"] +``` + +Make sure your C compiler is included in `$PATH`, then add it to the +`bootstrap.toml`: + +```toml +[target.mips64-unknown-linux-muslabi64] +cc = "mips64-linux-musl-gcc" +cxx = "mips64-linux-musl-g++" +ar = "mips64-linux-musl-ar" +linker = "mips64-linux-musl-gcc" +``` + +## Building Rust programs + +Rust does not yet ship pre-compiled artifacts for this target. To compile for +this target, you will first need to build Rust with the target enabled (see +"Building the target" above). + +## Cross-compilation + +This target can be cross-compiled from any host. + +## Testing + +This target can be tested as normal with `x.py` on a 64-bit big endian MIPS +host or via QEMU emulation. -- cgit 1.4.1-3-g733a5 From 717041232ae0ae0ae445a2a302510aab3375ea47 Mon Sep 17 00:00:00 2001 From: Predrag Gruevski Date: Mon, 7 Jul 2025 00:56:29 +0000 Subject: Don't mark `#[target_feature]` safe fns as unsafe in rustdoc JSON. --- src/librustdoc/json/conversions.rs | 15 ++++++++++++++- tests/rustdoc-json/attrs/target_feature.rs | 23 +++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index f51b35097f6..f76ff11590b 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -9,6 +9,7 @@ use rustc_ast::ast; use rustc_attr_data_structures::{self as attrs, DeprecatedSince}; use rustc_hir::def::CtorKind; use rustc_hir::def_id::DefId; +use rustc_hir::{HeaderSafety, Safety}; use rustc_metadata::rendered_const; use rustc_middle::{bug, ty}; use rustc_span::{Pos, kw, sym}; @@ -383,10 +384,22 @@ impl FromClean for Union { impl FromClean for FunctionHeader { fn from_clean(header: &rustc_hir::FnHeader, renderer: &JsonRenderer<'_>) -> Self { + let is_unsafe = match header.safety { + HeaderSafety::SafeTargetFeatures => { + // The type system's internal implementation details consider + // safe functions with the `#[target_feature]` attribute to be analogous + // to unsafe functions: `header.is_unsafe()` returns `true` for them. + // For rustdoc, this isn't the right decision, so we explicitly return `false`. + // Context: https://github.com/rust-lang/rust/issues/142655 + false + } + HeaderSafety::Normal(Safety::Safe) => false, + HeaderSafety::Normal(Safety::Unsafe) => true, + }; FunctionHeader { is_async: header.is_async(), is_const: header.is_const(), - is_unsafe: header.is_unsafe(), + is_unsafe, abi: header.abi.into_json(renderer), } } diff --git a/tests/rustdoc-json/attrs/target_feature.rs b/tests/rustdoc-json/attrs/target_feature.rs index ee2b3235f72..80262d8e332 100644 --- a/tests/rustdoc-json/attrs/target_feature.rs +++ b/tests/rustdoc-json/attrs/target_feature.rs @@ -1,17 +1,40 @@ //@ only-x86_64 //@ is "$.index[?(@.name=='test1')].attrs" '["#[target_feature(enable=\"avx\")]"]' +//@ is "$.index[?(@.name=='test1')].inner.function.header.is_unsafe" false #[target_feature(enable = "avx")] pub fn test1() {} //@ is "$.index[?(@.name=='test2')].attrs" '["#[target_feature(enable=\"avx\", enable=\"avx2\")]"]' +//@ is "$.index[?(@.name=='test1')].inner.function.header.is_unsafe" false #[target_feature(enable = "avx,avx2")] pub fn test2() {} //@ is "$.index[?(@.name=='test3')].attrs" '["#[target_feature(enable=\"avx\", enable=\"avx2\")]"]' +//@ is "$.index[?(@.name=='test1')].inner.function.header.is_unsafe" false #[target_feature(enable = "avx", enable = "avx2")] pub fn test3() {} //@ is "$.index[?(@.name=='test4')].attrs" '["#[target_feature(enable=\"avx\", enable=\"avx2\", enable=\"avx512f\")]"]' +//@ is "$.index[?(@.name=='test1')].inner.function.header.is_unsafe" false #[target_feature(enable = "avx", enable = "avx2,avx512f")] pub fn test4() {} + +//@ is "$.index[?(@.name=='test_unsafe_fn')].attrs" '["#[target_feature(enable=\"avx\")]"]' +//@ is "$.index[?(@.name=='test_unsafe_fn')].inner.function.header.is_unsafe" true +#[target_feature(enable = "avx")] +pub unsafe fn test_unsafe_fn() {} + +pub struct Example; + +impl Example { + //@ is "$.index[?(@.name=='safe_assoc_fn')].attrs" '["#[target_feature(enable=\"avx\")]"]' + //@ is "$.index[?(@.name=='safe_assoc_fn')].inner.function.header.is_unsafe" false + #[target_feature(enable = "avx")] + pub fn safe_assoc_fn() {} + + //@ is "$.index[?(@.name=='unsafe_assoc_fn')].attrs" '["#[target_feature(enable=\"avx\")]"]' + //@ is "$.index[?(@.name=='unsafe_assoc_fn')].inner.function.header.is_unsafe" true + #[target_feature(enable = "avx")] + pub unsafe fn unsafe_assoc_fn() {} +} -- cgit 1.4.1-3-g733a5 From a4ea949356b8d40e7c588cccf30739fbb22cd45c Mon Sep 17 00:00:00 2001 From: Rémy Rakic Date: Mon, 17 Mar 2025 21:57:44 +0100 Subject: use LLD by default on x64 regardless of channel --- src/bootstrap/src/core/build_steps/compile.rs | 4 +--- src/bootstrap/src/core/config/toml/rust.rs | 5 +---- 2 files changed, 2 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 3e2bdc2d6b5..ca74771bb6e 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -1369,9 +1369,7 @@ pub fn rustc_cargo_env( } // Enable rustc's env var for `rust-lld` when requested. - if builder.config.lld_enabled - && (builder.config.channel == "dev" || builder.config.channel == "nightly") - { + if builder.config.lld_enabled { cargo.env("CFG_USE_SELF_CONTAINED_LINKER", "1"); } diff --git a/src/bootstrap/src/core/config/toml/rust.rs b/src/bootstrap/src/core/config/toml/rust.rs index ac5eaea3bcb..0fae235bb93 100644 --- a/src/bootstrap/src/core/config/toml/rust.rs +++ b/src/bootstrap/src/core/config/toml/rust.rs @@ -619,7 +619,6 @@ impl Config { // build our internal lld and use it as the default linker, by setting the `rust.lld` config // to true by default: // - on the `x86_64-unknown-linux-gnu` target - // - on the `dev` and `nightly` channels // - when building our in-tree llvm (i.e. the target has not set an `llvm-config`), so that // we're also able to build the corresponding lld // - or when using an external llvm that's downloaded from CI, which also contains our prebuilt @@ -628,9 +627,7 @@ impl Config { // thus, disabled // - similarly, lld will not be built nor used by default when explicitly asked not to, e.g. // when the config sets `rust.lld = false` - if self.host_target.triple == "x86_64-unknown-linux-gnu" - && self.hosts == [self.host_target] - && (self.channel == "dev" || self.channel == "nightly") + if self.host_target.triple == "x86_64-unknown-linux-gnu" && self.hosts == [self.host_target] { let no_llvm_config = self .target_config -- cgit 1.4.1-3-g733a5 From aa527115432df082f3c9e4d2459acb7bb02ed5a6 Mon Sep 17 00:00:00 2001 From: Rémy Rakic Date: Tue, 18 Mar 2025 08:17:38 +0100 Subject: add post-dist test for checking that we use LLD And remove the previous beta/stable/nightly LLD tests. --- src/tools/opt-dist/src/tests.rs | 3 +++ .../run-make/rust-lld-by-default-beta-stable/main.rs | 1 - .../rust-lld-by-default-beta-stable/rmake.rs | 14 -------------- tests/run-make/rust-lld-by-default-nightly/main.rs | 5 ----- tests/run-make/rust-lld-by-default-nightly/rmake.rs | 19 ------------------- .../rust-lld-x86_64-unknown-linux-gnu-dist/main.rs | 5 +++++ .../rust-lld-x86_64-unknown-linux-gnu-dist/rmake.rs | 16 ++++++++++++++++ .../rust-lld-x86_64-unknown-linux-gnu/main.rs | 5 +++++ .../rust-lld-x86_64-unknown-linux-gnu/rmake.rs | 20 ++++++++++++++++++++ 9 files changed, 49 insertions(+), 39 deletions(-) delete mode 100644 tests/run-make/rust-lld-by-default-beta-stable/main.rs delete mode 100644 tests/run-make/rust-lld-by-default-beta-stable/rmake.rs delete mode 100644 tests/run-make/rust-lld-by-default-nightly/main.rs delete mode 100644 tests/run-make/rust-lld-by-default-nightly/rmake.rs create mode 100644 tests/run-make/rust-lld-x86_64-unknown-linux-gnu-dist/main.rs create mode 100644 tests/run-make/rust-lld-x86_64-unknown-linux-gnu-dist/rmake.rs create mode 100644 tests/run-make/rust-lld-x86_64-unknown-linux-gnu/main.rs create mode 100644 tests/run-make/rust-lld-x86_64-unknown-linux-gnu/rmake.rs (limited to 'src') diff --git a/src/tools/opt-dist/src/tests.rs b/src/tools/opt-dist/src/tests.rs index 705a1750ae8..2d2aab86eda 100644 --- a/src/tools/opt-dist/src/tests.rs +++ b/src/tools/opt-dist/src/tests.rs @@ -106,7 +106,10 @@ llvm-config = "{llvm_config}" "tests/incremental", "tests/mir-opt", "tests/pretty", + // Make sure that we don't use too new GLIBC symbols on x64 "tests/run-make/glibc-symbols-x86_64-unknown-linux-gnu", + // Make sure that we use LLD by default on x64 + "tests/run-make/rust-lld-x86_64-unknown-linux-gnu-dist", "tests/ui", "tests/crashes", ]; diff --git a/tests/run-make/rust-lld-by-default-beta-stable/main.rs b/tests/run-make/rust-lld-by-default-beta-stable/main.rs deleted file mode 100644 index f328e4d9d04..00000000000 --- a/tests/run-make/rust-lld-by-default-beta-stable/main.rs +++ /dev/null @@ -1 +0,0 @@ -fn main() {} diff --git a/tests/run-make/rust-lld-by-default-beta-stable/rmake.rs b/tests/run-make/rust-lld-by-default-beta-stable/rmake.rs deleted file mode 100644 index 9a08991c4b8..00000000000 --- a/tests/run-make/rust-lld-by-default-beta-stable/rmake.rs +++ /dev/null @@ -1,14 +0,0 @@ -// Ensure that rust-lld is *not* used as the default linker on `x86_64-unknown-linux-gnu` on stable -// or beta. - -//@ ignore-nightly -//@ only-x86_64-unknown-linux-gnu - -use run_make_support::linker::assert_rustc_doesnt_use_lld; -use run_make_support::rustc; - -fn main() { - // A regular compilation should not use rust-lld by default. We'll check that by asking the - // linker to display its version number with a link-arg. - assert_rustc_doesnt_use_lld(rustc().input("main.rs")); -} diff --git a/tests/run-make/rust-lld-by-default-nightly/main.rs b/tests/run-make/rust-lld-by-default-nightly/main.rs deleted file mode 100644 index e9f655fc09e..00000000000 --- a/tests/run-make/rust-lld-by-default-nightly/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -// Test linking using `cc` with `rust-lld`, which is on by default on the x86_64-unknown-linux-gnu -// target. -// See https://github.com/rust-lang/compiler-team/issues/510 for more info - -fn main() {} diff --git a/tests/run-make/rust-lld-by-default-nightly/rmake.rs b/tests/run-make/rust-lld-by-default-nightly/rmake.rs deleted file mode 100644 index 3ff1e2770e6..00000000000 --- a/tests/run-make/rust-lld-by-default-nightly/rmake.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Ensure that rust-lld is used as the default linker on `x86_64-unknown-linux-gnu` on the nightly -// channel, and that it can also be turned off with a CLI flag. - -//@ needs-rust-lld -//@ ignore-beta -//@ ignore-stable -//@ only-x86_64-unknown-linux-gnu - -use run_make_support::linker::{assert_rustc_doesnt_use_lld, assert_rustc_uses_lld}; -use run_make_support::rustc; - -fn main() { - // A regular compilation should use rust-lld by default. We'll check that by asking the linker - // to display its version number with a link-arg. - assert_rustc_uses_lld(rustc().input("main.rs")); - - // But it can still be disabled by turning the linker feature off. - assert_rustc_doesnt_use_lld(rustc().arg("-Zlinker-features=-lld").input("main.rs")); -} diff --git a/tests/run-make/rust-lld-x86_64-unknown-linux-gnu-dist/main.rs b/tests/run-make/rust-lld-x86_64-unknown-linux-gnu-dist/main.rs new file mode 100644 index 00000000000..e9f655fc09e --- /dev/null +++ b/tests/run-make/rust-lld-x86_64-unknown-linux-gnu-dist/main.rs @@ -0,0 +1,5 @@ +// Test linking using `cc` with `rust-lld`, which is on by default on the x86_64-unknown-linux-gnu +// target. +// See https://github.com/rust-lang/compiler-team/issues/510 for more info + +fn main() {} diff --git a/tests/run-make/rust-lld-x86_64-unknown-linux-gnu-dist/rmake.rs b/tests/run-make/rust-lld-x86_64-unknown-linux-gnu-dist/rmake.rs new file mode 100644 index 00000000000..c26f82b7d37 --- /dev/null +++ b/tests/run-make/rust-lld-x86_64-unknown-linux-gnu-dist/rmake.rs @@ -0,0 +1,16 @@ +// Ensure that rust-lld is used as the default linker on `x86_64-unknown-linux-gnu` +// dist artifacts and that it can also be turned off with a CLI flag. + +//@ only-dist +//@ only-x86_64-unknown-linux-gnu + +use run_make_support::linker::{assert_rustc_doesnt_use_lld, assert_rustc_uses_lld}; +use run_make_support::rustc; + +fn main() { + // A regular compilation should use rust-lld by default. + assert_rustc_uses_lld(rustc().input("main.rs")); + + // But it can still be disabled by turning the linker feature off. + assert_rustc_doesnt_use_lld(rustc().arg("-Zlinker-features=-lld").input("main.rs")); +} diff --git a/tests/run-make/rust-lld-x86_64-unknown-linux-gnu/main.rs b/tests/run-make/rust-lld-x86_64-unknown-linux-gnu/main.rs new file mode 100644 index 00000000000..e9f655fc09e --- /dev/null +++ b/tests/run-make/rust-lld-x86_64-unknown-linux-gnu/main.rs @@ -0,0 +1,5 @@ +// Test linking using `cc` with `rust-lld`, which is on by default on the x86_64-unknown-linux-gnu +// target. +// See https://github.com/rust-lang/compiler-team/issues/510 for more info + +fn main() {} diff --git a/tests/run-make/rust-lld-x86_64-unknown-linux-gnu/rmake.rs b/tests/run-make/rust-lld-x86_64-unknown-linux-gnu/rmake.rs new file mode 100644 index 00000000000..e71a47f11e2 --- /dev/null +++ b/tests/run-make/rust-lld-x86_64-unknown-linux-gnu/rmake.rs @@ -0,0 +1,20 @@ +// Ensure that rust-lld is used as the default linker on `x86_64-unknown-linux-gnu` +// and that it can also be turned off with a CLI flag. +// +// This version of the test checks that LLD is used by default when LLD is enabled in the +// toolchain. There is a separate test that checks that LLD is used for dist artifacts +// unconditionally. + +//@ needs-rust-lld +//@ only-x86_64-unknown-linux-gnu + +use run_make_support::linker::{assert_rustc_doesnt_use_lld, assert_rustc_uses_lld}; +use run_make_support::rustc; + +fn main() { + // A regular compilation should use rust-lld by default. + assert_rustc_uses_lld(rustc().input("main.rs")); + + // But it can still be disabled by turning the linker feature off. + assert_rustc_doesnt_use_lld(rustc().arg("-Zlinker-features=-lld").input("main.rs")); +} -- cgit 1.4.1-3-g733a5 From d6179022c1d86f6c3e63a64933dff2734b366935 Mon Sep 17 00:00:00 2001 From: Rémy Rakic Date: Tue, 8 Jul 2025 09:20:14 +0000 Subject: update bootstrap mcp510 handling beta and stage1 need to use different flags (-C vs -Z) to be able to use the old and new `linker-features` and `link-self-contained` flags --- src/bootstrap/src/core/build_steps/test.rs | 20 ++++++++++++++++---- src/bootstrap/src/core/builder/cargo.rs | 15 ++++++++++----- src/bootstrap/src/core/builder/mod.rs | 2 +- src/bootstrap/src/utils/helpers.rs | 25 +++++++++++++++++++------ 4 files changed, 46 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index a5b7b22aba8..716bef3f38c 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -262,7 +262,13 @@ impl Step for Cargotest { .args(builder.config.test_args()) .env("RUSTC", builder.rustc(compiler)) .env("RUSTDOC", builder.rustdoc(compiler)); - add_rustdoc_cargo_linker_args(&mut cmd, builder, compiler.host, LldThreads::No); + add_rustdoc_cargo_linker_args( + &mut cmd, + builder, + compiler.host, + LldThreads::No, + compiler.stage, + ); cmd.delay_failure().run(builder); } } @@ -857,7 +863,7 @@ impl Step for RustdocTheme { .env("CFG_RELEASE_CHANNEL", &builder.config.channel) .env("RUSTDOC_REAL", builder.rustdoc(self.compiler)) .env("RUSTC_BOOTSTRAP", "1"); - cmd.args(linker_args(builder, self.compiler.host, LldThreads::No)); + cmd.args(linker_args(builder, self.compiler.host, LldThreads::No, self.compiler.stage)); cmd.delay_failure().run(builder); } @@ -1033,7 +1039,13 @@ impl Step for RustdocGUI { cmd.env("RUSTDOC", builder.rustdoc(self.compiler)) .env("RUSTC", builder.rustc(self.compiler)); - add_rustdoc_cargo_linker_args(&mut cmd, builder, self.compiler.host, LldThreads::No); + add_rustdoc_cargo_linker_args( + &mut cmd, + builder, + self.compiler.host, + LldThreads::No, + self.compiler.stage, + ); for path in &builder.paths { if let Some(p) = helpers::is_valid_test_suite_arg(path, "tests/rustdoc-gui", builder) { @@ -1812,7 +1824,7 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the } let mut hostflags = flags.clone(); - hostflags.extend(linker_flags(builder, compiler.host, LldThreads::No)); + hostflags.extend(linker_flags(builder, compiler.host, LldThreads::No, compiler.stage)); let mut targetflags = flags; diff --git a/src/bootstrap/src/core/builder/cargo.rs b/src/bootstrap/src/core/builder/cargo.rs index deb7106f185..065d7e45e0f 100644 --- a/src/bootstrap/src/core/builder/cargo.rs +++ b/src/bootstrap/src/core/builder/cargo.rs @@ -115,7 +115,7 @@ impl Cargo { // No need to configure the target linker for these command types. Kind::Clean | Kind::Check | Kind::Suggest | Kind::Format | Kind::Setup => {} _ => { - cargo.configure_linker(builder); + cargo.configure_linker(builder, mode); } } @@ -209,7 +209,7 @@ impl Cargo { // FIXME(onur-ozkan): Add coverage to make sure modifications to this function // doesn't cause cache invalidations (e.g., #130108). - fn configure_linker(&mut self, builder: &Builder<'_>) -> &mut Cargo { + fn configure_linker(&mut self, builder: &Builder<'_>, mode: Mode) -> &mut Cargo { let target = self.target; let compiler = self.compiler; @@ -264,7 +264,12 @@ impl Cargo { } } - for arg in linker_args(builder, compiler.host, LldThreads::Yes) { + // We use the snapshot compiler when building host code (build scripts/proc macros) of + // `Mode::Std` tools, so we need to determine the current stage here to pass the proper + // linker args (e.g. -C vs -Z). + // This should stay synchronized with the [cargo] function. + let host_stage = if mode == Mode::Std { 0 } else { compiler.stage }; + for arg in linker_args(builder, compiler.host, LldThreads::Yes, host_stage) { self.hostflags.arg(&arg); } @@ -274,10 +279,10 @@ impl Cargo { } // We want to set -Clinker using Cargo, therefore we only call `linker_flags` and not // `linker_args` here. - for flag in linker_flags(builder, target, LldThreads::Yes) { + for flag in linker_flags(builder, target, LldThreads::Yes, compiler.stage) { self.rustflags.arg(&flag); } - for arg in linker_args(builder, target, LldThreads::Yes) { + for arg in linker_args(builder, target, LldThreads::Yes, compiler.stage) { self.rustdocflags.arg(&arg); } diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index b96a988cde3..7464327fde9 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -1599,7 +1599,7 @@ You have to build a stage1 compiler for `{}` first, and then use it to build a s cmd.arg("-Dwarnings"); } cmd.arg("-Znormalize-docs"); - cmd.args(linker_args(self, compiler.host, LldThreads::Yes)); + cmd.args(linker_args(self, compiler.host, LldThreads::Yes, compiler.stage)); cmd } diff --git a/src/bootstrap/src/utils/helpers.rs b/src/bootstrap/src/utils/helpers.rs index 3c5f612daa7..eb00ed566c2 100644 --- a/src/bootstrap/src/utils/helpers.rs +++ b/src/bootstrap/src/utils/helpers.rs @@ -404,8 +404,9 @@ pub fn linker_args( builder: &Builder<'_>, target: TargetSelection, lld_threads: LldThreads, + stage: u32, ) -> Vec { - let mut args = linker_flags(builder, target, lld_threads); + let mut args = linker_flags(builder, target, lld_threads, stage); if let Some(linker) = builder.linker(target) { args.push(format!("-Clinker={}", linker.display())); @@ -420,19 +421,30 @@ pub fn linker_flags( builder: &Builder<'_>, target: TargetSelection, lld_threads: LldThreads, + stage: u32, ) -> Vec { let mut args = vec![]; if !builder.is_lld_direct_linker(target) && builder.config.lld_mode.is_used() { match builder.config.lld_mode { LldMode::External => { - args.push("-Zlinker-features=+lld".to_string()); - // FIXME(kobzol): remove this flag once MCP510 gets stabilized + // cfg(bootstrap) - remove the stage 0 check after updating the bootstrap compiler: + // `-Clinker-features` has been stabilized. + if stage == 0 { + args.push("-Zlinker-features=+lld".to_string()); + } else { + args.push("-Clinker-features=+lld".to_string()); + } args.push("-Zunstable-options".to_string()); } LldMode::SelfContained => { - args.push("-Zlinker-features=+lld".to_string()); + // cfg(bootstrap) - remove the stage 0 check after updating the bootstrap compiler: + // `-Clinker-features` has been stabilized. + if stage == 0 { + args.push("-Zlinker-features=+lld".to_string()); + } else { + args.push("-Clinker-features=+lld".to_string()); + } args.push("-Clink-self-contained=+linker".to_string()); - // FIXME(kobzol): remove this flag once MCP510 gets stabilized args.push("-Zunstable-options".to_string()); } LldMode::Unused => unreachable!(), @@ -453,8 +465,9 @@ pub fn add_rustdoc_cargo_linker_args( builder: &Builder<'_>, target: TargetSelection, lld_threads: LldThreads, + stage: u32, ) { - let args = linker_args(builder, target, lld_threads); + let args = linker_args(builder, target, lld_threads, stage); let mut flags = cmd .get_envs() .find_map(|(k, v)| if k == OsStr::new("RUSTDOCFLAGS") { v } else { None }) -- cgit 1.4.1-3-g733a5 From 754d46e33a2a01fef9732b4bb7c2bb479f744195 Mon Sep 17 00:00:00 2001 From: Jakub Beránek Date: Tue, 10 Jun 2025 20:15:36 +0200 Subject: Remove `extra_features` from `LlvmBitcodeLinker` It wasn't used anywhere. --- src/bootstrap/src/core/build_steps/compile.rs | 1 - src/bootstrap/src/core/build_steps/dist.rs | 3 +-- src/bootstrap/src/core/build_steps/tool.rs | 4 +--- 3 files changed, 2 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 3e2bdc2d6b5..c84f451bbb2 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -2061,7 +2061,6 @@ impl Step for Assemble { builder.ensure(crate::core::build_steps::tool::LlvmBitcodeLinker { compiler, target: target_compiler.host, - extra_features: vec![], }); let tool_exe = exe("llvm-bitcode-linker", target_compiler.host); builder.copy_link( diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index 25b7e5a1b5d..f2aace76896 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -2374,8 +2374,7 @@ impl Step for LlvmBitcodeLinker { builder.ensure(compile::Rustc::new(compiler, target)); - let llbc_linker = - builder.ensure(tool::LlvmBitcodeLinker { compiler, target, extra_features: vec![] }); + let llbc_linker = builder.ensure(tool::LlvmBitcodeLinker { compiler, target }); let self_contained_bin_dir = format!("lib/rustlib/{}/bin/self-contained", target.triple); diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index b05b34b9b22..b906409aedd 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -1016,7 +1016,6 @@ impl Step for RustAnalyzerProcMacroSrv { pub struct LlvmBitcodeLinker { pub compiler: Compiler, pub target: TargetSelection, - pub extra_features: Vec, } impl Step for LlvmBitcodeLinker { @@ -1033,7 +1032,6 @@ impl Step for LlvmBitcodeLinker { fn make_run(run: RunConfig<'_>) { run.builder.ensure(LlvmBitcodeLinker { compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.host_target), - extra_features: Vec::new(), target: run.target, }); } @@ -1050,7 +1048,7 @@ impl Step for LlvmBitcodeLinker { mode: Mode::ToolRustc, path: "src/tools/llvm-bitcode-linker", source_type: SourceType::InTree, - extra_features: self.extra_features, + extra_features: vec![], allow_features: "", cargo_args: Vec::new(), artifact_kind: ToolArtifactKind::Binary, -- cgit 1.4.1-3-g733a5 From c33f908f57cf1f3ea1a1261440062d2757909dc4 Mon Sep 17 00:00:00 2001 From: Jakub Beránek Date: Wed, 11 Jun 2025 08:50:09 +0200 Subject: Remove sysroot copy from `LlvmBitcodeLinker` step That step should be responsible for building the tool, not performing side-effects. Also, only copy the tool to the `self-contained` directory, not to the `rustlib//bin` directory. --- src/bootstrap/src/core/build_steps/compile.rs | 9 ++++++++- src/bootstrap/src/core/build_steps/tool.rs | 21 ++------------------- 2 files changed, 10 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index c84f451bbb2..1d095cfc58e 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -2062,10 +2062,17 @@ impl Step for Assemble { compiler, target: target_compiler.host, }); + + // Copy the llvm-bitcode-linker to the self-contained binary directory + let bindir_self_contained = builder + .sysroot(compiler) + .join(format!("lib/rustlib/{}/bin/self-contained", compiler.host)); let tool_exe = exe("llvm-bitcode-linker", target_compiler.host); + + t!(fs::create_dir_all(&bindir_self_contained)); builder.copy_link( &llvm_bitcode_linker.tool_path, - &libdir_bin.join(tool_exe), + &bindir_self_contained.join(tool_exe), FileType::Executable, ); } diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index b906409aedd..8396099d380 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -1041,7 +1041,7 @@ impl Step for LlvmBitcodeLinker { instrument(level = "debug", name = "LlvmBitcodeLinker::run", skip_all) )] fn run(self, builder: &Builder<'_>) -> ToolBuildResult { - let tool_result = builder.ensure(ToolBuild { + builder.ensure(ToolBuild { compiler: self.compiler, target: self.target, tool: "llvm-bitcode-linker", @@ -1052,24 +1052,7 @@ impl Step for LlvmBitcodeLinker { allow_features: "", cargo_args: Vec::new(), artifact_kind: ToolArtifactKind::Binary, - }); - - if tool_result.target_compiler.stage > 0 { - let bindir_self_contained = builder - .sysroot(tool_result.target_compiler) - .join(format!("lib/rustlib/{}/bin/self-contained", self.target.triple)); - t!(fs::create_dir_all(&bindir_self_contained)); - let bin_destination = bindir_self_contained - .join(exe("llvm-bitcode-linker", tool_result.target_compiler.host)); - builder.copy_link(&tool_result.tool_path, &bin_destination, FileType::Executable); - ToolBuildResult { - tool_path: bin_destination, - build_compiler: tool_result.build_compiler, - target_compiler: tool_result.target_compiler, - } - } else { - tool_result - } + }) } } -- cgit 1.4.1-3-g733a5 From fd3772200140b82324a7af8b4153c2a1a2ac1e89 Mon Sep 17 00:00:00 2001 From: Jakub Beránek Date: Tue, 8 Jul 2025 11:47:57 +0200 Subject: Update llvm-bitcode-linker tests --- src/bootstrap/src/core/build_steps/compile.rs | 2 +- src/bootstrap/src/core/build_steps/dist.rs | 3 ++- src/bootstrap/src/core/build_steps/tool.rs | 12 +++++++++--- src/bootstrap/src/core/builder/tests.rs | 23 +++++++++++++++++++++++ 4 files changed, 35 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 1d095cfc58e..29300ff56f5 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -2059,7 +2059,7 @@ impl Step for Assemble { trace!("llvm-bitcode-linker enabled, installing"); let llvm_bitcode_linker = builder.ensure(crate::core::build_steps::tool::LlvmBitcodeLinker { - compiler, + build_compiler: compiler, target: target_compiler.host, }); diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index f2aace76896..8b2d65ace50 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -2374,7 +2374,8 @@ impl Step for LlvmBitcodeLinker { builder.ensure(compile::Rustc::new(compiler, target)); - let llbc_linker = builder.ensure(tool::LlvmBitcodeLinker { compiler, target }); + let llbc_linker = + builder.ensure(tool::LlvmBitcodeLinker { build_compiler: compiler, target }); let self_contained_bin_dir = format!("lib/rustlib/{}/bin/self-contained", target.triple); diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 8396099d380..a7f6a2c7bae 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -1014,7 +1014,7 @@ impl Step for RustAnalyzerProcMacroSrv { #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct LlvmBitcodeLinker { - pub compiler: Compiler, + pub build_compiler: Compiler, pub target: TargetSelection, } @@ -1031,7 +1031,9 @@ impl Step for LlvmBitcodeLinker { fn make_run(run: RunConfig<'_>) { run.builder.ensure(LlvmBitcodeLinker { - compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.host_target), + build_compiler: run + .builder + .compiler(run.builder.top_stage, run.builder.config.host_target), target: run.target, }); } @@ -1042,7 +1044,7 @@ impl Step for LlvmBitcodeLinker { )] fn run(self, builder: &Builder<'_>) -> ToolBuildResult { builder.ensure(ToolBuild { - compiler: self.compiler, + compiler: self.build_compiler, target: self.target, tool: "llvm-bitcode-linker", mode: Mode::ToolRustc, @@ -1054,6 +1056,10 @@ impl Step for LlvmBitcodeLinker { artifact_kind: ToolArtifactKind::Binary, }) } + + fn metadata(&self) -> Option { + Some(StepMetadata::build("LlvmBitcodeLinker", self.target).built_by(self.build_compiler)) + } } #[derive(Debug, Clone, Hash, PartialEq, Eq)] diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 1d5690a8197..131394f2a65 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -757,6 +757,27 @@ mod snapshot { "); } + #[test] + fn build_compiler_tools() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx + .config("build") + .stage(2) + .args(&["--set", "rust.llvm-bitcode-linker=true"]) + .render_steps(), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 1 -> LlvmBitcodeLinker 2 + [build] rustc 1 -> std 1 + [build] rustc 1 -> rustc 2 + [build] rustc 2 -> LlvmBitcodeLinker 3 + [build] rustc 2 -> std 2 + [build] rustdoc 1 + " + ); + } + #[test] fn build_library_no_explicit_stage() { let ctx = TestCtx::new(); @@ -1040,6 +1061,7 @@ mod snapshot { [build] rustc 0 -> cargo-clippy 1 [build] rustc 0 -> miri 1 [build] rustc 0 -> cargo-miri 1 + [build] rustc 1 -> LlvmBitcodeLinker 2 "); } @@ -1230,6 +1252,7 @@ mod snapshot { [build] rustc 0 -> cargo-clippy 1 [build] rustc 0 -> miri 1 [build] rustc 0 -> cargo-miri 1 + [build] rustc 1 -> LlvmBitcodeLinker 2 "); } -- cgit 1.4.1-3-g733a5 From b14323aedcfef75bde97aff4f2562dcab8e9a3cd Mon Sep 17 00:00:00 2001 From: Jakub Beránek Date: Tue, 8 Jul 2025 11:49:08 +0200 Subject: Also test `LldWrapper` and remove `llvm-config` override from tests --- src/bootstrap/src/core/build_steps/tool.rs | 7 +++++++ src/bootstrap/src/core/builder/tests.rs | 4 +++- src/bootstrap/src/utils/tests/mod.rs | 2 -- 3 files changed, 10 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index a7f6a2c7bae..5de1b472d79 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -910,6 +910,13 @@ impl Step for LldWrapper { tool_result } + + fn metadata(&self) -> Option { + Some( + StepMetadata::build("LldWrapper", self.target_compiler.host) + .built_by(self.build_compiler), + ) + } } #[derive(Debug, Clone, Hash, PartialEq, Eq)] diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 131394f2a65..b240d670b6b 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -764,13 +764,15 @@ mod snapshot { ctx .config("build") .stage(2) - .args(&["--set", "rust.llvm-bitcode-linker=true"]) + .args(&["--set", "rust.lld=true", "--set", "rust.llvm-bitcode-linker=true"]) .render_steps(), @r" [build] llvm [build] rustc 0 -> rustc 1 + [build] rustc 0 -> LldWrapper 1 [build] rustc 1 -> LlvmBitcodeLinker 2 [build] rustc 1 -> std 1 [build] rustc 1 -> rustc 2 + [build] rustc 1 -> LldWrapper 2 [build] rustc 2 -> LlvmBitcodeLinker 3 [build] rustc 2 -> std 2 [build] rustdoc 1 diff --git a/src/bootstrap/src/utils/tests/mod.rs b/src/bootstrap/src/utils/tests/mod.rs index 59c169b0f2b..5b568c1df5b 100644 --- a/src/bootstrap/src/utils/tests/mod.rs +++ b/src/bootstrap/src/utils/tests/mod.rs @@ -96,8 +96,6 @@ impl ConfigBuilder { // in-tree LLVM from sources. self.args.push("--set".to_string()); self.args.push("llvm.download-ci-llvm=false".to_string()); - self.args.push("--set".to_string()); - self.args.push(format!("target.'{}'.llvm-config=false", get_host_target())); // Do not mess with the local rustc checkout build directory self.args.push("--build-dir".to_string()); -- cgit 1.4.1-3-g733a5 From 889638a8b3591d71bdec38efbac27469f5019b49 Mon Sep 17 00:00:00 2001 From: Rémy Rakic Date: Tue, 8 Jul 2025 09:19:58 +0000 Subject: document new stable flags, with x64 linux implementation notes --- src/doc/rustc/src/codegen-options/index.md | 59 ++++++++++++++++++++-- .../src/compiler-flags/codegen-options.md | 8 +-- .../src/compiler-flags/linker-features.md | 35 ------------- 3 files changed, 59 insertions(+), 43 deletions(-) delete mode 100644 src/doc/unstable-book/src/compiler-flags/linker-features.md (limited to 'src') diff --git a/src/doc/rustc/src/codegen-options/index.md b/src/doc/rustc/src/codegen-options/index.md index bb109adf76f..07eafdf4c4c 100644 --- a/src/doc/rustc/src/codegen-options/index.md +++ b/src/doc/rustc/src/codegen-options/index.md @@ -235,15 +235,33 @@ coverage measurement. Its use is not recommended. ## link-self-contained -On `windows-gnu`, `linux-musl`, and `wasi` targets, this flag controls whether the -linker will use libraries and objects shipped with Rust instead of those in the system. -It takes one of the following values: +This flag controls whether the linker will use libraries and objects shipped with Rust instead of +those in the system. It also controls which binary is used for the linker itself. This allows +overriding cases when detection fails or the user wants to use shipped libraries. + +You can enable or disable the usage of any self-contained components using one of the following values: * no value: rustc will use heuristic to disable self-contained mode if system has necessary tools. * `y`, `yes`, `on`, `true`: use only libraries/objects shipped with Rust. * `n`, `no`, `off` or `false`: rely on the user or the linker to provide non-Rust libraries/objects. -This allows overriding cases when detection fails or user wants to use shipped libraries. +It is also possible to enable or disable specific self-contained components in a more granular way. +You can pass a comma-separated list of self-contained components, individually enabled +(`+component`) or disabled (`-component`). + +Currently, only the `linker` granular option is stabilized, and only on the `x86_64-unknown-linux-gnu` target: +- `linker`: toggle the usage of self-contained linker binaries (linker, dlltool, and their necessary libraries) + +Note that only the `-linker` opt-out is stable on the `x86_64-unknown-linux-gnu` target: `+linker` is +already the default on this target. + +#### Implementation notes + +On the `x86_64-unknown-linux-gnu` target, when using the default linker flavor (using `cc` as the +linker driver) and linker features (to try using `lld`), `rustc` will try to use the self-contained +linker by passing a `-B /path/to/sysroot/` link argument to the driver to find `rust-lld` in the +sysroot. For backwards-compatibility, and to limit name and `PATH` collisions, this is done using a +shim executable (the `lld-wrapper` tool) that forwards execution to the `rust-lld` executable itself. ## linker @@ -256,6 +274,39 @@ Note that on Unix-like targets (for example, `*-unknown-linux-gnu` or `*-unknown the C compiler (for example `cc` or `clang`) is used as the "linker" here, serving as a linker driver. It will invoke the actual linker with all the necessary flags to be able to link against the system libraries like libc. +## linker-features + +The `-Clinker-features` flag allows enabling or disabling specific features used during linking. + +These feature flags are a flexible extension mechanism that is complementary to linker flavors, +designed to avoid the combinatorial explosion of having to create a new set of flavors for each +linker feature we'd want to use. + +The flag accepts a comma-separated list of features, individually enabled (`+feature`) or disabled +(`-feature`). + +Currently only one is stable, and only on the `x86_64-unknown-linux-gnu` target: +- `lld`: to toggle trying to use the lld linker, either the system-installed binary, or the self-contained + `rust-lld` linker (via the [`-Clink-self-contained=+linker`](#link-self-contained) flag). + +For example, use: +- `-Clinker-features=+lld` to opt into using the `lld` linker, when possible (see the Implementation notes below) +- `-Clinker-features=-lld` to opt out instead, for targets where it is configured as the default linker + +Note that only the `-lld` opt-out is stable on the `x86_64-unknown-linux-gnu` target: `+lld` is +already the default on this target. + +#### Implementation notes + +On the `x86_64-unknown-linux-gnu` target, when using the default linker flavor (using `cc` as the +linker driver), `rustc` will try to use lld by passing a `-fuse-ld=lld` link argument to the driver. +`rustc` will also try to detect if that _causes_ an error during linking (for example, if GCC is too +old to understand the flag, and returns an error) and will then retry linking without this argument, +as a fallback. + +If the user _also_ passes a `-Clink-arg=-fuse-ld=$value`, both will be given to the linker +driver but the user's will be passed last, and would generally have priority over `rustc`'s. + ## linker-flavor This flag controls the linker flavor used by `rustc`. If a linker is given with diff --git a/src/doc/unstable-book/src/compiler-flags/codegen-options.md b/src/doc/unstable-book/src/compiler-flags/codegen-options.md index cc51554706d..f927e5c439c 100644 --- a/src/doc/unstable-book/src/compiler-flags/codegen-options.md +++ b/src/doc/unstable-book/src/compiler-flags/codegen-options.md @@ -51,10 +51,10 @@ instead of those in the system. The stable boolean values for this flag are coar - `mingw`: other MinGW libs and Windows import libs Out of the above self-contained linking components, `linker` is the only one currently implemented -(beyond parsing the CLI options). +(beyond parsing the CLI options) and stabilized. It refers to the LLD linker, built from the same LLVM revision used by rustc (named `rust-lld` to avoid naming conflicts), that is distributed via `rustup` with the compiler (and is used by default -for the wasm targets). One can also opt-in to use it by combining this flag with an appropriate -linker flavor: for example, `-Clinker-flavor=gnu-lld-cc -Clink-self-contained=+linker` will use the -toolchain's `rust-lld` as the linker. +for the wasm targets). One can also opt into using it by combining this flag with the appropriate +linker feature: for example, `-Clinker-features=+lld -Clink-self-contained=+linker` will use the +toolchain's `rust-lld` as the linker instead of the system's lld with `-Clinker-features=+lld` only. diff --git a/src/doc/unstable-book/src/compiler-flags/linker-features.md b/src/doc/unstable-book/src/compiler-flags/linker-features.md deleted file mode 100644 index 643fcf7c6d7..00000000000 --- a/src/doc/unstable-book/src/compiler-flags/linker-features.md +++ /dev/null @@ -1,35 +0,0 @@ -# `linker-features` - --------------------- - -The `-Zlinker-features` compiler flag allows enabling or disabling specific features used during -linking, and is intended to be stabilized under the codegen options as `-Clinker-features`. - -These feature flags are a flexible extension mechanism that is complementary to linker flavors, -designed to avoid the combinatorial explosion of having to create a new set of flavors for each -linker feature we'd want to use. - -For example, this design allows: -- default feature sets for principal flavors, or for specific targets. -- flavor-specific features: for example, clang offers automatic cross-linking with `--target`, which - gcc-style compilers don't support. The *flavor* is still a C/C++ compiler, and we don't want to - multiply the number of flavors for this use-case. Instead, we can have a single `+target` feature. -- umbrella features: for example, if clang accumulates more features in the future than just the - `+target` above. That could be modeled as `+clang`. -- niche features for resolving specific issues: for example, on Apple targets the linker flag - implementing the `as-needed` native link modifier (#99424) is only possible on sufficiently recent - linker versions. -- still allows for discovery and automation, for example via feature detection. This can be useful - in exotic environments/build systems. - -The flag accepts a comma-separated list of features, individually enabled (`+features`) or disabled -(`-features`), though currently only one is exposed on the CLI: -- `lld`: to toggle using the lld linker, either the system-installed binary, or the self-contained - `rust-lld` linker. - -As described above, this list is intended to grow in the future. - -One of the most common uses of this flag will be to toggle self-contained linking with `rust-lld` on -and off: `-Clinker-features=+lld -Clink-self-contained=+linker` will use the toolchain's `rust-lld` -as the linker. Inversely, `-Clinker-features=-lld` would opt out of that, if the current target had -self-contained linking enabled by default. -- cgit 1.4.1-3-g733a5 From 3ba8e330f9960a52b2c8ca10c8cba425514919f9 Mon Sep 17 00:00:00 2001 From: Aleksey Kliger Date: Tue, 8 Jul 2025 07:34:51 -0400 Subject: Rewrite for clarity move common code to a helper function Co-Authored-By: Kobzol --- src/bootstrap/configure.py | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/bootstrap/configure.py b/src/bootstrap/configure.py index 94e02f942dc..86208b94261 100755 --- a/src/bootstrap/configure.py +++ b/src/bootstrap/configure.py @@ -744,22 +744,24 @@ def write_uncommented(target, f): A block is a sequence of non-empty lines separated by empty lines. """ block = [] - is_comment = True + + def flush(last): + # If the block is entiry made of comments, ignore it + entire_block_comments = all(ln.startswith("#") or ln == "" for ln in block) + if not entire_block_comments and len(block) > 0: + for line in block: + f.write(line + "\n") + # Required to output a newline before the start of a new section + if last: + f.write("\n") + block.clear() for line in target: block.append(line) if len(line) == 0: - if not is_comment: - for ln in block: - f.write(ln + "\n") - block = [] - is_comment = True - continue - is_comment = is_comment and line.startswith("#") - # Write the last accumulated block - if len(block) > 0 and not is_comment: - for ln in block: - f.write(ln + "\n") + flush(last=False) + + flush(last=True) return f -- cgit 1.4.1-3-g733a5 From 961bac0b197bf5ded0da8faf1395c96598923b20 Mon Sep 17 00:00:00 2001 From: Jakub Beránek Date: Tue, 8 Jul 2025 15:06:27 +0200 Subject: Add cross-compilation tool test --- src/bootstrap/src/core/builder/tests.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'src') diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index b240d670b6b..bbcb58fca14 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -780,6 +780,35 @@ mod snapshot { ); } + #[test] + fn build_compiler_tools_cross() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx + .config("build") + .stage(2) + .args(&["--set", "rust.lld=true", "--set", "rust.llvm-bitcode-linker=true"]) + .hosts(&[TEST_TRIPLE_1]) + .render_steps(), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 0 -> LldWrapper 1 + [build] rustc 1 -> LlvmBitcodeLinker 2 + [build] rustc 1 -> std 1 + [build] rustc 1 -> rustc 2 + [build] rustc 1 -> LldWrapper 2 + [build] rustc 2 -> LlvmBitcodeLinker 3 + [build] rustc 1 -> std 1 + [build] rustc 2 -> std 2 + [build] llvm + [build] rustc 1 -> rustc 2 + [build] rustc 1 -> LldWrapper 2 + [build] rustc 2 -> LlvmBitcodeLinker 3 + [build] rustdoc 1 + " + ); + } + #[test] fn build_library_no_explicit_stage() { let ctx = TestCtx::new(); -- cgit 1.4.1-3-g733a5 From e5f7d4d783c1567ddc16e02091bae8bacfca1418 Mon Sep 17 00:00:00 2001 From: Stypox Date: Tue, 8 Jul 2025 15:37:01 +0200 Subject: Implement enter_trace_span() in MiriMachine --- src/tools/miri/src/machine.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index 693b8916d89..35399dbf4cb 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -1014,8 +1014,6 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> { const PANIC_ON_ALLOC_FAIL: bool = false; - const TRACING_ENABLED: bool = cfg!(feature = "tracing"); - #[inline(always)] fn enforce_alignment(ecx: &MiriInterpCx<'tcx>) -> bool { ecx.machine.check_alignment != AlignmentCheck::None @@ -1827,6 +1825,16 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> { #[cfg(not(target_os = "linux"))] MiriAllocParams::Global } + + fn enter_trace_span(span: impl FnOnce() -> tracing::Span) -> impl EnteredTraceSpan { + #[cfg(feature = "tracing")] + { span().entered() } + #[cfg(not(feature = "tracing"))] + { + let _ = span; // so we avoid the "unused variable" warning + () + } + } } /// Trait for callbacks handling asynchronous machine operations. -- cgit 1.4.1-3-g733a5 From 66bc2340876746365870a61b3ee3f769713c7525 Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 3 Jul 2025 13:21:35 -0500 Subject: tidy: refactor --extra-checks parsing --- src/tools/tidy/src/ext_tool_checks.rs | 125 ++++++++++++++++++++++++++++++---- 1 file changed, 111 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/tools/tidy/src/ext_tool_checks.rs b/src/tools/tidy/src/ext_tool_checks.rs index d2da63a9703..c552cf8e400 100644 --- a/src/tools/tidy/src/ext_tool_checks.rs +++ b/src/tools/tidy/src/ext_tool_checks.rs @@ -20,6 +20,7 @@ use std::ffi::OsStr; use std::path::{Path, PathBuf}; use std::process::Command; +use std::str::FromStr; use std::{fmt, fs, io}; const MIN_PY_REV: (u32, u32) = (3, 9); @@ -61,25 +62,38 @@ fn check_impl( // Split comma-separated args up let lint_args = match extra_checks { - Some(s) => s.strip_prefix("--extra-checks=").unwrap().split(',').collect(), + Some(s) => s + .strip_prefix("--extra-checks=") + .unwrap() + .split(',') + .map(|s| { + if s == "spellcheck:fix" { + eprintln!("warning: `spellcheck:fix` is no longer valid, use `--extra=check=spellcheck --bless`"); + } + (ExtraCheckArg::from_str(s), s) + }) + .filter_map(|(res, src)| match res { + Ok(x) => Some(x), + Err(err) => { + eprintln!("warning: bad extra check argument {src:?}: {err:?}"); + None + } + }) + .collect(), None => vec![], }; - if lint_args.contains(&"spellcheck:fix") { - return Err(Error::Generic( - "`spellcheck:fix` is no longer valid, use `--extra=check=spellcheck --bless`" - .to_string(), - )); + macro_rules! extra_check { + ($lang:ident, $kind:ident) => { + lint_args.iter().any(|arg| arg.matches(ExtraCheckLang::$lang, ExtraCheckKind::$kind)) + }; } - let python_all = lint_args.contains(&"py"); - let python_lint = lint_args.contains(&"py:lint") || python_all; - let python_fmt = lint_args.contains(&"py:fmt") || python_all; - let shell_all = lint_args.contains(&"shell"); - let shell_lint = lint_args.contains(&"shell:lint") || shell_all; - let cpp_all = lint_args.contains(&"cpp"); - let cpp_fmt = lint_args.contains(&"cpp:fmt") || cpp_all; - let spellcheck = lint_args.contains(&"spellcheck"); + let python_lint = extra_check!(Py, Lint); + let python_fmt = extra_check!(Py, Fmt); + let shell_lint = extra_check!(Shell, Lint); + let cpp_fmt = extra_check!(Cpp, Fmt); + let spellcheck = extra_check!(Spellcheck, None); let mut py_path = None; @@ -638,3 +652,86 @@ impl From for Error { Self::Io(value) } } + +#[derive(Debug)] +enum ExtraCheckParseError { + #[allow(dead_code, reason = "shown through Debug")] + UnknownKind(String), + #[allow(dead_code)] + UnknownLang(String), + /// Too many `:` + TooManyParts, + /// Tried to parse the empty string + Empty, +} + +struct ExtraCheckArg { + lang: ExtraCheckLang, + /// None = run all extra checks for the given lang + kind: Option, +} + +impl ExtraCheckArg { + fn matches(&self, lang: ExtraCheckLang, kind: ExtraCheckKind) -> bool { + self.lang == lang && self.kind.map(|k| k == kind).unwrap_or(true) + } +} + +impl FromStr for ExtraCheckArg { + type Err = ExtraCheckParseError; + + fn from_str(s: &str) -> Result { + let mut parts = s.split(':'); + let Some(first) = parts.next() else { + return Err(ExtraCheckParseError::Empty); + }; + let second = parts.next(); + if parts.next().is_some() { + return Err(ExtraCheckParseError::TooManyParts); + } + Ok(Self { lang: first.parse()?, kind: second.map(|s| s.parse()).transpose()? }) + } +} + +#[derive(PartialEq, Copy, Clone)] +enum ExtraCheckLang { + Py, + Shell, + Cpp, + Spellcheck, +} + +impl FromStr for ExtraCheckLang { + type Err = ExtraCheckParseError; + + fn from_str(s: &str) -> Result { + Ok(match s { + "py" => Self::Py, + "shell" => Self::Shell, + "cpp" => Self::Cpp, + "spellcheck" => Self::Spellcheck, + _ => return Err(ExtraCheckParseError::UnknownLang(s.to_string())), + }) + } +} + +#[derive(PartialEq, Copy, Clone)] +enum ExtraCheckKind { + Lint, + Fmt, + /// Never parsed, but used as a placeholder for + /// langs that never have a specific kind. + None, +} + +impl FromStr for ExtraCheckKind { + type Err = ExtraCheckParseError; + + fn from_str(s: &str) -> Result { + Ok(match s { + "lint" => Self::Lint, + "fmt" => Self::Fmt, + _ => return Err(ExtraCheckParseError::UnknownKind(s.to_string())), + }) + } +} -- cgit 1.4.1-3-g733a5 From 7c8a6d978bb47827eeef15448ca95f82af32c381 Mon Sep 17 00:00:00 2001 From: Aleksey Kliger Date: Tue, 8 Jul 2025 14:18:07 -0400 Subject: Spelling --- src/bootstrap/configure.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/bootstrap/configure.py b/src/bootstrap/configure.py index 86208b94261..b05a5cc8b81 100755 --- a/src/bootstrap/configure.py +++ b/src/bootstrap/configure.py @@ -746,7 +746,7 @@ def write_uncommented(target, f): block = [] def flush(last): - # If the block is entiry made of comments, ignore it + # If the block is entirely made of comments, ignore it entire_block_comments = all(ln.startswith("#") or ln == "" for ln in block) if not entire_block_comments and len(block) > 0: for line in block: -- cgit 1.4.1-3-g733a5 From 9eb180541ac58409b1b2c82ad86e4078bcbb741b Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 3 Jul 2025 13:37:20 -0500 Subject: tidy: factor out change detection logic and make it more robust now does proper parsing of git's output and falls back to assuming all files are modified if `git` doesn't work. accepts a closure so extensions can be checked. --- src/tools/tidy/src/lib.rs | 26 ++++++++++++++++++++++++++ src/tools/tidy/src/rustdoc_json.rs | 20 ++++---------------- 2 files changed, 30 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/tools/tidy/src/lib.rs b/src/tools/tidy/src/lib.rs index 237737f0f16..90111079ecd 100644 --- a/src/tools/tidy/src/lib.rs +++ b/src/tools/tidy/src/lib.rs @@ -124,6 +124,32 @@ pub fn git_diff>(base_commit: &str, extra_arg: S) -> Option bool) -> bool { + match crate::git_diff(&base_commit, "--name-status") { + Some(output) => { + let modified_files = output.lines().filter_map(|ln| { + let (status, name) = ln + .trim_end() + .split_once('\t') + .expect("bad format from `git diff --name-status`"); + if status == "M" { Some(name) } else { None } + }); + for modified_file in modified_files { + if pred(modified_file) { + return true; + } + } + false + } + None => { + eprintln!("warning: failed to run `git diff` to check for changes"); + eprintln!("warning: assuming all files are modified"); + true + } + } +} + pub mod alphabetical; pub mod bins; pub mod debug_artifacts; diff --git a/src/tools/tidy/src/rustdoc_json.rs b/src/tools/tidy/src/rustdoc_json.rs index dfbb35d69f1..da6f51c2a22 100644 --- a/src/tools/tidy/src/rustdoc_json.rs +++ b/src/tools/tidy/src/rustdoc_json.rs @@ -14,22 +14,10 @@ pub fn check(src_path: &Path, ci_info: &crate::CiInfo, bad: &mut bool) { }; // First we check that `src/rustdoc-json-types` was modified. - match crate::git_diff(&base_commit, "--name-status") { - Some(output) => { - if !output - .lines() - .any(|line| line.starts_with("M") && line.contains(RUSTDOC_JSON_TYPES)) - { - // `rustdoc-json-types` was not modified so nothing more to check here. - println!("`rustdoc-json-types` was not modified."); - return; - } - } - None => { - *bad = true; - eprintln!("error: failed to run `git diff` in rustdoc_json check"); - return; - } + if !crate::files_modified(base_commit, |p| p == RUSTDOC_JSON_TYPES) { + // `rustdoc-json-types` was not modified so nothing more to check here. + println!("`rustdoc-json-types` was not modified."); + return; } // Then we check that if `FORMAT_VERSION` was updated, the `Latest feature:` was also updated. match crate::git_diff(&base_commit, src_path.join("rustdoc-json-types")) { -- cgit 1.4.1-3-g733a5 From 4a6f6977f98026a9359a3b168b6d50045b1c07a8 Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 3 Jul 2025 14:06:32 -0500 Subject: tidy: update files_modified to take CiInfo --- src/tools/tidy/src/lib.rs | 8 ++++++-- src/tools/tidy/src/rustdoc_json.rs | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/tools/tidy/src/lib.rs b/src/tools/tidy/src/lib.rs index 90111079ecd..062cfe7b597 100644 --- a/src/tools/tidy/src/lib.rs +++ b/src/tools/tidy/src/lib.rs @@ -124,8 +124,12 @@ pub fn git_diff>(base_commit: &str, extra_arg: S) -> Option bool) -> bool { +/// Returns true if any modified file matches the predicate, if we are in CI, or if unable to list modified files. +pub fn files_modified(ci_info: &CiInfo, pred: impl Fn(&str) -> bool) -> bool { + let Some(base_commit) = &ci_info.base_commit else { + eprintln!("No base commit, assuming all files are modified"); + return true; + }; match crate::git_diff(&base_commit, "--name-status") { Some(output) => { let modified_files = output.lines().filter_map(|ln| { diff --git a/src/tools/tidy/src/rustdoc_json.rs b/src/tools/tidy/src/rustdoc_json.rs index da6f51c2a22..19b8e79ec33 100644 --- a/src/tools/tidy/src/rustdoc_json.rs +++ b/src/tools/tidy/src/rustdoc_json.rs @@ -14,7 +14,7 @@ pub fn check(src_path: &Path, ci_info: &crate::CiInfo, bad: &mut bool) { }; // First we check that `src/rustdoc-json-types` was modified. - if !crate::files_modified(base_commit, |p| p == RUSTDOC_JSON_TYPES) { + if !crate::files_modified(ci_info, |p| p == RUSTDOC_JSON_TYPES) { // `rustdoc-json-types` was not modified so nothing more to check here. println!("`rustdoc-json-types` was not modified."); return; -- cgit 1.4.1-3-g733a5 From 64456e07b8e8550376d5136600fb0c59178df6a0 Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 3 Jul 2025 14:27:47 -0500 Subject: tidy: add `auto:` prefix to --extra-checks syntax currently this just uses a very simple extension-based heirustic. --- src/bootstrap/src/core/config/flags.rs | 5 ++- src/etc/completions/x.fish | 2 +- src/etc/completions/x.ps1 | 2 +- src/etc/completions/x.py.fish | 2 +- src/etc/completions/x.py.ps1 | 2 +- src/etc/completions/x.py.zsh | 2 +- src/etc/completions/x.zsh | 2 +- src/tools/tidy/src/ext_tool_checks.rs | 60 +++++++++++++++++++++++++++------- src/tools/tidy/src/main.rs | 10 +++++- 9 files changed, 67 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/bootstrap/src/core/config/flags.rs b/src/bootstrap/src/core/config/flags.rs index bfc06f90d4f..19e0d3413bb 100644 --- a/src/bootstrap/src/core/config/flags.rs +++ b/src/bootstrap/src/core/config/flags.rs @@ -383,7 +383,10 @@ pub enum Subcommand { bless: bool, #[arg(long)] /// comma-separated list of other files types to check (accepts py, py:lint, - /// py:fmt, shell, shell:lint, cpp, cpp:fmt, spellcheck, spellcheck:fix) + /// py:fmt, shell, shell:lint, cpp, cpp:fmt, spellcheck) + /// + /// Any argument can be prefixed with "auto:" to only run if + /// relevant files are modified (eg. "auto:py"). extra_checks: Option, #[arg(long)] /// rerun tests even if the inputs are unchanged diff --git a/src/etc/completions/x.fish b/src/etc/completions/x.fish index 69bd525a312..3009dd85e93 100644 --- a/src/etc/completions/x.fish +++ b/src/etc/completions/x.fish @@ -293,7 +293,7 @@ complete -c x -n "__fish_x_using_subcommand doc" -l skip-std-check-if-no-downloa complete -c x -n "__fish_x_using_subcommand doc" -s h -l help -d 'Print help (see more with \'--help\')' complete -c x -n "__fish_x_using_subcommand test" -l test-args -d 'extra arguments to be passed for the test tool being used (e.g. libtest, compiletest or rustdoc)' -r complete -c x -n "__fish_x_using_subcommand test" -l compiletest-rustc-args -d 'extra options to pass the compiler when running compiletest tests' -r -complete -c x -n "__fish_x_using_subcommand test" -l extra-checks -d 'comma-separated list of other files types to check (accepts py, py:lint, py:fmt, shell, shell:lint, cpp, cpp:fmt, spellcheck, spellcheck:fix)' -r +complete -c x -n "__fish_x_using_subcommand test" -l extra-checks -d 'comma-separated list of other files types to check (accepts py, py:lint, py:fmt, shell, shell:lint, cpp, cpp:fmt, spellcheck)' -r complete -c x -n "__fish_x_using_subcommand test" -l compare-mode -d 'mode describing what file the actual ui output will be compared to' -r complete -c x -n "__fish_x_using_subcommand test" -l pass -d 'force {check,build,run}-pass tests to this mode' -r complete -c x -n "__fish_x_using_subcommand test" -l run -d 'whether to execute run-* tests' -r diff --git a/src/etc/completions/x.ps1 b/src/etc/completions/x.ps1 index 7b142ba97ce..8002ec31592 100644 --- a/src/etc/completions/x.ps1 +++ b/src/etc/completions/x.ps1 @@ -339,7 +339,7 @@ Register-ArgumentCompleter -Native -CommandName 'x' -ScriptBlock { 'x;test' { [CompletionResult]::new('--test-args', '--test-args', [CompletionResultType]::ParameterName, 'extra arguments to be passed for the test tool being used (e.g. libtest, compiletest or rustdoc)') [CompletionResult]::new('--compiletest-rustc-args', '--compiletest-rustc-args', [CompletionResultType]::ParameterName, 'extra options to pass the compiler when running compiletest tests') - [CompletionResult]::new('--extra-checks', '--extra-checks', [CompletionResultType]::ParameterName, 'comma-separated list of other files types to check (accepts py, py:lint, py:fmt, shell, shell:lint, cpp, cpp:fmt, spellcheck, spellcheck:fix)') + [CompletionResult]::new('--extra-checks', '--extra-checks', [CompletionResultType]::ParameterName, 'comma-separated list of other files types to check (accepts py, py:lint, py:fmt, shell, shell:lint, cpp, cpp:fmt, spellcheck)') [CompletionResult]::new('--compare-mode', '--compare-mode', [CompletionResultType]::ParameterName, 'mode describing what file the actual ui output will be compared to') [CompletionResult]::new('--pass', '--pass', [CompletionResultType]::ParameterName, 'force {check,build,run}-pass tests to this mode') [CompletionResult]::new('--run', '--run', [CompletionResultType]::ParameterName, 'whether to execute run-* tests') diff --git a/src/etc/completions/x.py.fish b/src/etc/completions/x.py.fish index e982cde634f..4766a5ee0c7 100644 --- a/src/etc/completions/x.py.fish +++ b/src/etc/completions/x.py.fish @@ -293,7 +293,7 @@ complete -c x.py -n "__fish_x.py_using_subcommand doc" -l skip-std-check-if-no-d complete -c x.py -n "__fish_x.py_using_subcommand doc" -s h -l help -d 'Print help (see more with \'--help\')' complete -c x.py -n "__fish_x.py_using_subcommand test" -l test-args -d 'extra arguments to be passed for the test tool being used (e.g. libtest, compiletest or rustdoc)' -r complete -c x.py -n "__fish_x.py_using_subcommand test" -l compiletest-rustc-args -d 'extra options to pass the compiler when running compiletest tests' -r -complete -c x.py -n "__fish_x.py_using_subcommand test" -l extra-checks -d 'comma-separated list of other files types to check (accepts py, py:lint, py:fmt, shell, shell:lint, cpp, cpp:fmt, spellcheck, spellcheck:fix)' -r +complete -c x.py -n "__fish_x.py_using_subcommand test" -l extra-checks -d 'comma-separated list of other files types to check (accepts py, py:lint, py:fmt, shell, shell:lint, cpp, cpp:fmt, spellcheck)' -r complete -c x.py -n "__fish_x.py_using_subcommand test" -l compare-mode -d 'mode describing what file the actual ui output will be compared to' -r complete -c x.py -n "__fish_x.py_using_subcommand test" -l pass -d 'force {check,build,run}-pass tests to this mode' -r complete -c x.py -n "__fish_x.py_using_subcommand test" -l run -d 'whether to execute run-* tests' -r diff --git a/src/etc/completions/x.py.ps1 b/src/etc/completions/x.py.ps1 index f4b26fac0bc..1aff3c433b4 100644 --- a/src/etc/completions/x.py.ps1 +++ b/src/etc/completions/x.py.ps1 @@ -339,7 +339,7 @@ Register-ArgumentCompleter -Native -CommandName 'x.py' -ScriptBlock { 'x.py;test' { [CompletionResult]::new('--test-args', '--test-args', [CompletionResultType]::ParameterName, 'extra arguments to be passed for the test tool being used (e.g. libtest, compiletest or rustdoc)') [CompletionResult]::new('--compiletest-rustc-args', '--compiletest-rustc-args', [CompletionResultType]::ParameterName, 'extra options to pass the compiler when running compiletest tests') - [CompletionResult]::new('--extra-checks', '--extra-checks', [CompletionResultType]::ParameterName, 'comma-separated list of other files types to check (accepts py, py:lint, py:fmt, shell, shell:lint, cpp, cpp:fmt, spellcheck, spellcheck:fix)') + [CompletionResult]::new('--extra-checks', '--extra-checks', [CompletionResultType]::ParameterName, 'comma-separated list of other files types to check (accepts py, py:lint, py:fmt, shell, shell:lint, cpp, cpp:fmt, spellcheck)') [CompletionResult]::new('--compare-mode', '--compare-mode', [CompletionResultType]::ParameterName, 'mode describing what file the actual ui output will be compared to') [CompletionResult]::new('--pass', '--pass', [CompletionResultType]::ParameterName, 'force {check,build,run}-pass tests to this mode') [CompletionResult]::new('--run', '--run', [CompletionResultType]::ParameterName, 'whether to execute run-* tests') diff --git a/src/etc/completions/x.py.zsh b/src/etc/completions/x.py.zsh index 8fc4f052252..77f995c1704 100644 --- a/src/etc/completions/x.py.zsh +++ b/src/etc/completions/x.py.zsh @@ -338,7 +338,7 @@ _arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" : \ '*--test-args=[extra arguments to be passed for the test tool being used (e.g. libtest, compiletest or rustdoc)]:ARGS:_default' \ '*--compiletest-rustc-args=[extra options to pass the compiler when running compiletest tests]:ARGS:_default' \ -'--extra-checks=[comma-separated list of other files types to check (accepts py, py\:lint, py\:fmt, shell, shell\:lint, cpp, cpp\:fmt, spellcheck, spellcheck\:fix)]:EXTRA_CHECKS:_default' \ +'--extra-checks=[comma-separated list of other files types to check (accepts py, py\:lint, py\:fmt, shell, shell\:lint, cpp, cpp\:fmt, spellcheck)]:EXTRA_CHECKS:_default' \ '--compare-mode=[mode describing what file the actual ui output will be compared to]:COMPARE MODE:_default' \ '--pass=[force {check,build,run}-pass tests to this mode]:check | build | run:_default' \ '--run=[whether to execute run-* tests]:auto | always | never:_default' \ diff --git a/src/etc/completions/x.zsh b/src/etc/completions/x.zsh index c495e8318ba..6c6d7b3f49f 100644 --- a/src/etc/completions/x.zsh +++ b/src/etc/completions/x.zsh @@ -338,7 +338,7 @@ _arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" : \ '*--test-args=[extra arguments to be passed for the test tool being used (e.g. libtest, compiletest or rustdoc)]:ARGS:_default' \ '*--compiletest-rustc-args=[extra options to pass the compiler when running compiletest tests]:ARGS:_default' \ -'--extra-checks=[comma-separated list of other files types to check (accepts py, py\:lint, py\:fmt, shell, shell\:lint, cpp, cpp\:fmt, spellcheck, spellcheck\:fix)]:EXTRA_CHECKS:_default' \ +'--extra-checks=[comma-separated list of other files types to check (accepts py, py\:lint, py\:fmt, shell, shell\:lint, cpp, cpp\:fmt, spellcheck)]:EXTRA_CHECKS:_default' \ '--compare-mode=[mode describing what file the actual ui output will be compared to]:COMPARE MODE:_default' \ '--pass=[force {check,build,run}-pass tests to this mode]:check | build | run:_default' \ '--run=[whether to execute run-* tests]:auto | always | never:_default' \ diff --git a/src/tools/tidy/src/ext_tool_checks.rs b/src/tools/tidy/src/ext_tool_checks.rs index c552cf8e400..be2f585a6d8 100644 --- a/src/tools/tidy/src/ext_tool_checks.rs +++ b/src/tools/tidy/src/ext_tool_checks.rs @@ -23,6 +23,8 @@ use std::process::Command; use std::str::FromStr; use std::{fmt, fs, io}; +use crate::CiInfo; + const MIN_PY_REV: (u32, u32) = (3, 9); const MIN_PY_REV_STR: &str = "≥3.9"; @@ -37,15 +39,18 @@ const RUFF_CONFIG_PATH: &[&str] = &["src", "tools", "tidy", "config", "ruff.toml const RUFF_CACHE_PATH: &[&str] = &["cache", "ruff_cache"]; const PIP_REQ_PATH: &[&str] = &["src", "tools", "tidy", "config", "requirements.txt"]; +const SPELLCHECK_DIRS: &[&str] = &["compiler", "library", "src/bootstrap", "src/librustdoc"]; + pub fn check( root_path: &Path, outdir: &Path, + ci_info: &CiInfo, bless: bool, extra_checks: Option<&str>, pos_args: &[String], bad: &mut bool, ) { - if let Err(e) = check_impl(root_path, outdir, bless, extra_checks, pos_args) { + if let Err(e) = check_impl(root_path, outdir, ci_info, bless, extra_checks, pos_args) { tidy_error!(bad, "{e}"); } } @@ -53,6 +58,7 @@ pub fn check( fn check_impl( root_path: &Path, outdir: &Path, + ci_info: &CiInfo, bless: bool, extra_checks: Option<&str>, pos_args: &[String], @@ -73,7 +79,13 @@ fn check_impl( (ExtraCheckArg::from_str(s), s) }) .filter_map(|(res, src)| match res { - Ok(x) => Some(x), + Ok(arg) => { + if arg.is_inactive_auto(ci_info) { + None + } else { + Some(arg) + } + } Err(err) => { eprintln!("warning: bad extra check argument {src:?}: {err:?}"); None @@ -249,14 +261,9 @@ fn check_impl( if spellcheck { let config_path = root_path.join("typos.toml"); // sync target files with .github/workflows/spellcheck.yml - let mut args = vec![ - "-c", - config_path.as_os_str().to_str().unwrap(), - "./compiler", - "./library", - "./src/bootstrap", - "./src/librustdoc", - ]; + let mut args = vec!["-c", config_path.as_os_str().to_str().unwrap()]; + + args.extend_from_slice(SPELLCHECK_DIRS); if bless { eprintln!("spellcheck files and fix"); @@ -663,9 +670,12 @@ enum ExtraCheckParseError { TooManyParts, /// Tried to parse the empty string Empty, + /// `auto` specified without lang part. + AutoRequiresLang, } struct ExtraCheckArg { + auto: bool, lang: ExtraCheckLang, /// None = run all extra checks for the given lang kind: Option, @@ -675,21 +685,47 @@ impl ExtraCheckArg { fn matches(&self, lang: ExtraCheckLang, kind: ExtraCheckKind) -> bool { self.lang == lang && self.kind.map(|k| k == kind).unwrap_or(true) } + + /// Returns `true` if this is an auto arg and the relevant files are not modified. + fn is_inactive_auto(&self, ci_info: &CiInfo) -> bool { + if !self.auto { + return false; + } + let ext = match self.lang { + ExtraCheckLang::Py => ".py", + ExtraCheckLang::Cpp => ".cpp", + ExtraCheckLang::Shell => ".sh", + ExtraCheckLang::Spellcheck => { + return !crate::files_modified(ci_info, |s| { + SPELLCHECK_DIRS.iter().any(|dir| Path::new(s).starts_with(dir)) + }); + } + }; + !crate::files_modified(ci_info, |s| s.ends_with(ext)) + } } impl FromStr for ExtraCheckArg { type Err = ExtraCheckParseError; fn from_str(s: &str) -> Result { + let mut auto = false; let mut parts = s.split(':'); - let Some(first) = parts.next() else { + let Some(mut first) = parts.next() else { return Err(ExtraCheckParseError::Empty); }; + if first == "auto" { + let Some(part) = parts.next() else { + return Err(ExtraCheckParseError::AutoRequiresLang); + }; + auto = true; + first = part; + } let second = parts.next(); if parts.next().is_some() { return Err(ExtraCheckParseError::TooManyParts); } - Ok(Self { lang: first.parse()?, kind: second.map(|s| s.parse()).transpose()? }) + Ok(Self { auto, lang: first.parse()?, kind: second.map(|s| s.parse()).transpose()? }) } } diff --git a/src/tools/tidy/src/main.rs b/src/tools/tidy/src/main.rs index ef6ff5c9277..1eb5485f2b8 100644 --- a/src/tools/tidy/src/main.rs +++ b/src/tools/tidy/src/main.rs @@ -173,7 +173,15 @@ fn main() { }; check!(unstable_book, &src_path, collected); - check!(ext_tool_checks, &root_path, &output_directory, bless, extra_checks, pos_args); + check!( + ext_tool_checks, + &root_path, + &output_directory, + &ci_info, + bless, + extra_checks, + pos_args + ); }); if bad.load(Ordering::Relaxed) { -- cgit 1.4.1-3-g733a5 From 6b349a41da18b0960c7a2e7bb2d8444b56f32054 Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 3 Jul 2025 14:42:42 -0500 Subject: tidy: warn when --extra-checks is passed an invalid lang:kind combo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jakub Beránek --- src/tools/tidy/src/ext_tool_checks.rs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/tools/tidy/src/ext_tool_checks.rs b/src/tools/tidy/src/ext_tool_checks.rs index be2f585a6d8..baab46752a5 100644 --- a/src/tools/tidy/src/ext_tool_checks.rs +++ b/src/tools/tidy/src/ext_tool_checks.rs @@ -39,6 +39,7 @@ const RUFF_CONFIG_PATH: &[&str] = &["src", "tools", "tidy", "config", "ruff.toml const RUFF_CACHE_PATH: &[&str] = &["cache", "ruff_cache"]; const PIP_REQ_PATH: &[&str] = &["src", "tools", "tidy", "config", "requirements.txt"]; +// this must be kept in sync with with .github/workflows/spellcheck.yml const SPELLCHECK_DIRS: &[&str] = &["compiler", "library", "src/bootstrap", "src/librustdoc"]; pub fn check( @@ -74,7 +75,7 @@ fn check_impl( .split(',') .map(|s| { if s == "spellcheck:fix" { - eprintln!("warning: `spellcheck:fix` is no longer valid, use `--extra=check=spellcheck --bless`"); + eprintln!("warning: `spellcheck:fix` is no longer valid, use `--extra-checks=spellcheck --bless`"); } (ExtraCheckArg::from_str(s), s) }) @@ -87,6 +88,7 @@ fn check_impl( } } Err(err) => { + // only warn because before bad extra checks would be silently ignored. eprintln!("warning: bad extra check argument {src:?}: {err:?}"); None } @@ -260,7 +262,6 @@ fn check_impl( if spellcheck { let config_path = root_path.join("typos.toml"); - // sync target files with .github/workflows/spellcheck.yml let mut args = vec!["-c", config_path.as_os_str().to_str().unwrap()]; args.extend_from_slice(SPELLCHECK_DIRS); @@ -666,6 +667,7 @@ enum ExtraCheckParseError { UnknownKind(String), #[allow(dead_code)] UnknownLang(String), + UnsupportedKindForLang, /// Too many `:` TooManyParts, /// Tried to parse the empty string @@ -703,6 +705,21 @@ impl ExtraCheckArg { }; !crate::files_modified(ci_info, |s| s.ends_with(ext)) } + + fn has_supported_kind(&self) -> bool { + let Some(kind) = self.kind else { + // "run all extra checks" mode is supported for all languages. + return true; + }; + use ExtraCheckKind::*; + let supported_kinds: &[_] = match self.lang { + ExtraCheckLang::Py => &[Fmt, Lint], + ExtraCheckLang::Cpp => &[Fmt], + ExtraCheckLang::Shell => &[Lint], + ExtraCheckLang::Spellcheck => &[], + }; + supported_kinds.contains(&kind) + } } impl FromStr for ExtraCheckArg { @@ -725,7 +742,12 @@ impl FromStr for ExtraCheckArg { if parts.next().is_some() { return Err(ExtraCheckParseError::TooManyParts); } - Ok(Self { auto, lang: first.parse()?, kind: second.map(|s| s.parse()).transpose()? }) + let arg = Self { auto, lang: first.parse()?, kind: second.map(|s| s.parse()).transpose()? }; + if !arg.has_supported_kind() { + return Err(ExtraCheckParseError::UnsupportedKindForLang); + } + + Ok(arg) } } -- cgit 1.4.1-3-g733a5 From 9aafc98244c0a8e0ec83203e7d17e02fcdfa0371 Mon Sep 17 00:00:00 2001 From: binarycat Date: Tue, 8 Jul 2025 12:32:33 -0500 Subject: tidy: assume all files are modified in CI --- src/tools/tidy/src/lib.rs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/tools/tidy/src/lib.rs b/src/tools/tidy/src/lib.rs index 062cfe7b597..77855392b4d 100644 --- a/src/tools/tidy/src/lib.rs +++ b/src/tools/tidy/src/lib.rs @@ -126,6 +126,10 @@ pub fn git_diff>(base_commit: &str, extra_arg: S) -> Option bool) -> bool { + if CiEnv::is_ci() { + // assume everything is modified on CI because we really don't want false positives there. + return true; + } let Some(base_commit) = &ci_info.base_commit else { eprintln!("No base commit, assuming all files are modified"); return true; -- cgit 1.4.1-3-g733a5 From 1f80fd0f23405bd5d6061684eb2259dc92116f81 Mon Sep 17 00:00:00 2001 From: binarycat Date: Tue, 8 Jul 2025 12:36:15 -0500 Subject: bootstrap: add change tracker entry for new --extra-checks=auto: feature --- src/bootstrap/src/utils/change_tracker.rs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/bootstrap/src/utils/change_tracker.rs b/src/bootstrap/src/utils/change_tracker.rs index 424f211c7d4..29591edc9cc 100644 --- a/src/bootstrap/src/utils/change_tracker.rs +++ b/src/bootstrap/src/utils/change_tracker.rs @@ -461,4 +461,9 @@ pub const CONFIG_CHANGE_HISTORY: &[ChangeInfo] = &[ severity: ChangeSeverity::Warning, summary: "`download-rustc` has been temporarily disabled for the library profile due to implementation bugs (see #142505).", }, + ChangeInfo { + change_id: 143398, + severity: ChangeSeverity::Info, + summary: "The --extra-checks flag now supports prefixing any check with `auto:` to only run it if relevant files are modified", + }, ]; -- cgit 1.4.1-3-g733a5 From 15940b8beae3d6b9e06c239c81dd2d094f1ca9c0 Mon Sep 17 00:00:00 2001 From: Marcin Kolny Date: Wed, 9 Jul 2025 07:40:01 +0100 Subject: Add a new maintainer to the wasm32-wasip1 target --- src/doc/rustc/src/platform-support/wasm32-wasip1.md | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/doc/rustc/src/platform-support/wasm32-wasip1.md b/src/doc/rustc/src/platform-support/wasm32-wasip1.md index 1e7447698bc..a8a9e550581 100644 --- a/src/doc/rustc/src/platform-support/wasm32-wasip1.md +++ b/src/doc/rustc/src/platform-support/wasm32-wasip1.md @@ -42,6 +42,7 @@ said since when this document was last updated those interested in maintaining this target are: [@alexcrichton](https://github.com/alexcrichton) +[@loganek](https://github.com/loganek) ## Requirements -- cgit 1.4.1-3-g733a5 From 8d58d5e800c0a52aef5194055c3e19e1bf345211 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 9 Jul 2025 20:02:36 +0800 Subject: Remove `run-make-support` CHANGELOG Hopelessly outdated, and this support library is purely internal. --- src/tools/run-make-support/CHANGELOG.md | 83 --------------------------------- 1 file changed, 83 deletions(-) delete mode 100644 src/tools/run-make-support/CHANGELOG.md (limited to 'src') diff --git a/src/tools/run-make-support/CHANGELOG.md b/src/tools/run-make-support/CHANGELOG.md deleted file mode 100644 index c1b7b618a92..00000000000 --- a/src/tools/run-make-support/CHANGELOG.md +++ /dev/null @@ -1,83 +0,0 @@ -# Changelog - -All notable changes to the `run_make_support` library should be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the support -library should adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) even if it's -not intended for public consumption (it's moreso to help internally, to help test writers track -changes to the support library). - -This support library will probably never reach 1.0. Please bump the minor version in `Cargo.toml` if -you make any breaking changes or other significant changes, or bump the patch version for bug fixes. - -## [0.2.0] - 2024-06-11 - -### Added - -- Added `fs_wrapper` module which provides panic-on-fail helpers for their respective `std::fs` - counterparts, the motivation is to: - - Reduce littering `.unwrap()` or `.expect()` everywhere for fs operations - - Help the test writer avoid forgetting to check fs results (even though enforced by - `-Dunused_must_use`) - - Provide better panic messages by default -- Added `path()` helper which creates a `Path` relative to `cwd()` (but is less noisy). - -### Changed - -- Marked many functions with `#[must_use]`, and rmake.rs are now compiled with `-Dunused_must_use`. - -## [0.1.0] - 2024-06-09 - -### Changed - -- Use *drop bombs* to enforce that commands are executed; a command invocation will panic if it is - constructed but never executed. Execution methods `Command::{run, run_fail}` will defuse the drop - bomb. -- Added `Command` helpers that forward to `std::process::Command` counterparts. - -### Removed - -- The `env_var` method which was incorrectly named and is `env_clear` underneath and is a footgun - from `impl_common_helpers`. For example, removing `TMPDIR` on Unix and `TMP`/`TEMP` breaks - `std::env::temp_dir` and wrecks anything using that, such as rustc's codgen. -- Removed `Deref`/`DerefMut` for `run_make_support::Command` -> `std::process::Command` because it - causes a method chain like `htmldocck().arg().run()` to fail, because `arg()` resolves to - `std::process::Command` which also returns a `&mut std::process::Command`, causing the `run()` to - be not found. - -## [0.0.0] - 2024-06-09 - -Consider this version to contain all changes made to the support library before we started to track -changes in this changelog. - -### Added - -- Custom command wrappers around `std::process::Command` (`run_make_support::Command`) and custom - wrapper around `std::process::Output` (`CompletedProcess`) to make it more convenient to work with - commands and their output, and help avoid forgetting to check for exit status. - - `Command`: `set_stdin`, `run`, `run_fail`. - - `CompletedProcess`: `std{err,out}_utf8`, `status`, `assert_std{err,out}_{equals, contains, - not_contains}`, `assert_exit_code`. -- `impl_common_helpers` macro to avoid repeating adding common convenience methods, including: - - Environment manipulation methods: `env`, `env_remove` - - Command argument providers: `arg`, `args` - - Common invocation inspection (of the command invocation up until `inspect` is called): - `inspect` - - Execution methods: `run` (for commands expected to succeed execution, exit status `0`) and - `run_fail` (for commands expected to fail execution, exit status non-zero). -- Command wrappers around: `rustc`, `clang`, `cc`, `rustc`, `rustdoc`, `llvm-readobj`. -- Thin helpers to construct `python` and `htmldocck` commands. -- `run` and `run_fail` (like `Command::{run, run_fail}`) for running binaries, which sets suitable - env vars (like `LD_LIB_PATH` or equivalent, `TARGET_RPATH_ENV`, `PATH` on Windows). -- Pseudo command `diff` which has similar functionality as the cli util but not the same API. -- Convenience panic-on-fail helpers `env_var`, `env_var_os`, `cwd` for their `std::env` conterparts. -- Convenience panic-on-fail helpers for reading respective env vars: `target`, `source_root`. -- Platform check helpers: `is_windows`, `is_msvc`, `cygpath_windows`, `uname`. -- fs helpers: `copy_dir_all`. -- `recursive_diff` helper. -- Generic `assert_not_contains` helper. -- Scoped run-with-teardown helper `run_in_tmpdir` which is designed to run commands in a temporary - directory that is cleared when closure returns. -- Helpers for constructing the name of binaries and libraries: `rust_lib_name`, `static_lib_name`, - `bin_name`, `dynamic_lib_name`. -- Re-export libraries: `gimli`, `object`, `regex`, `wasmparsmer`. -- cgit 1.4.1-3-g733a5 From ed520af279100728fd35df40cbf6353838cb7529 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 9 Jul 2025 20:05:13 +0800 Subject: Don't attempt to version `run-make-support` Purely internal test support library. --- Cargo.lock | 2 +- src/tools/run-make-support/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/Cargo.lock b/Cargo.lock index 6d823c5b5a5..271a2f7962c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3214,7 +3214,7 @@ dependencies = [ [[package]] name = "run_make_support" -version = "0.2.0" +version = "0.0.0" dependencies = [ "bstr", "build_helper", diff --git a/src/tools/run-make-support/Cargo.toml b/src/tools/run-make-support/Cargo.toml index 3226f467ba4..95aedf7d080 100644 --- a/src/tools/run-make-support/Cargo.toml +++ b/src/tools/run-make-support/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "run_make_support" -version = "0.2.0" +version = "0.0.0" edition = "2021" [dependencies] -- cgit 1.4.1-3-g733a5 From e70493d06c1e4fbc56380efc8d179bd845b20061 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 9 Jul 2025 20:07:09 +0800 Subject: Bump `run-make-support` to Edition 2024 --- src/tools/run-make-support/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/tools/run-make-support/Cargo.toml b/src/tools/run-make-support/Cargo.toml index 95aedf7d080..d01224eb56d 100644 --- a/src/tools/run-make-support/Cargo.toml +++ b/src/tools/run-make-support/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "run_make_support" version = "0.0.0" -edition = "2021" +edition = "2024" [dependencies] bstr = "1.12" -- cgit 1.4.1-3-g733a5 From fae15466aadd77e0369a893c7b962f7afbb86ff2 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 9 Jul 2025 20:10:32 +0800 Subject: Sort and document `run-make-support` dependencies --- src/tools/run-make-support/Cargo.toml | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/tools/run-make-support/Cargo.toml b/src/tools/run-make-support/Cargo.toml index d01224eb56d..a4e7534137d 100644 --- a/src/tools/run-make-support/Cargo.toml +++ b/src/tools/run-make-support/Cargo.toml @@ -4,15 +4,24 @@ version = "0.0.0" edition = "2024" [dependencies] + +# These dependencies are either used to implement part of support library +# functionality, or re-exported to test recipe programs via the support library, +# or both. + +# tidy-alphabetical-start bstr = "1.12" +gimli = "0.32" +libc = "0.2" object = "0.37" +regex = "1.11" +serde_json = "1.0" similar = "2.7" wasmparser = { version = "0.219", default-features = false, features = ["std"] } -regex = "1.11" -gimli = "0.32" +# tidy-alphabetical-end + +# Shared with bootstrap and compiletest build_helper = { path = "../../build_helper" } -serde_json = "1.0" -libc = "0.2" [lib] crate-type = ["lib", "dylib"] -- cgit 1.4.1-3-g733a5 From 200f132367f2aada7aff45689e53448a69cd7ce3 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 9 Jul 2025 20:22:58 +0800 Subject: Massage `lib.rs` so it can be rustfmt'd Even if the formatting isn't strictly "better", it at least allows rustfmtting it automatically. --- src/tools/run-make-support/src/lib.rs | 108 +++++++++++++--------------------- 1 file changed, 42 insertions(+), 66 deletions(-) (limited to 'src') diff --git a/src/tools/run-make-support/src/lib.rs b/src/tools/run-make-support/src/lib.rs index 67d8c351a59..69054396229 100644 --- a/src/tools/run-make-support/src/lib.rs +++ b/src/tools/run-make-support/src/lib.rs @@ -3,9 +3,6 @@ //! notably is built via cargo: this means that if your test wants some non-trivial utility, such //! as `object` or `wasmparser`, they can be re-exported and be made available through this library. -// We want to control use declaration ordering and spacing (and preserve use group comments), so -// skip rustfmt on this file. -#![cfg_attr(rustfmt, rustfmt::skip)] #![warn(unreachable_pub)] mod command; @@ -22,8 +19,8 @@ pub mod path_helpers; pub mod run; pub mod scoped_run; pub mod string; -pub mod targets; pub mod symbols; +pub mod targets; // Internally we call our fs-related support module as `fs`, but re-export its content as `rfs` // to tests to avoid colliding with commonly used `use std::fs;`. @@ -36,77 +33,56 @@ pub mod rfs { } // Re-exports of third-party library crates. -// tidy-alphabetical-start -pub use bstr; -pub use gimli; -pub use libc; -pub use object; -pub use regex; -pub use serde_json; -pub use similar; -pub use wasmparser; -// tidy-alphabetical-end +pub use {bstr, gimli, libc, object, regex, serde_json, similar, wasmparser}; -// Re-exports of external dependencies. -pub use external_deps::{ - cargo, c_build, c_cxx_compiler, clang, htmldocck, llvm, python, rustc, rustdoc +// Helpers for building names of output artifacts that are potentially target-specific. +pub use crate::artifact_names::{ + bin_name, dynamic_lib_extension, dynamic_lib_name, msvc_import_dynamic_lib_name, rust_lib_name, + static_lib_name, }; - -// These rely on external dependencies. -pub use c_cxx_compiler::{Cc, Gcc, cc, cxx, extra_c_flags, extra_cxx_flags, gcc}; -pub use c_build::{ +pub use crate::assertion_helpers::{ + assert_contains, assert_contains_regex, assert_count_is, assert_dirs_are_equal, assert_equals, + assert_not_contains, assert_not_contains_regex, +}; +// `diff` is implemented in terms of the [similar] library. +// +// [similar]: https://github.com/mitsuhiko/similar +pub use crate::diff::{Diff, diff}; +// Panic-on-fail [`std::env::var`] and [`std::env::var_os`] wrappers. +pub use crate::env::{env_var, env_var_os, set_current_dir}; +pub use crate::external_deps::c_build::{ build_native_dynamic_lib, build_native_static_lib, build_native_static_lib_cxx, build_native_static_lib_optimized, }; -pub use cargo::cargo; -pub use clang::{clang, Clang}; -pub use htmldocck::htmldocck; -pub use llvm::{ - llvm_ar, llvm_bcanalyzer, llvm_dis, llvm_dwarfdump, llvm_filecheck, llvm_nm, llvm_objcopy, - llvm_objdump, llvm_profdata, llvm_readobj, LlvmAr, LlvmBcanalyzer, LlvmDis, LlvmDwarfdump, - LlvmFilecheck, LlvmNm, LlvmObjcopy, LlvmObjdump, LlvmProfdata, LlvmReadobj, -}; -pub use python::python_command; -pub use rustc::{bare_rustc, rustc, rustc_path, Rustc}; -pub use rustdoc::{bare_rustdoc, rustdoc, Rustdoc}; - -/// [`diff`][mod@diff] is implemented in terms of the [similar] library. -/// -/// [similar]: https://github.com/mitsuhiko/similar -pub use diff::{diff, Diff}; - -/// Panic-on-fail [`std::env::var`] and [`std::env::var_os`] wrappers. -pub use env::{env_var, env_var_os, set_current_dir}; - -/// Convenience helpers for running binaries and other commands. -pub use run::{cmd, run, run_fail, run_with_args}; - -/// Helpers for checking target information. -pub use targets::{ - apple_os, is_aix, is_darwin, is_msvc, is_windows, is_windows_gnu, is_windows_msvc, is_win7, llvm_components_contain, - target, uname, +// Re-exports of external dependencies. +pub use crate::external_deps::c_cxx_compiler::{ + Cc, Gcc, cc, cxx, extra_c_flags, extra_cxx_flags, gcc, }; - -/// Helpers for building names of output artifacts that are potentially target-specific. -pub use artifact_names::{ - bin_name, dynamic_lib_extension, dynamic_lib_name, msvc_import_dynamic_lib_name, rust_lib_name, - static_lib_name, +pub use crate::external_deps::cargo::cargo; +pub use crate::external_deps::clang::{Clang, clang}; +pub use crate::external_deps::htmldocck::htmldocck; +pub use crate::external_deps::llvm::{ + self, LlvmAr, LlvmBcanalyzer, LlvmDis, LlvmDwarfdump, LlvmFilecheck, LlvmNm, LlvmObjcopy, + LlvmObjdump, LlvmProfdata, LlvmReadobj, llvm_ar, llvm_bcanalyzer, llvm_dis, llvm_dwarfdump, + llvm_filecheck, llvm_nm, llvm_objcopy, llvm_objdump, llvm_profdata, llvm_readobj, }; - -/// Path-related helpers. -pub use path_helpers::{ +pub use crate::external_deps::python::python_command; +pub use crate::external_deps::rustc::{self, Rustc, bare_rustc, rustc, rustc_path}; +pub use crate::external_deps::rustdoc::{Rustdoc, bare_rustdoc, rustdoc}; +// Path-related helpers. +pub use crate::path_helpers::{ build_root, cwd, filename_contains, filename_not_in_denylist, has_extension, has_prefix, has_suffix, not_contains, path, shallow_find_directories, shallow_find_files, source_root, }; - -/// Helpers for scoped test execution where certain properties are attempted to be maintained. -pub use scoped_run::{run_in_tmpdir, test_while_readonly}; - -pub use assertion_helpers::{ - assert_contains, assert_contains_regex, assert_count_is, assert_dirs_are_equal, assert_equals, - assert_not_contains, assert_not_contains_regex, -}; - -pub use string::{ +// Convenience helpers for running binaries and other commands. +pub use crate::run::{cmd, run, run_fail, run_with_args}; +// Helpers for scoped test execution where certain properties are attempted to be maintained. +pub use crate::scoped_run::{run_in_tmpdir, test_while_readonly}; +pub use crate::string::{ count_regex_matches_in_files_with_extension, invalid_utf8_contains, invalid_utf8_not_contains, }; +// Helpers for checking target information. +pub use crate::targets::{ + apple_os, is_aix, is_darwin, is_msvc, is_win7, is_windows, is_windows_gnu, is_windows_msvc, + llvm_components_contain, target, uname, +}; -- cgit 1.4.1-3-g733a5 From 65dc474d1ce75071dacd76480807abdf0beed830 Mon Sep 17 00:00:00 2001 From: Daniel Paoliello Date: Wed, 9 Jul 2025 12:56:06 -0700 Subject: Update LLVM submodule --- src/llvm-project | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/llvm-project b/src/llvm-project index 9b1bf4cf041..99f0e053168 160000 --- a/src/llvm-project +++ b/src/llvm-project @@ -1 +1 @@ -Subproject commit 9b1bf4cf041c1c1fe62cf03891ac90431615e780 +Subproject commit 99f0e0531688a822a753cc585b7408b069cb6822 -- cgit 1.4.1-3-g733a5 From 93db9e7ee01d61cb97b4f7b3d61903477910cae2 Mon Sep 17 00:00:00 2001 From: yukang Date: Sun, 29 Jun 2025 11:40:59 +0800 Subject: Remove uncessary parens in closure body with unused lint --- compiler/rustc_errors/src/emitter.rs | 2 +- compiler/rustc_lint/src/unused.rs | 10 +++- compiler/rustc_parse/src/parser/item.rs | 2 +- compiler/rustc_resolve/src/late/diagnostics.rs | 3 +- library/core/src/unicode/unicode_data.rs | 2 +- src/tools/clippy/clippy_lints/src/unused_async.rs | 2 +- src/tools/clippy/clippy_utils/src/ty/mod.rs | 4 +- src/tools/compiletest/src/runtest.rs | 6 +++ src/tools/test-float-parse/src/lib.rs | 2 +- .../unicode-table-generator/src/range_search.rs | 2 +- .../async-await/issues/issue-54752-async-block.rs | 1 - .../issues/issue-54752-async-block.stderr | 15 ------ .../ui/lint/unused/closure-body-issue-136741.fixed | 36 +++++++++++++ tests/ui/lint/unused/closure-body-issue-136741.rs | 38 +++++++++++++ .../lint/unused/closure-body-issue-136741.stderr | 62 ++++++++++++++++++++++ 15 files changed, 160 insertions(+), 27 deletions(-) delete mode 100644 tests/ui/async-await/issues/issue-54752-async-block.stderr create mode 100644 tests/ui/lint/unused/closure-body-issue-136741.fixed create mode 100644 tests/ui/lint/unused/closure-body-issue-136741.rs create mode 100644 tests/ui/lint/unused/closure-body-issue-136741.stderr (limited to 'src') diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 2f398cea926..510f37f37e2 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -3526,7 +3526,7 @@ pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool { // All the chars that differ in capitalization are confusable (above): let confusable = iter::zip(found.chars(), suggested.chars()) .filter(|(f, s)| f != s) - .all(|(f, s)| (ascii_confusables.contains(&f) || ascii_confusables.contains(&s))); + .all(|(f, s)| ascii_confusables.contains(&f) || ascii_confusables.contains(&s)); confusable && found.to_lowercase() == suggested.to_lowercase() // FIXME: We sometimes suggest the same thing we already have, which is a // bug, but be defensive against that here. diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index d3942a1c816..a9eb1739f7f 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -1,7 +1,7 @@ use std::iter; use rustc_ast::util::{classify, parser}; -use rustc_ast::{self as ast, ExprKind, HasAttrs as _, StmtKind}; +use rustc_ast::{self as ast, ExprKind, FnRetTy, HasAttrs as _, StmtKind}; use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{MultiSpan, pluralize}; @@ -599,6 +599,7 @@ enum UnusedDelimsCtx { AnonConst, MatchArmExpr, IndexExpr, + ClosureBody, } impl From for &'static str { @@ -620,6 +621,7 @@ impl From for &'static str { UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression", UnusedDelimsCtx::MatchArmExpr => "match arm expression", UnusedDelimsCtx::IndexExpr => "index expression", + UnusedDelimsCtx::ClosureBody => "closure body", } } } @@ -919,6 +921,11 @@ trait UnusedDelimLint { let (args_to_check, ctx) = match *call_or_other { Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg), MethodCall(ref call) => (&call.args[..], UnusedDelimsCtx::MethodArg), + Closure(ref closure) + if matches!(closure.fn_decl.output, FnRetTy::Default(_)) => + { + (&[closure.body.clone()][..], UnusedDelimsCtx::ClosureBody) + } // actual catch-all arm _ => { return; @@ -1508,6 +1515,7 @@ impl UnusedDelimLint for UnusedBraces { && (ctx != UnusedDelimsCtx::AnonConst || (matches!(expr.kind, ast::ExprKind::Lit(_)) && !expr.span.from_expansion())) + && ctx != UnusedDelimsCtx::ClosureBody && !cx.sess().source_map().is_multiline(value.span) && value.attrs.is_empty() && !value.span.from_expansion() diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 9ed7124a11c..d6cc98d505c 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -2206,7 +2206,7 @@ impl<'a> Parser<'a> { if self.look_ahead(1, |t| *t == token::Bang) && self.look_ahead(2, |t| t.is_ident()) { return IsMacroRulesItem::Yes { has_bang: true }; - } else if self.look_ahead(1, |t| (t.is_ident())) { + } else if self.look_ahead(1, |t| t.is_ident()) { // macro_rules foo self.dcx().emit_err(errors::MacroRulesMissingBang { span: macro_rules_span, diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index e015eb7a636..8114021510e 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -328,8 +328,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id); let mod_prefix = - mod_prefix.map_or_else(String::new, |res| (format!("{} ", res.descr()))); - + mod_prefix.map_or_else(String::new, |res| format!("{} ", res.descr())); (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), module_did, None) }; diff --git a/library/core/src/unicode/unicode_data.rs b/library/core/src/unicode/unicode_data.rs index 25b9c6e0e0e..b57234bbee9 100644 --- a/library/core/src/unicode/unicode_data.rs +++ b/library/core/src/unicode/unicode_data.rs @@ -82,7 +82,7 @@ unsafe fn skip_search( let needle = needle as u32; let last_idx = - match short_offset_runs.binary_search_by_key(&(needle << 11), |header| (header.0 << 11)) { + match short_offset_runs.binary_search_by_key(&(needle << 11), |header| header.0 << 11) { Ok(idx) => idx + 1, Err(idx) => idx, }; diff --git a/src/tools/clippy/clippy_lints/src/unused_async.rs b/src/tools/clippy/clippy_lints/src/unused_async.rs index 8ceaa3dc58e..e67afc7f5a8 100644 --- a/src/tools/clippy/clippy_lints/src/unused_async.rs +++ b/src/tools/clippy/clippy_lints/src/unused_async.rs @@ -169,7 +169,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedAsync { let iter = self .unused_async_fns .iter() - .filter(|UnusedAsyncFn { def_id, .. }| (!self.async_fns_as_value.contains(def_id))); + .filter(|UnusedAsyncFn { def_id, .. }| !self.async_fns_as_value.contains(def_id)); for fun in iter { span_lint_hir_and_then( diff --git a/src/tools/clippy/clippy_utils/src/ty/mod.rs b/src/tools/clippy/clippy_utils/src/ty/mod.rs index bffbcf073ab..fe208c032f4 100644 --- a/src/tools/clippy/clippy_utils/src/ty/mod.rs +++ b/src/tools/clippy/clippy_utils/src/ty/mod.rs @@ -889,7 +889,7 @@ impl AdtVariantInfo { .enumerate() .map(|(i, f)| (i, approx_ty_size(cx, f.ty(cx.tcx, subst)))) .collect::>(); - fields_size.sort_by(|(_, a_size), (_, b_size)| (a_size.cmp(b_size))); + fields_size.sort_by(|(_, a_size), (_, b_size)| a_size.cmp(b_size)); Self { ind: i, @@ -898,7 +898,7 @@ impl AdtVariantInfo { } }) .collect::>(); - variants_size.sort_by(|a, b| (b.size.cmp(&a.size))); + variants_size.sort_by(|a, b| b.size.cmp(&a.size)); variants_size } } diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 3e879e0e4bb..933a32392bd 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -1777,6 +1777,12 @@ impl<'test> TestCx<'test> { // Allow tests to use internal features. rustc.args(&["-A", "internal_features"]); + // Allow tests to have unused parens and braces. + // Add #![deny(unused_parens, unused_braces)] to the test file if you want to + // test that these lints are working. + rustc.args(&["-A", "unused_parens"]); + rustc.args(&["-A", "unused_braces"]); + if self.props.force_host { self.maybe_add_external_args(&mut rustc, &self.config.host_rustcflags); if !is_rustdoc { diff --git a/src/tools/test-float-parse/src/lib.rs b/src/tools/test-float-parse/src/lib.rs index 0bd4878f9a6..1321a3c3354 100644 --- a/src/tools/test-float-parse/src/lib.rs +++ b/src/tools/test-float-parse/src/lib.rs @@ -340,7 +340,7 @@ fn launch_tests(tests: &mut [TestInfo], cfg: &Config) -> Duration { for test in tests.iter_mut() { test.progress = Some(ui::Progress::new(test, &mut all_progress_bars)); ui::set_panic_hook(&all_progress_bars); - ((test.launch)(test, cfg)); + (test.launch)(test, cfg); } start.elapsed() diff --git a/src/tools/unicode-table-generator/src/range_search.rs b/src/tools/unicode-table-generator/src/range_search.rs index 02f9cf16d4d..4d1dd9b423b 100644 --- a/src/tools/unicode-table-generator/src/range_search.rs +++ b/src/tools/unicode-table-generator/src/range_search.rs @@ -80,7 +80,7 @@ unsafe fn skip_search( let needle = needle as u32; let last_idx = - match short_offset_runs.binary_search_by_key(&(needle << 11), |header| (header.0 << 11)) { + match short_offset_runs.binary_search_by_key(&(needle << 11), |header| header.0 << 11) { Ok(idx) => idx + 1, Err(idx) => idx, }; diff --git a/tests/ui/async-await/issues/issue-54752-async-block.rs b/tests/ui/async-await/issues/issue-54752-async-block.rs index 452b6794bee..164c1885da1 100644 --- a/tests/ui/async-await/issues/issue-54752-async-block.rs +++ b/tests/ui/async-await/issues/issue-54752-async-block.rs @@ -4,4 +4,3 @@ //@ pp-exact fn main() { let _a = (async { }); } -//~^ WARNING unnecessary parentheses around assigned value diff --git a/tests/ui/async-await/issues/issue-54752-async-block.stderr b/tests/ui/async-await/issues/issue-54752-async-block.stderr deleted file mode 100644 index 8cc849dd985..00000000000 --- a/tests/ui/async-await/issues/issue-54752-async-block.stderr +++ /dev/null @@ -1,15 +0,0 @@ -warning: unnecessary parentheses around assigned value - --> $DIR/issue-54752-async-block.rs:6:22 - | -LL | fn main() { let _a = (async { }); } - | ^ ^ - | - = note: `#[warn(unused_parens)]` on by default -help: remove these parentheses - | -LL - fn main() { let _a = (async { }); } -LL + fn main() { let _a = async { }; } - | - -warning: 1 warning emitted - diff --git a/tests/ui/lint/unused/closure-body-issue-136741.fixed b/tests/ui/lint/unused/closure-body-issue-136741.fixed new file mode 100644 index 00000000000..2ded52544b9 --- /dev/null +++ b/tests/ui/lint/unused/closure-body-issue-136741.fixed @@ -0,0 +1,36 @@ +//@ run-rustfix +// ignore-tidy-linelength +#![deny(unused_parens)] +#![deny(unused_braces)] + +fn long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces() +{} + +fn func(f: impl FnOnce()) { + f() +} + +pub fn main() { + let _closure = |x: i32, y: i32| { x * (x + (y * 2)) }; + let _ = || 0 == 0; //~ ERROR unnecessary parentheses around closure body + let _ = (0..).find(|n| n % 2 == 0); //~ ERROR unnecessary parentheses around closure body + let _ = (0..).find(|n| {n % 2 == 0}); + + // multiple lines of code will not lint with braces + let _ = (0..).find(|n| { + n % 2 == 0 + }); + + // multiple lines of code will lint with parentheses + let _ = (0..).find(|n| n % 2 == 0); + + let _ = || { + _ = 0; + 0 == 0 //~ ERROR unnecessary parentheses around block return value + }; + + // long expressions will not lint with braces + func(|| { + long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces() + }) +} diff --git a/tests/ui/lint/unused/closure-body-issue-136741.rs b/tests/ui/lint/unused/closure-body-issue-136741.rs new file mode 100644 index 00000000000..4eac981ec2e --- /dev/null +++ b/tests/ui/lint/unused/closure-body-issue-136741.rs @@ -0,0 +1,38 @@ +//@ run-rustfix +// ignore-tidy-linelength +#![deny(unused_parens)] +#![deny(unused_braces)] + +fn long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces() +{} + +fn func(f: impl FnOnce()) { + f() +} + +pub fn main() { + let _closure = |x: i32, y: i32| { x * (x + (y * 2)) }; + let _ = || (0 == 0); //~ ERROR unnecessary parentheses around closure body + let _ = (0..).find(|n| (n % 2 == 0)); //~ ERROR unnecessary parentheses around closure body + let _ = (0..).find(|n| {n % 2 == 0}); + + // multiple lines of code will not lint with braces + let _ = (0..).find(|n| { + n % 2 == 0 + }); + + // multiple lines of code will lint with parentheses + let _ = (0..).find(|n| ( //~ ERROR unnecessary parentheses around closure body + n % 2 == 0 + )); + + let _ = || { + _ = 0; + (0 == 0) //~ ERROR unnecessary parentheses around block return value + }; + + // long expressions will not lint with braces + func(|| { + long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces() + }) +} diff --git a/tests/ui/lint/unused/closure-body-issue-136741.stderr b/tests/ui/lint/unused/closure-body-issue-136741.stderr new file mode 100644 index 00000000000..2ea872c08c7 --- /dev/null +++ b/tests/ui/lint/unused/closure-body-issue-136741.stderr @@ -0,0 +1,62 @@ +error: unnecessary parentheses around closure body + --> $DIR/closure-body-issue-136741.rs:15:16 + | +LL | let _ = || (0 == 0); + | ^ ^ + | +note: the lint level is defined here + --> $DIR/closure-body-issue-136741.rs:3:9 + | +LL | #![deny(unused_parens)] + | ^^^^^^^^^^^^^ +help: remove these parentheses + | +LL - let _ = || (0 == 0); +LL + let _ = || 0 == 0; + | + +error: unnecessary parentheses around closure body + --> $DIR/closure-body-issue-136741.rs:16:28 + | +LL | let _ = (0..).find(|n| (n % 2 == 0)); + | ^ ^ + | +help: remove these parentheses + | +LL - let _ = (0..).find(|n| (n % 2 == 0)); +LL + let _ = (0..).find(|n| n % 2 == 0); + | + +error: unnecessary parentheses around closure body + --> $DIR/closure-body-issue-136741.rs:25:28 + | +LL | let _ = (0..).find(|n| ( + | _____________________________^ +LL | | n % 2 == 0 + | | ________^__________^ + | ||________| + | | +LL | | )); + | |_____^ + | +help: remove these parentheses + | +LL - let _ = (0..).find(|n| ( +LL - n % 2 == 0 +LL + let _ = (0..).find(|n| n % 2 == 0); + | + +error: unnecessary parentheses around block return value + --> $DIR/closure-body-issue-136741.rs:31:9 + | +LL | (0 == 0) + | ^ ^ + | +help: remove these parentheses + | +LL - (0 == 0) +LL + 0 == 0 + | + +error: aborting due to 4 previous errors + -- cgit 1.4.1-3-g733a5 From e726c643e8319ee5eb2a8be45eb65f7600be2d5d Mon Sep 17 00:00:00 2001 From: The Miri Cronjob Bot Date: Thu, 10 Jul 2025 04:58:14 +0000 Subject: Preparing for merge from rustc --- src/tools/miri/rust-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version index a9394819541..0af6b8c6fc7 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -688ea65df6a47866d0f72a00f1e18b47a7edf83b +32cd9114712a24010b0583624dc52ac302194128 -- cgit 1.4.1-3-g733a5 From 4dc954f88256314c4c03a4cb43eee838bc3762eb Mon Sep 17 00:00:00 2001 From: yukang Date: Thu, 10 Jul 2025 13:50:02 +0800 Subject: remove unnecessary parens in rust-analyzer --- src/tools/rust-analyzer/crates/rust-analyzer/src/cli/scip.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/scip.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/scip.rs index d258c5d8191..37f83f6dee6 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/scip.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/scip.rs @@ -25,7 +25,7 @@ impl flags::Scip { eprintln!("Generating SCIP start..."); let now = Instant::now(); - let no_progress = &|s| (eprintln!("rust-analyzer: Loading {s}")); + let no_progress = &|s| eprintln!("rust-analyzer: Loading {s}"); let root = vfs::AbsPathBuf::assert_utf8(std::env::current_dir()?.join(&self.path)).normalize(); -- cgit 1.4.1-3-g733a5 From 87a41210d4ec4f43a1e015dfea44ef3f686c9872 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 9 Jul 2025 20:29:51 +0800 Subject: Only provide `is_windows_msvc` to gate on windows-msvc And not both `is_windows_msvc` and `is_msvc`. --- src/tools/run-make-support/src/artifact_names.rs | 6 +++--- .../run-make-support/src/external_deps/c_build.rs | 23 +++++++++++----------- .../src/external_deps/c_cxx_compiler/cc.rs | 6 +++--- .../src/external_deps/c_cxx_compiler/extras.rs | 6 +++--- .../run-make-support/src/external_deps/rustc.rs | 4 ++-- src/tools/run-make-support/src/lib.rs | 2 +- src/tools/run-make-support/src/linker.rs | 4 ++-- src/tools/run-make-support/src/targets.rs | 12 +++-------- 8 files changed, 29 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/tools/run-make-support/src/artifact_names.rs b/src/tools/run-make-support/src/artifact_names.rs index b0d588d3550..a889b30e145 100644 --- a/src/tools/run-make-support/src/artifact_names.rs +++ b/src/tools/run-make-support/src/artifact_names.rs @@ -2,7 +2,7 @@ //! libraries which are target-dependent. use crate::target; -use crate::targets::is_msvc; +use crate::targets::is_windows_msvc; /// Construct the static library name based on the target. #[track_caller] @@ -10,7 +10,7 @@ use crate::targets::is_msvc; pub fn static_lib_name(name: &str) -> String { assert!(!name.contains(char::is_whitespace), "static library name cannot contain whitespace"); - if is_msvc() { format!("{name}.lib") } else { format!("lib{name}.a") } + if is_windows_msvc() { format!("{name}.lib") } else { format!("lib{name}.a") } } /// Construct the dynamic library name based on the target. @@ -45,7 +45,7 @@ pub fn dynamic_lib_extension() -> &'static str { #[track_caller] #[must_use] pub fn msvc_import_dynamic_lib_name(name: &str) -> String { - assert!(is_msvc(), "this function is exclusive to MSVC"); + assert!(is_windows_msvc(), "this function is exclusive to MSVC"); assert!(!name.contains(char::is_whitespace), "import library name cannot contain whitespace"); format!("{name}.dll.lib") diff --git a/src/tools/run-make-support/src/external_deps/c_build.rs b/src/tools/run-make-support/src/external_deps/c_build.rs index 9dd30713f95..ecbf5ba8fe0 100644 --- a/src/tools/run-make-support/src/external_deps/c_build.rs +++ b/src/tools/run-make-support/src/external_deps/c_build.rs @@ -4,7 +4,7 @@ use crate::artifact_names::{dynamic_lib_name, static_lib_name}; use crate::external_deps::c_cxx_compiler::{cc, cxx}; use crate::external_deps::llvm::llvm_ar; use crate::path_helpers::path; -use crate::targets::{is_darwin, is_msvc, is_windows}; +use crate::targets::{is_darwin, is_windows, is_windows_msvc}; // FIXME(Oneirical): These native build functions should take a Path-based generic. @@ -24,12 +24,12 @@ pub fn build_native_static_lib_optimized(lib_name: &str) -> PathBuf { #[track_caller] fn build_native_static_lib_internal(lib_name: &str, optimzed: bool) -> PathBuf { - let obj_file = if is_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; + let obj_file = if is_windows_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; let src = format!("{lib_name}.c"); let lib_path = static_lib_name(lib_name); let mut cc = cc(); - if !is_msvc() { + if !is_windows_msvc() { cc.arg("-v"); } if optimzed { @@ -37,7 +37,7 @@ fn build_native_static_lib_internal(lib_name: &str, optimzed: bool) -> PathBuf { } cc.arg("-c").out_exe(&obj_file).input(src).optimize().run(); - let obj_file = if is_msvc() { + let obj_file = if is_windows_msvc() { PathBuf::from(format!("{lib_name}.obj")) } else { PathBuf::from(format!("{lib_name}.o")) @@ -50,16 +50,17 @@ fn build_native_static_lib_internal(lib_name: &str, optimzed: bool) -> PathBuf { /// [`std::env::consts::DLL_PREFIX`] and [`std::env::consts::DLL_EXTENSION`]. #[track_caller] pub fn build_native_dynamic_lib(lib_name: &str) -> PathBuf { - let obj_file = if is_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; + let obj_file = if is_windows_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; let src = format!("{lib_name}.c"); let lib_path = dynamic_lib_name(lib_name); - if is_msvc() { + if is_windows_msvc() { cc().arg("-c").out_exe(&obj_file).input(src).run(); } else { cc().arg("-v").arg("-c").out_exe(&obj_file).input(src).run(); }; - let obj_file = if is_msvc() { format!("{lib_name}.obj") } else { format!("{lib_name}.o") }; - if is_msvc() { + let obj_file = + if is_windows_msvc() { format!("{lib_name}.obj") } else { format!("{lib_name}.o") }; + if is_windows_msvc() { let out_arg = format!("-out:{lib_path}"); cc().input(&obj_file).args(&["-link", "-dll", &out_arg]).run(); } else if is_darwin() { @@ -79,15 +80,15 @@ pub fn build_native_dynamic_lib(lib_name: &str) -> PathBuf { /// Built from a C++ file. #[track_caller] pub fn build_native_static_lib_cxx(lib_name: &str) -> PathBuf { - let obj_file = if is_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; + let obj_file = if is_windows_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; let src = format!("{lib_name}.cpp"); let lib_path = static_lib_name(lib_name); - if is_msvc() { + if is_windows_msvc() { cxx().arg("-EHs").arg("-c").out_exe(&obj_file).input(src).run(); } else { cxx().arg("-c").out_exe(&obj_file).input(src).run(); }; - let obj_file = if is_msvc() { + let obj_file = if is_windows_msvc() { PathBuf::from(format!("{lib_name}.obj")) } else { PathBuf::from(format!("{lib_name}.o")) diff --git a/src/tools/run-make-support/src/external_deps/c_cxx_compiler/cc.rs b/src/tools/run-make-support/src/external_deps/c_cxx_compiler/cc.rs index 0e6d6ea6075..31469e669e1 100644 --- a/src/tools/run-make-support/src/external_deps/c_cxx_compiler/cc.rs +++ b/src/tools/run-make-support/src/external_deps/c_cxx_compiler/cc.rs @@ -1,7 +1,7 @@ use std::path::Path; use crate::command::Command; -use crate::{env_var, is_msvc}; +use crate::{env_var, is_windows_msvc}; /// Construct a new platform-specific C compiler invocation. /// @@ -82,7 +82,7 @@ impl Cc { pub fn out_exe(&mut self, name: &str) -> &mut Self { let mut path = std::path::PathBuf::from(name); - if is_msvc() { + if is_windows_msvc() { path.set_extension("exe"); let fe_path = path.clone(); path.set_extension(""); @@ -108,7 +108,7 @@ impl Cc { /// Optimize the output. /// Equivalent to `-O3` for GNU-compatible linkers or `-O2` for MSVC linkers. pub fn optimize(&mut self) -> &mut Self { - if is_msvc() { + if is_windows_msvc() { self.cmd.arg("-O2"); } else { self.cmd.arg("-O3"); diff --git a/src/tools/run-make-support/src/external_deps/c_cxx_compiler/extras.rs b/src/tools/run-make-support/src/external_deps/c_cxx_compiler/extras.rs index c0317633873..ac7392641c0 100644 --- a/src/tools/run-make-support/src/external_deps/c_cxx_compiler/extras.rs +++ b/src/tools/run-make-support/src/external_deps/c_cxx_compiler/extras.rs @@ -1,9 +1,9 @@ -use crate::{is_msvc, is_win7, is_windows, uname}; +use crate::{is_win7, is_windows, is_windows_msvc, uname}; /// `EXTRACFLAGS` pub fn extra_c_flags() -> Vec<&'static str> { if is_windows() { - if is_msvc() { + if is_windows_msvc() { let mut libs = vec!["ws2_32.lib", "userenv.lib", "bcrypt.lib", "ntdll.lib", "synchronization.lib"]; if is_win7() { @@ -29,7 +29,7 @@ pub fn extra_c_flags() -> Vec<&'static str> { /// `EXTRACXXFLAGS` pub fn extra_cxx_flags() -> Vec<&'static str> { if is_windows() { - if is_msvc() { vec![] } else { vec!["-lstdc++"] } + if is_windows_msvc() { vec![] } else { vec!["-lstdc++"] } } else { match &uname()[..] { "Darwin" => vec!["-lc++"], diff --git a/src/tools/run-make-support/src/external_deps/rustc.rs b/src/tools/run-make-support/src/external_deps/rustc.rs index 72a1e062a38..1ea549ca7ea 100644 --- a/src/tools/run-make-support/src/external_deps/rustc.rs +++ b/src/tools/run-make-support/src/external_deps/rustc.rs @@ -6,7 +6,7 @@ use crate::command::Command; use crate::env::env_var; use crate::path_helpers::cwd; use crate::util::set_host_compiler_dylib_path; -use crate::{is_aix, is_darwin, is_msvc, is_windows, target, uname}; +use crate::{is_aix, is_darwin, is_windows, is_windows_msvc, target, uname}; /// Construct a new `rustc` invocation. This will automatically set the library /// search path as `-L cwd()`. Use [`bare_rustc`] to avoid this. @@ -377,7 +377,7 @@ impl Rustc { // So we end up with the following hack: we link use static:-bundle to only // link the parts of libstdc++ that we actually use, which doesn't include // the dependency on the pthreads DLL. - if !is_msvc() { + if !is_windows_msvc() { self.cmd.arg("-lstatic:-bundle=stdc++"); }; } else if is_darwin() { diff --git a/src/tools/run-make-support/src/lib.rs b/src/tools/run-make-support/src/lib.rs index 69054396229..29cd6c4ad15 100644 --- a/src/tools/run-make-support/src/lib.rs +++ b/src/tools/run-make-support/src/lib.rs @@ -83,6 +83,6 @@ pub use crate::string::{ }; // Helpers for checking target information. pub use crate::targets::{ - apple_os, is_aix, is_darwin, is_msvc, is_win7, is_windows, is_windows_gnu, is_windows_msvc, + apple_os, is_aix, is_darwin, is_win7, is_windows, is_windows_gnu, is_windows_msvc, llvm_components_contain, target, uname, }; diff --git a/src/tools/run-make-support/src/linker.rs b/src/tools/run-make-support/src/linker.rs index 89093cf0113..b2893ad88fe 100644 --- a/src/tools/run-make-support/src/linker.rs +++ b/src/tools/run-make-support/src/linker.rs @@ -1,6 +1,6 @@ use regex::Regex; -use crate::{Rustc, is_msvc}; +use crate::{Rustc, is_windows_msvc}; /// Asserts that `rustc` uses LLD for linking when executed. pub fn assert_rustc_uses_lld(rustc: &mut Rustc) { @@ -22,7 +22,7 @@ pub fn assert_rustc_doesnt_use_lld(rustc: &mut Rustc) { fn get_stderr_with_linker_messages(rustc: &mut Rustc) -> String { // lld-link is used if msvc, otherwise a gnu-compatible lld is used. - let linker_version_flag = if is_msvc() { "--version" } else { "-Wl,-v" }; + let linker_version_flag = if is_windows_msvc() { "--version" } else { "-Wl,-v" }; let output = rustc.arg("-Wlinker-messages").link_arg(linker_version_flag).run(); output.stderr_utf8() diff --git a/src/tools/run-make-support/src/targets.rs b/src/tools/run-make-support/src/targets.rs index 1ab2e2ab2be..b20e12561fb 100644 --- a/src/tools/run-make-support/src/targets.rs +++ b/src/tools/run-make-support/src/targets.rs @@ -16,10 +16,10 @@ pub fn is_windows() -> bool { target().contains("windows") } -/// Check if target uses msvc. +/// Check if target is windows-msvc. #[must_use] -pub fn is_msvc() -> bool { - target().contains("msvc") +pub fn is_windows_msvc() -> bool { + target().ends_with("windows-msvc") } /// Check if target is windows-gnu. @@ -28,12 +28,6 @@ pub fn is_windows_gnu() -> bool { target().ends_with("windows-gnu") } -/// Check if target is windows-msvc. -#[must_use] -pub fn is_windows_msvc() -> bool { - target().ends_with("windows-msvc") -} - /// Check if target is win7. #[must_use] pub fn is_win7() -> bool { -- cgit 1.4.1-3-g733a5 From 5e940f581008dbc9b84aa1a8672a3c0a940da7be Mon Sep 17 00:00:00 2001 From: The Miri Cronjob Bot Date: Thu, 10 Jul 2025 05:06:47 +0000 Subject: fmt --- src/tools/miri/src/machine.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index 35399dbf4cb..7c4d394525b 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -1828,7 +1828,9 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> { fn enter_trace_span(span: impl FnOnce() -> tracing::Span) -> impl EnteredTraceSpan { #[cfg(feature = "tracing")] - { span().entered() } + { + span().entered() + } #[cfg(not(feature = "tracing"))] { let _ = span; // so we avoid the "unused variable" warning -- cgit 1.4.1-3-g733a5 From 17b240e04f8d14e5563b6afb2ed3b842f87d1c78 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 10 Jul 2025 08:33:05 +0200 Subject: silence clippy --- src/tools/miri/src/machine.rs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index 7c4d394525b..9c077e5b7b6 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -1832,6 +1832,7 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> { span().entered() } #[cfg(not(feature = "tracing"))] + #[expect(clippy::unused_unit)] { let _ = span; // so we avoid the "unused variable" warning () -- cgit 1.4.1-3-g733a5