From e836a2f5ff6d3317db06891feb3087e6164c282b Mon Sep 17 00:00:00 2001 From: Jonathan Gruner Date: Thu, 24 Apr 2025 21:14:47 +0200 Subject: [PATCH 01/30] implement continue_ok and break_ok for ControlFlow --- library/core/src/ops/control_flow.rs | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/library/core/src/ops/control_flow.rs b/library/core/src/ops/control_flow.rs index 26661b20c12d6..ee450209f4476 100644 --- a/library/core/src/ops/control_flow.rs +++ b/library/core/src/ops/control_flow.rs @@ -187,6 +187,28 @@ impl ControlFlow { } } + /// Converts the `ControlFlow` into an `Result` which is `Ok` if the + /// `ControlFlow` was `Break` and `Err` if otherwise. + /// + /// # Examples + /// + /// ``` + /// #![feature(control_flow_ok)] + /// + /// use std::ops::ControlFlow; + /// + /// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").break_ok(), Ok("Stop right there!")); + /// assert_eq!(ControlFlow::<&str, i32>::Continue(3).break_ok(), Err(3)); + /// ``` + #[inline] + #[unstable(feature = "control_flow_ok", issue = "140266")] + pub fn break_ok(self) -> Result { + match self { + ControlFlow::Continue(c) => Err(c), + ControlFlow::Break(b) => Ok(b), + } + } + /// Maps `ControlFlow` to `ControlFlow` by applying a function /// to the break value in case it exists. #[inline] @@ -218,6 +240,28 @@ impl ControlFlow { } } + /// Converts the `ControlFlow` into an `Result` which is `Ok` if the + /// `ControlFlow` was `Continue` and `Err` if otherwise. + /// + /// # Examples + /// + /// ``` + /// #![feature(control_flow_ok)] + /// + /// use std::ops::ControlFlow; + /// + /// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").continue_ok(), Err("Stop right there!")); + /// assert_eq!(ControlFlow::<&str, i32>::Continue(3).continue_ok(), Ok(3)); + /// ``` + #[inline] + #[unstable(feature = "control_flow_ok", issue = "140266")] + pub fn continue_ok(self) -> Result { + match self { + ControlFlow::Continue(c) => Ok(c), + ControlFlow::Break(b) => Err(b), + } + } + /// Maps `ControlFlow` to `ControlFlow` by applying a function /// to the continue value in case it exists. #[inline] From b981b84e031b0316c9e1ba244395c7bb2fdb68a9 Mon Sep 17 00:00:00 2001 From: Jonathan Gruner Date: Sat, 26 Apr 2025 12:57:12 +0200 Subject: [PATCH 02/30] moved simple test to coretests, introduced more fleshed out doctests for break_ok/continue_ok --- library/core/src/ops/control_flow.rs | 111 +++++++++++++++++++- library/coretests/tests/lib.rs | 1 + library/coretests/tests/ops/control_flow.rs | 12 +++ 3 files changed, 120 insertions(+), 4 deletions(-) diff --git a/library/core/src/ops/control_flow.rs b/library/core/src/ops/control_flow.rs index ee450209f4476..7489a8bb6e74b 100644 --- a/library/core/src/ops/control_flow.rs +++ b/library/core/src/ops/control_flow.rs @@ -197,8 +197,60 @@ impl ControlFlow { /// /// use std::ops::ControlFlow; /// - /// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").break_ok(), Ok("Stop right there!")); - /// assert_eq!(ControlFlow::<&str, i32>::Continue(3).break_ok(), Err(3)); + /// struct TreeNode { + /// value: T, + /// left: Option>>, + /// right: Option>>, + /// } + /// + /// impl TreeNode { + /// fn find<'a>(&'a self, mut predicate: impl FnMut(&T) -> bool) -> Result<&'a T, ()> { + /// let mut f = |t: &'a T| -> ControlFlow<&'a T> { + /// if predicate(t) { + /// ControlFlow::Break(t) + /// } else { + /// ControlFlow::Continue(()) + /// } + /// }; + /// + /// self.traverse_inorder(&mut f).break_ok() + /// } + /// + /// fn traverse_inorder<'a, B>( + /// &'a self, + /// f: &mut impl FnMut(&'a T) -> ControlFlow, + /// ) -> ControlFlow { + /// if let Some(left) = &self.left { + /// left.traverse_inorder(f)?; + /// } + /// f(&self.value)?; + /// if let Some(right) = &self.right { + /// right.traverse_inorder(f)?; + /// } + /// ControlFlow::Continue(()) + /// } + /// + /// fn leaf(value: T) -> Option>> { + /// Some(Box::new(Self { + /// value, + /// left: None, + /// right: None, + /// })) + /// } + /// } + /// + /// let node = TreeNode { + /// value: 0, + /// left: TreeNode::leaf(1), + /// right: Some(Box::new(TreeNode { + /// value: -1, + /// left: TreeNode::leaf(5), + /// right: TreeNode::leaf(2), + /// })), + /// }; + /// + /// let res = node.find(|val: &i32| *val > 3); + /// assert_eq!(res, Ok(&5)); /// ``` #[inline] #[unstable(feature = "control_flow_ok", issue = "140266")] @@ -250,8 +302,59 @@ impl ControlFlow { /// /// use std::ops::ControlFlow; /// - /// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").continue_ok(), Err("Stop right there!")); - /// assert_eq!(ControlFlow::<&str, i32>::Continue(3).continue_ok(), Ok(3)); + /// struct TreeNode { + /// value: T, + /// left: Option>>, + /// right: Option>>, + /// } + /// + /// impl TreeNode { + /// fn validate(&self, f: &mut impl FnMut(&T) -> ControlFlow) -> Result<(), B> { + /// self.traverse_inorder(f).continue_ok() + /// } + /// + /// fn traverse_inorder(&self, f: &mut impl FnMut(&T) -> ControlFlow) -> ControlFlow { + /// if let Some(left) = &self.left { + /// left.traverse_inorder(f)?; + /// } + /// f(&self.value)?; + /// if let Some(right) = &self.right { + /// right.traverse_inorder(f)?; + /// } + /// ControlFlow::Continue(()) + /// } + /// + /// fn leaf(value: T) -> Option>> { + /// Some(Box::new(Self { + /// value, + /// left: None, + /// right: None, + /// })) + /// } + /// } + /// + /// let node = TreeNode { + /// value: 0, + /// left: TreeNode::leaf(1), + /// right: Some(Box::new(TreeNode { + /// value: -1, + /// left: TreeNode::leaf(5), + /// right: TreeNode::leaf(2), + /// })), + /// }; + /// + /// let res = node.validate(&mut |val| { + /// if *val < 0 { + /// return ControlFlow::Break("negative value detected"); + /// } + /// + /// if *val > 4 { + /// return ControlFlow::Break("too big value detected"); + /// } + /// + /// ControlFlow::Continue(()) + /// }); + /// assert_eq!(res, Err("too big value detected")); /// ``` #[inline] #[unstable(feature = "control_flow_ok", issue = "140266")] diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index 0a9c0c61c9584..a0c594d2d5961 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -22,6 +22,7 @@ #![feature(const_ref_cell)] #![feature(const_result_trait_fn)] #![feature(const_trait_impl)] +#![feature(control_flow_ok)] #![feature(core_float_math)] #![feature(core_intrinsics)] #![feature(core_intrinsics_fallbacks)] diff --git a/library/coretests/tests/ops/control_flow.rs b/library/coretests/tests/ops/control_flow.rs index eacfd63a6c48f..1df6599ac4a5a 100644 --- a/library/coretests/tests/ops/control_flow.rs +++ b/library/coretests/tests/ops/control_flow.rs @@ -16,3 +16,15 @@ fn control_flow_discriminants_match_result() { discriminant_value(&Result::::Ok(3)), ); } + +#[test] +fn control_flow_break_ok() { + assert_eq!(ControlFlow::::Break('b').break_ok(), Ok('b')); + assert_eq!(ControlFlow::::Continue(3).break_ok(), Err(3)); +} + +#[test] +fn control_flow_continue_ok() { + assert_eq!(ControlFlow::::Break('b').continue_ok(), Err('b')); + assert_eq!(ControlFlow::::Continue(3).continue_ok(), Ok(3)); +} From 6dbac3f09e67c853f343df9d75a7eb213f16c959 Mon Sep 17 00:00:00 2001 From: Jed Brown Date: Wed, 26 Feb 2025 20:06:25 -0700 Subject: [PATCH 03/30] add nvptx_target_feature Add target features for sm_* and ptx*, both of which form a partial order, but cannot be combined to a single partial order. These mirror the LLVM target features, but we do not provide LLVM target processors (which imply both an sm_* and ptx* feature). Add some documentation for the nvptx target. --- compiler/rustc_codegen_llvm/src/llvm_util.rs | 9 +++ compiler/rustc_feature/src/unstable.rs | 1 + compiler/rustc_span/src/symbol.rs | 1 + compiler/rustc_target/src/target_features.rs | 69 ++++++++++++++++++- library/core/src/lib.rs | 1 + .../platform-support/nvptx64-nvidia-cuda.md | 40 +++++++++++ tests/ui/check-cfg/target_feature.stderr | 56 +++++++++++++++ tests/ui/target-feature/gate.rs | 1 + tests/ui/target-feature/gate.stderr | 2 +- 9 files changed, 178 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index 6fd07d562afd8..202b9641e5675 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -262,6 +262,15 @@ pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> Option None, // only existed in 18 ("arm", "fp16") => Some(LLVMFeature::new("fullfp16")), + // NVPTX targets added in LLVM 20 + ("nvptx64", "sm_100") if get_version().0 < 20 => None, + ("nvptx64", "sm_100a") if get_version().0 < 20 => None, + ("nvptx64", "sm_101") if get_version().0 < 20 => None, + ("nvptx64", "sm_101a") if get_version().0 < 20 => None, + ("nvptx64", "sm_120") if get_version().0 < 20 => None, + ("nvptx64", "sm_120a") if get_version().0 < 20 => None, + ("nvptx64", "ptx86") if get_version().0 < 20 => None, + ("nvptx64", "ptx87") if get_version().0 < 20 => None, // Filter out features that are not supported by the current LLVM version ("loongarch64", "div32" | "lam-bh" | "lamcas" | "ld-seq-sa" | "scq") if get_version().0 < 20 => diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 91715851226bb..bc48b45bce17f 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -329,6 +329,7 @@ declare_features! ( (unstable, m68k_target_feature, "1.85.0", Some(134328)), (unstable, mips_target_feature, "1.27.0", Some(44839)), (unstable, movrs_target_feature, "1.88.0", Some(137976)), + (unstable, nvptx_target_feature, "CURRENT_RUSTC_VERSION", Some(44839)), (unstable, powerpc_target_feature, "1.27.0", Some(44839)), (unstable, prfchw_target_feature, "1.78.0", Some(44839)), (unstable, riscv_target_feature, "1.45.0", Some(44839)), diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index da69f6c44927b..b0dd144bf47e4 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1509,6 +1509,7 @@ symbols! { not, notable_trait, note, + nvptx_target_feature, object_safe_for_dispatch, of, off, diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index 3eea1e070a669..3449c16ee4aea 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -517,6 +517,71 @@ const MIPS_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ // tidy-alphabetical-end ]; +const NVPTX_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ + // tidy-alphabetical-start + ("sm_20", Unstable(sym::nvptx_target_feature), &[]), + ("sm_21", Unstable(sym::nvptx_target_feature), &["sm_20"]), + ("sm_30", Unstable(sym::nvptx_target_feature), &["sm_21"]), + ("sm_32", Unstable(sym::nvptx_target_feature), &["sm_30"]), + ("sm_35", Unstable(sym::nvptx_target_feature), &["sm_32"]), + ("sm_37", Unstable(sym::nvptx_target_feature), &["sm_35"]), + ("sm_50", Unstable(sym::nvptx_target_feature), &["sm_37"]), + ("sm_52", Unstable(sym::nvptx_target_feature), &["sm_50"]), + ("sm_53", Unstable(sym::nvptx_target_feature), &["sm_52"]), + ("sm_60", Unstable(sym::nvptx_target_feature), &["sm_53"]), + ("sm_61", Unstable(sym::nvptx_target_feature), &["sm_60"]), + ("sm_62", Unstable(sym::nvptx_target_feature), &["sm_61"]), + ("sm_70", Unstable(sym::nvptx_target_feature), &["sm_62"]), + ("sm_72", Unstable(sym::nvptx_target_feature), &["sm_70"]), + ("sm_75", Unstable(sym::nvptx_target_feature), &["sm_72"]), + ("sm_80", Unstable(sym::nvptx_target_feature), &["sm_75"]), + ("sm_86", Unstable(sym::nvptx_target_feature), &["sm_80"]), + ("sm_87", Unstable(sym::nvptx_target_feature), &["sm_86"]), + ("sm_89", Unstable(sym::nvptx_target_feature), &["sm_87"]), + ("sm_90", Unstable(sym::nvptx_target_feature), &["sm_89"]), + ("sm_90a", Unstable(sym::nvptx_target_feature), &["sm_90"]), + // tidy-alphabetical-end + // tidy-alphabetical-start + ("sm_100", Unstable(sym::nvptx_target_feature), &["sm_90"]), + ("sm_100a", Unstable(sym::nvptx_target_feature), &["sm_100"]), + ("sm_101", Unstable(sym::nvptx_target_feature), &["sm_100"]), + ("sm_101a", Unstable(sym::nvptx_target_feature), &["sm_101"]), + ("sm_120", Unstable(sym::nvptx_target_feature), &["sm_101"]), + ("sm_120a", Unstable(sym::nvptx_target_feature), &["sm_120"]), + // tidy-alphabetical-end + // tidy-alphabetical-start + ("ptx32", Unstable(sym::nvptx_target_feature), &[]), + ("ptx40", Unstable(sym::nvptx_target_feature), &["ptx32"]), + ("ptx41", Unstable(sym::nvptx_target_feature), &["ptx40"]), + ("ptx42", Unstable(sym::nvptx_target_feature), &["ptx41"]), + ("ptx43", Unstable(sym::nvptx_target_feature), &["ptx42"]), + ("ptx50", Unstable(sym::nvptx_target_feature), &["ptx43"]), + ("ptx60", Unstable(sym::nvptx_target_feature), &["ptx50"]), + ("ptx61", Unstable(sym::nvptx_target_feature), &["ptx60"]), + ("ptx62", Unstable(sym::nvptx_target_feature), &["ptx61"]), + ("ptx63", Unstable(sym::nvptx_target_feature), &["ptx62"]), + ("ptx64", Unstable(sym::nvptx_target_feature), &["ptx63"]), + ("ptx65", Unstable(sym::nvptx_target_feature), &["ptx64"]), + ("ptx70", Unstable(sym::nvptx_target_feature), &["ptx65"]), + ("ptx71", Unstable(sym::nvptx_target_feature), &["ptx70"]), + ("ptx72", Unstable(sym::nvptx_target_feature), &["ptx71"]), + ("ptx73", Unstable(sym::nvptx_target_feature), &["ptx72"]), + ("ptx74", Unstable(sym::nvptx_target_feature), &["ptx73"]), + ("ptx75", Unstable(sym::nvptx_target_feature), &["ptx74"]), + ("ptx76", Unstable(sym::nvptx_target_feature), &["ptx75"]), + ("ptx77", Unstable(sym::nvptx_target_feature), &["ptx76"]), + ("ptx78", Unstable(sym::nvptx_target_feature), &["ptx77"]), + ("ptx80", Unstable(sym::nvptx_target_feature), &["ptx78"]), + ("ptx81", Unstable(sym::nvptx_target_feature), &["ptx80"]), + ("ptx82", Unstable(sym::nvptx_target_feature), &["ptx81"]), + ("ptx83", Unstable(sym::nvptx_target_feature), &["ptx82"]), + ("ptx84", Unstable(sym::nvptx_target_feature), &["ptx83"]), + ("ptx85", Unstable(sym::nvptx_target_feature), &["ptx84"]), + ("ptx86", Unstable(sym::nvptx_target_feature), &["ptx85"]), + ("ptx87", Unstable(sym::nvptx_target_feature), &["ptx86"]), + // tidy-alphabetical-end +]; + static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ // tidy-alphabetical-start ("a", Stable, &["zaamo", "zalrsc"]), @@ -782,6 +847,7 @@ pub fn all_rust_features() -> impl Iterator { .chain(HEXAGON_FEATURES.iter()) .chain(POWERPC_FEATURES.iter()) .chain(MIPS_FEATURES.iter()) + .chain(NVPTX_FEATURES.iter()) .chain(RISCV_FEATURES.iter()) .chain(WASM_FEATURES.iter()) .chain(BPF_FEATURES.iter()) @@ -847,6 +913,7 @@ impl Target { "x86" | "x86_64" => X86_FEATURES, "hexagon" => HEXAGON_FEATURES, "mips" | "mips32r6" | "mips64" | "mips64r6" => MIPS_FEATURES, + "nvptx64" => NVPTX_FEATURES, "powerpc" | "powerpc64" => POWERPC_FEATURES, "riscv32" | "riscv64" => RISCV_FEATURES, "wasm32" | "wasm64" => WASM_FEATURES, @@ -873,7 +940,7 @@ impl Target { "sparc" | "sparc64" => SPARC_FEATURES_FOR_CORRECT_VECTOR_ABI, "hexagon" => HEXAGON_FEATURES_FOR_CORRECT_VECTOR_ABI, "mips" | "mips32r6" | "mips64" | "mips64r6" => MIPS_FEATURES_FOR_CORRECT_VECTOR_ABI, - "bpf" | "m68k" => &[], // no vector ABI + "nvptx64" | "bpf" | "m68k" => &[], // no vector ABI "csky" => CSKY_FEATURES_FOR_CORRECT_VECTOR_ABI, // FIXME: for some tier3 targets, we are overly cautious and always give warnings // when passing args in vector registers. diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 39d5399101da6..4ff142bf5d05f 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -192,6 +192,7 @@ #![feature(hexagon_target_feature)] #![feature(loongarch_target_feature)] #![feature(mips_target_feature)] +#![feature(nvptx_target_feature)] #![feature(powerpc_target_feature)] #![feature(riscv_target_feature)] #![feature(rtm_target_feature)] diff --git a/src/doc/rustc/src/platform-support/nvptx64-nvidia-cuda.md b/src/doc/rustc/src/platform-support/nvptx64-nvidia-cuda.md index 106ec562bfc79..36598982481bf 100644 --- a/src/doc/rustc/src/platform-support/nvptx64-nvidia-cuda.md +++ b/src/doc/rustc/src/platform-support/nvptx64-nvidia-cuda.md @@ -10,6 +10,46 @@ platform. [@RDambrosio016](https://github.com/RDambrosio016) [@kjetilkjeka](https://github.com/kjetilkjeka) +## Requirements + +This target is `no_std` and will typically be built with crate-type `cdylib` and `-C linker-flavor=llbc`, which generates PTX. +The necessary components for this workflow are: + +- `rustup toolchain add nightly` +- `rustup component add llvm-tools --toolchain nightly` +- `rustup component add llvm-bitcode-linker --toolchain nightly` + +There are two options for using the core library: + +- `rustup component add rust-src --toolchain nightly` and build using `-Z build-std=core`. +- `rustup target add nvptx64-nvidia-cuda --toolchain nightly` + +### Target and features + +It is generally necessary to specify the target, such as `-C target-cpu=sm_89`, because the default is very old. This implies two target features: `sm_89` and `ptx78` (and all preceding features within `sm_*` and `ptx*`). Rust will default to using the oldest PTX version that supports the target processor (see [this table](https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#release-notes-ptx-release-history)), which maximizes driver compatibility. +One can use `-C target-feature=+ptx80` to choose a later PTX version without changing the target (the default in this case, `ptx78`, requires CUDA driver version 11.8, while `ptx80` would require driver version 12.0). +Later PTX versions may allow more efficient code generation. + +Although Rust follows LLVM in representing `ptx*` and `sm_*` as target features, they should be thought of as having crate granularity, set via (either via `-Ctarget-cpu` and optionally `-Ctarget-feature`). +While the compiler accepts `#[target_feature(enable = "ptx80", enable = "sm_89")]`, it is not supported, may not behave as intended, and may become erroneous in the future. + +## Building Rust kernels + +A `no_std` crate containing one or more functions with `extern "ptx-kernel"` can be compiled to PTX using a command like the following. + +```console +$ RUSTFLAGS='-Ctarget-cpu=sm_89' cargo +nightly rustc --target=nvptx64-nvidia-cuda -Zbuild-std=core --crate-type=cdylib -- -Clinker-flavor=llbc -Zunstable-options +``` + +Intrinsics in `core::arch::nvptx` may use `#[cfg(target_feature = "...")]`, thus it's necessary to use `-Zbuild-std=core` with appropriate `RUSTFLAGS`. The following components are needed for this workflow: + +```console +$ rustup component add rust-src --toolchain nightly +$ rustup component add llvm-tools --toolchain nightly +$ rustup component add llvm-bitcode-linker --toolchain nightly +``` + + $DIR/gate.rs:29:18 + --> $DIR/gate.rs:30:18 | LL | #[target_feature(enable = "x87")] | ^^^^^^^^^^^^^^ From 35a485ddd86229101c4c17d9167f23cf75cae644 Mon Sep 17 00:00:00 2001 From: Jed Brown Date: Wed, 21 May 2025 22:08:51 -0600 Subject: [PATCH 04/30] target-feature: enable rust target features implied by target-cpu Normally LLVM and rustc agree about what features are implied by target-cpu, but for NVPTX, LLVM considers sm_* and ptx* features to be exclusive, which makes sense for codegen purposes. But in Rust, we want to think of them as: sm_{sver} means that the target supports the hardware features of sver ptx{pver} means the driver supports PTX ISA pver Intrinsics usually require a minimum sm_{sver} and ptx{pver}. Prior to this commit, -Ctarget-cpu=sm_70 would activate only sm_70 and ptx60 (the minimum PTX version that supports sm_70, which maximizes driver compatibility). With this commit, it also activates all the implied target features (sm_20, ..., sm_62; ptx32, ..., ptx50). --- compiler/rustc_codegen_llvm/src/llvm_util.rs | 9 ++---- .../rustc_codegen_ssa/src/target_features.rs | 15 ++++++++-- .../target-feature/implied-features-nvptx.rs | 28 +++++++++++++++++++ 3 files changed, 44 insertions(+), 8 deletions(-) create mode 100644 tests/ui/target-feature/implied-features-nvptx.rs diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index 202b9641e5675..2c1882e24bed5 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -333,15 +333,12 @@ pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> Option TargetConfig { - // Add base features for the target. - // We do *not* add the -Ctarget-features there, and instead duplicate the logic for that below. - // The reason is that if LLVM considers a feature implied but we do not, we don't want that to - // show up in `cfg`. That way, `cfg` is entirely under our control -- except for the handling of - // the target CPU, that is still expanded to target features (with all their implied features) - // by LLVM. let target_machine = create_informational_target_machine(sess, true); let (unstable_target_features, target_features) = cfg_target_feature(sess, |feature| { + // This closure determines whether the target CPU has the feature according to LLVM. We do + // *not* consider the `-Ctarget-feature`s here, as that will be handled later in + // `cfg_target_feature`. if let Some(feat) = to_llvm_features(sess, feature) { // All the LLVM features this expands to must be enabled. for llvm_feature in feat { diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index 67ac619091bea..e291fb8649c19 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -224,7 +224,10 @@ fn parse_rust_feature_flag<'a>( /// 2nd component of the return value, respectively). /// /// `target_base_has_feature` should check whether the given feature (a Rust feature name!) is -/// enabled in the "base" target machine, i.e., without applying `-Ctarget-feature`. +/// enabled in the "base" target machine, i.e., without applying `-Ctarget-feature`. Note that LLVM +/// may consider features to be implied that we do not and vice-versa. We want `cfg` to be entirely +/// consistent with Rust feature implications, and thus only consult LLVM to expand the target CPU +/// to target features. /// /// We do not have to worry about RUSTC_SPECIFIC_FEATURES here, those are handled elsewhere. pub fn cfg_target_feature( @@ -238,7 +241,15 @@ pub fn cfg_target_feature( .rust_target_features() .iter() .filter(|(feature, _, _)| target_base_has_feature(feature)) - .map(|(feature, _, _)| Symbol::intern(feature)) + .flat_map(|(base_feature, _, _)| { + // Expand the direct base feature into all transitively-implied features. Note that we + // cannot simply use the `implied` field of the tuple since that only contains + // directly-implied features. + // + // Iteration order is irrelevant because we're collecting into an `UnordSet`. + #[allow(rustc::potential_query_instability)] + sess.target.implied_target_features(base_feature).into_iter().map(|f| Symbol::intern(f)) + }) .collect(); // Add enabled and remove disabled features. diff --git a/tests/ui/target-feature/implied-features-nvptx.rs b/tests/ui/target-feature/implied-features-nvptx.rs new file mode 100644 index 0000000000000..1550c99f67a8d --- /dev/null +++ b/tests/ui/target-feature/implied-features-nvptx.rs @@ -0,0 +1,28 @@ +//@ assembly-output: ptx-linker +//@ compile-flags: --crate-type cdylib -C target-cpu=sm_80 -Z unstable-options -Clinker-flavor=llbc +//@ only-nvptx64 +//@ build-pass +#![no_std] +#![allow(dead_code)] + +#[panic_handler] +pub fn panic(_info: &core::panic::PanicInfo) -> ! { + loop {} +} + +// -Ctarget-cpu=sm_80 directly enables sm_80 and ptx70 +#[cfg(not(all(target_feature = "sm_80", target_feature = "ptx70")))] +compile_error!("direct target features not enabled"); + +// -Ctarget-cpu=sm_80 implies all earlier sm_* and ptx* features. +#[cfg(not(all( + target_feature = "sm_60", + target_feature = "sm_70", + target_feature = "ptx50", + target_feature = "ptx60", +)))] +compile_error!("implied target features not enabled"); + +// -Ctarget-cpu=sm_80 implies all earlier sm_* and ptx* features. +#[cfg(target_feature = "ptx71")] +compile_error!("sm_80 requires only ptx70, but ptx71 enabled"); From 4653b7acbdd50f14d35f5b2f95c3af765c0799ec Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Fri, 18 Jul 2025 13:18:56 +0000 Subject: [PATCH 05/30] Stabilize const `TypeId::of` --- library/core/src/any.rs | 4 ++-- tests/ui/const-generics/issues/issue-90318.rs | 1 - tests/ui/const-generics/issues/issue-90318.stderr | 4 ++-- tests/ui/consts/const-typeid-of-rpass.rs | 2 -- tests/ui/consts/const_cmp_type_id.rs | 2 +- tests/ui/consts/const_transmute_type_id.rs | 2 +- tests/ui/consts/const_transmute_type_id2.rs | 2 +- tests/ui/consts/const_transmute_type_id3.rs | 2 +- tests/ui/consts/const_transmute_type_id4.rs | 2 +- tests/ui/consts/const_transmute_type_id5.rs | 2 +- tests/ui/consts/issue-102117.rs | 2 -- tests/ui/consts/issue-102117.stderr | 4 ++-- tests/ui/consts/issue-73976-monomorphic.rs | 1 - tests/ui/consts/issue-73976-polymorphic.rs | 1 - tests/ui/consts/issue-73976-polymorphic.stderr | 4 ++-- 15 files changed, 14 insertions(+), 21 deletions(-) diff --git a/library/core/src/any.rs b/library/core/src/any.rs index 38393379a78a7..ceb9748e7feb9 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -725,7 +725,7 @@ unsafe impl Send for TypeId {} unsafe impl Sync for TypeId {} #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_type_id", issue = "77125")] +#[rustc_const_unstable(feature = "const_cmp", issue = "143800")] impl const PartialEq for TypeId { #[inline] fn eq(&self, other: &Self) -> bool { @@ -773,7 +773,7 @@ impl TypeId { /// ``` #[must_use] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_type_id", issue = "77125")] + #[rustc_const_stable(feature = "const_type_id", since = "CURRENT_RUSTC_VERSION")] pub const fn of() -> TypeId { const { intrinsics::type_id::() } } diff --git a/tests/ui/const-generics/issues/issue-90318.rs b/tests/ui/const-generics/issues/issue-90318.rs index 239171217ebab..35b0dd216a1af 100644 --- a/tests/ui/const-generics/issues/issue-90318.rs +++ b/tests/ui/const-generics/issues/issue-90318.rs @@ -1,4 +1,3 @@ -#![feature(const_type_id)] #![feature(generic_const_exprs)] #![feature(const_trait_impl, const_cmp)] #![feature(core_intrinsics)] diff --git a/tests/ui/const-generics/issues/issue-90318.stderr b/tests/ui/const-generics/issues/issue-90318.stderr index 7031230db91c3..f13fd795d7a10 100644 --- a/tests/ui/const-generics/issues/issue-90318.stderr +++ b/tests/ui/const-generics/issues/issue-90318.stderr @@ -1,5 +1,5 @@ error: overly complex generic constant - --> $DIR/issue-90318.rs:15:8 + --> $DIR/issue-90318.rs:14:8 | LL | If<{ TypeId::of::() != TypeId::of::<()>() }>: True, | ^^-----------------^^^^^^^^^^^^^^^^^^^^^^^^ @@ -10,7 +10,7 @@ LL | If<{ TypeId::of::() != TypeId::of::<()>() }>: True, = note: this operation may be supported in the future error: overly complex generic constant - --> $DIR/issue-90318.rs:22:8 + --> $DIR/issue-90318.rs:21:8 | LL | If<{ TypeId::of::() != TypeId::of::<()>() }>: True, | ^^-----------------^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/consts/const-typeid-of-rpass.rs b/tests/ui/consts/const-typeid-of-rpass.rs index 15ffdd1e83a2a..30f4107089333 100644 --- a/tests/ui/consts/const-typeid-of-rpass.rs +++ b/tests/ui/consts/const-typeid-of-rpass.rs @@ -1,6 +1,4 @@ //@ run-pass -#![feature(const_type_id)] -#![feature(core_intrinsics)] use std::any::TypeId; diff --git a/tests/ui/consts/const_cmp_type_id.rs b/tests/ui/consts/const_cmp_type_id.rs index db2d50f4d22c9..e312c0b75d52b 100644 --- a/tests/ui/consts/const_cmp_type_id.rs +++ b/tests/ui/consts/const_cmp_type_id.rs @@ -1,5 +1,5 @@ //@ compile-flags: -Znext-solver -#![feature(const_type_id, const_trait_impl, const_cmp)] +#![feature(const_trait_impl, const_cmp)] use std::any::TypeId; diff --git a/tests/ui/consts/const_transmute_type_id.rs b/tests/ui/consts/const_transmute_type_id.rs index a2d4cf378309d..98783ad5b81b3 100644 --- a/tests/ui/consts/const_transmute_type_id.rs +++ b/tests/ui/consts/const_transmute_type_id.rs @@ -1,4 +1,4 @@ -#![feature(const_type_id, const_trait_impl, const_cmp)] +#![feature(const_trait_impl, const_cmp)] use std::any::TypeId; diff --git a/tests/ui/consts/const_transmute_type_id2.rs b/tests/ui/consts/const_transmute_type_id2.rs index 3ceb2b942b04a..7e09947b768d2 100644 --- a/tests/ui/consts/const_transmute_type_id2.rs +++ b/tests/ui/consts/const_transmute_type_id2.rs @@ -1,6 +1,6 @@ //@ normalize-stderr: "0x(ff)+" -> "" -#![feature(const_type_id, const_trait_impl, const_cmp)] +#![feature( const_trait_impl, const_cmp)] use std::any::TypeId; diff --git a/tests/ui/consts/const_transmute_type_id3.rs b/tests/ui/consts/const_transmute_type_id3.rs index f1bb8cddf774b..77c469d42f50d 100644 --- a/tests/ui/consts/const_transmute_type_id3.rs +++ b/tests/ui/consts/const_transmute_type_id3.rs @@ -1,7 +1,7 @@ //! Test that all bytes of a TypeId must have the //! TypeId marker provenance. -#![feature(const_type_id, const_trait_impl, const_cmp)] +#![feature( const_trait_impl, const_cmp)] use std::any::TypeId; diff --git a/tests/ui/consts/const_transmute_type_id4.rs b/tests/ui/consts/const_transmute_type_id4.rs index 0ea75f2a2f4de..bedd6084a16be 100644 --- a/tests/ui/consts/const_transmute_type_id4.rs +++ b/tests/ui/consts/const_transmute_type_id4.rs @@ -1,4 +1,4 @@ -#![feature(const_type_id, const_trait_impl, const_cmp)] +#![feature(const_trait_impl, const_cmp)] use std::any::TypeId; diff --git a/tests/ui/consts/const_transmute_type_id5.rs b/tests/ui/consts/const_transmute_type_id5.rs index ae0429f8dbb63..7f9a34104a35a 100644 --- a/tests/ui/consts/const_transmute_type_id5.rs +++ b/tests/ui/consts/const_transmute_type_id5.rs @@ -1,7 +1,7 @@ //! Test that we require an equal TypeId to have an integer part that properly //! reflects the type id hash. -#![feature(const_type_id, const_trait_impl, const_cmp)] +#![feature(const_trait_impl, const_cmp)] use std::any::TypeId; diff --git a/tests/ui/consts/issue-102117.rs b/tests/ui/consts/issue-102117.rs index 6cb9832bcd81b..b7955283a8d81 100644 --- a/tests/ui/consts/issue-102117.rs +++ b/tests/ui/consts/issue-102117.rs @@ -1,5 +1,3 @@ -#![feature(const_type_id)] - use std::alloc::Layout; use std::any::TypeId; use std::mem::transmute; diff --git a/tests/ui/consts/issue-102117.stderr b/tests/ui/consts/issue-102117.stderr index da92db87f1821..cea355d01d7b4 100644 --- a/tests/ui/consts/issue-102117.stderr +++ b/tests/ui/consts/issue-102117.stderr @@ -1,5 +1,5 @@ error[E0310]: the parameter type `T` may not live long enough - --> $DIR/issue-102117.rs:19:26 + --> $DIR/issue-102117.rs:17:26 | LL | type_id: TypeId::of::(), | ^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL | pub fn new() -> &'static Self { | +++++++++ error[E0310]: the parameter type `T` may not live long enough - --> $DIR/issue-102117.rs:19:26 + --> $DIR/issue-102117.rs:17:26 | LL | type_id: TypeId::of::(), | ^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/consts/issue-73976-monomorphic.rs b/tests/ui/consts/issue-73976-monomorphic.rs index 5f364cd995e02..2867b836f4826 100644 --- a/tests/ui/consts/issue-73976-monomorphic.rs +++ b/tests/ui/consts/issue-73976-monomorphic.rs @@ -5,7 +5,6 @@ // will be properly rejected. This test will ensure that monomorphic use of these // would not be wrongly rejected in patterns. -#![feature(const_type_id)] #![feature(const_type_name)] #![feature(const_trait_impl)] #![feature(const_cmp)] diff --git a/tests/ui/consts/issue-73976-polymorphic.rs b/tests/ui/consts/issue-73976-polymorphic.rs index 98b4005792dbc..db06706a970cb 100644 --- a/tests/ui/consts/issue-73976-polymorphic.rs +++ b/tests/ui/consts/issue-73976-polymorphic.rs @@ -5,7 +5,6 @@ // This test case should either run-pass or be rejected at compile time. // Currently we just disallow this usage and require pattern is monomorphic. -#![feature(const_type_id)] #![feature(const_type_name)] use std::any::{self, TypeId}; diff --git a/tests/ui/consts/issue-73976-polymorphic.stderr b/tests/ui/consts/issue-73976-polymorphic.stderr index ec9512a261632..41a5e804c676d 100644 --- a/tests/ui/consts/issue-73976-polymorphic.stderr +++ b/tests/ui/consts/issue-73976-polymorphic.stderr @@ -1,5 +1,5 @@ error[E0158]: constant pattern cannot depend on generic parameters - --> $DIR/issue-73976-polymorphic.rs:20:37 + --> $DIR/issue-73976-polymorphic.rs:19:37 | LL | impl GetTypeId { | ----------------------------- @@ -12,7 +12,7 @@ LL | matches!(GetTypeId::::VALUE, GetTypeId::::VALUE) | ^^^^^^^^^^^^^^^^^^^^^ `const` depends on a generic parameter error[E0158]: constant pattern cannot depend on generic parameters - --> $DIR/issue-73976-polymorphic.rs:31:42 + --> $DIR/issue-73976-polymorphic.rs:30:42 | LL | impl GetTypeNameLen { | ---------------------------------- From 288a5654514938b973a75e0e1de64ee702170661 Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Wed, 23 Jul 2025 09:14:12 -0700 Subject: [PATCH 06/30] Upgrade semicolon_in_expressions_from_macros from warn to deny This is already warn-by-default, and a future compatibility warning (FCW) that warns in dependencies. Upgrade it to deny-by-default, as the next step towards hard error. --- compiler/rustc_lint_defs/src/builtin.rs | 2 +- ...arn-semicolon-in-expressions-from-macros.rs | 5 ++--- ...semicolon-in-expressions-from-macros.stderr | 18 +++++++++--------- tests/ui/macros/lint-trailing-macro-call.rs | 4 +--- .../ui/macros/lint-trailing-macro-call.stderr | 18 +++++++++--------- tests/ui/macros/macro-context.rs | 2 +- tests/ui/macros/macro-context.stderr | 14 +++++++------- .../macros/macro-in-expression-context.fixed | 4 ++-- tests/ui/macros/macro-in-expression-context.rs | 4 ++-- .../macros/macro-in-expression-context.stderr | 14 +++++++------- 10 files changed, 41 insertions(+), 44 deletions(-) diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index a08d68e2d1532..277a87f9bfc0f 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -2838,7 +2838,7 @@ declare_lint! { /// [issue #79813]: https://github.com/rust-lang/rust/issues/79813 /// [future-incompatible]: ../index.md#future-incompatible-lints pub SEMICOLON_IN_EXPRESSIONS_FROM_MACROS, - Warn, + Deny, "trailing semicolon in macro body used as expression", @future_incompatible = FutureIncompatibleInfo { reason: FutureIncompatibilityReason::FutureReleaseError, diff --git a/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.rs b/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.rs index 05fbfec2ae577..8ec70a17864ab 100644 --- a/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.rs +++ b/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.rs @@ -1,9 +1,8 @@ -//@ check-pass -// Ensure that trailing semicolons cause warnings by default +// Ensure that trailing semicolons cause errors by default macro_rules! foo { () => { - true; //~ WARN trailing semicolon in macro + true; //~ ERROR trailing semicolon in macro //~| WARN this was previously } } diff --git a/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.stderr b/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.stderr index 0fec4996f1a0a..99cdcafab39a4 100644 --- a/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.stderr +++ b/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.stderr @@ -1,5 +1,5 @@ -warning: trailing semicolon in macro used in expression position - --> $DIR/warn-semicolon-in-expressions-from-macros.rs:6:13 +error: trailing semicolon in macro used in expression position + --> $DIR/warn-semicolon-in-expressions-from-macros.rs:5:13 | LL | true; | ^ @@ -9,14 +9,14 @@ LL | _ => foo!() | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79813 - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) -warning: 1 warning emitted +error: aborting due to 1 previous error Future incompatibility report: Future breakage diagnostic: -warning: trailing semicolon in macro used in expression position - --> $DIR/warn-semicolon-in-expressions-from-macros.rs:6:13 +error: trailing semicolon in macro used in expression position + --> $DIR/warn-semicolon-in-expressions-from-macros.rs:5:13 | LL | true; | ^ @@ -26,6 +26,6 @@ LL | _ => foo!() | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79813 - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/macros/lint-trailing-macro-call.rs b/tests/ui/macros/lint-trailing-macro-call.rs index 78b861f1df17a..25fa91062c434 100644 --- a/tests/ui/macros/lint-trailing-macro-call.rs +++ b/tests/ui/macros/lint-trailing-macro-call.rs @@ -1,12 +1,10 @@ -//@ check-pass -// // Ensures that we properly lint // a removed 'expression' resulting from a macro // in trailing expression position macro_rules! expand_it { () => { - #[cfg(false)] 25; //~ WARN trailing semicolon in macro + #[cfg(false)] 25; //~ ERROR trailing semicolon in macro //~| WARN this was previously } } diff --git a/tests/ui/macros/lint-trailing-macro-call.stderr b/tests/ui/macros/lint-trailing-macro-call.stderr index 223b85e112ed6..3fd1ea813459f 100644 --- a/tests/ui/macros/lint-trailing-macro-call.stderr +++ b/tests/ui/macros/lint-trailing-macro-call.stderr @@ -1,5 +1,5 @@ -warning: trailing semicolon in macro used in expression position - --> $DIR/lint-trailing-macro-call.rs:9:25 +error: trailing semicolon in macro used in expression position + --> $DIR/lint-trailing-macro-call.rs:7:25 | LL | #[cfg(false)] 25; | ^ @@ -11,14 +11,14 @@ LL | expand_it!() = note: for more information, see issue #79813 = note: macro invocations at the end of a block are treated as expressions = note: to ignore the value produced by the macro, add a semicolon after the invocation of `expand_it` - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `expand_it` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `expand_it` (in Nightly builds, run with -Z macro-backtrace for more info) -warning: 1 warning emitted +error: aborting due to 1 previous error Future incompatibility report: Future breakage diagnostic: -warning: trailing semicolon in macro used in expression position - --> $DIR/lint-trailing-macro-call.rs:9:25 +error: trailing semicolon in macro used in expression position + --> $DIR/lint-trailing-macro-call.rs:7:25 | LL | #[cfg(false)] 25; | ^ @@ -30,6 +30,6 @@ LL | expand_it!() = note: for more information, see issue #79813 = note: macro invocations at the end of a block are treated as expressions = note: to ignore the value produced by the macro, add a semicolon after the invocation of `expand_it` - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `expand_it` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `expand_it` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/macros/macro-context.rs b/tests/ui/macros/macro-context.rs index a31470263a0a5..e1c24ba8b5705 100644 --- a/tests/ui/macros/macro-context.rs +++ b/tests/ui/macros/macro-context.rs @@ -6,7 +6,7 @@ macro_rules! m { //~| ERROR macro expansion ignores `;` //~| ERROR cannot find type `i` in this scope //~| ERROR cannot find value `i` in this scope - //~| WARN trailing semicolon in macro + //~| ERROR trailing semicolon in macro //~| WARN this was previously } diff --git a/tests/ui/macros/macro-context.stderr b/tests/ui/macros/macro-context.stderr index 4820a43f00c79..6b49c05f360da 100644 --- a/tests/ui/macros/macro-context.stderr +++ b/tests/ui/macros/macro-context.stderr @@ -64,7 +64,7 @@ LL | let i = m!(); | = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) -warning: trailing semicolon in macro used in expression position +error: trailing semicolon in macro used in expression position --> $DIR/macro-context.rs:3:15 | LL | () => ( i ; typeof ); @@ -75,15 +75,15 @@ LL | let i = m!(); | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79813 - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 6 previous errors; 1 warning emitted +error: aborting due to 7 previous errors Some errors have detailed explanations: E0412, E0425. For more information about an error, try `rustc --explain E0412`. Future incompatibility report: Future breakage diagnostic: -warning: trailing semicolon in macro used in expression position +error: trailing semicolon in macro used in expression position --> $DIR/macro-context.rs:3:15 | LL | () => ( i ; typeof ); @@ -94,6 +94,6 @@ LL | let i = m!(); | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79813 - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/macros/macro-in-expression-context.fixed b/tests/ui/macros/macro-in-expression-context.fixed index 7c830707ffd9d..52e1b429e48ac 100644 --- a/tests/ui/macros/macro-in-expression-context.fixed +++ b/tests/ui/macros/macro-in-expression-context.fixed @@ -3,12 +3,12 @@ macro_rules! foo { () => { assert_eq!("A", "A"); - //~^ WARN trailing semicolon in macro + //~^ ERROR trailing semicolon in macro //~| WARN this was previously //~| NOTE macro invocations at the end of a block //~| NOTE to ignore the value produced by the macro //~| NOTE for more information - //~| NOTE `#[warn(semicolon_in_expressions_from_macros)]` on by default + //~| NOTE `#[deny(semicolon_in_expressions_from_macros)]` on by default assert_eq!("B", "B"); } //~^^ ERROR macro expansion ignores `assert_eq` and any tokens following diff --git a/tests/ui/macros/macro-in-expression-context.rs b/tests/ui/macros/macro-in-expression-context.rs index da95017aa5f74..5c560e78dad4c 100644 --- a/tests/ui/macros/macro-in-expression-context.rs +++ b/tests/ui/macros/macro-in-expression-context.rs @@ -3,12 +3,12 @@ macro_rules! foo { () => { assert_eq!("A", "A"); - //~^ WARN trailing semicolon in macro + //~^ ERROR trailing semicolon in macro //~| WARN this was previously //~| NOTE macro invocations at the end of a block //~| NOTE to ignore the value produced by the macro //~| NOTE for more information - //~| NOTE `#[warn(semicolon_in_expressions_from_macros)]` on by default + //~| NOTE `#[deny(semicolon_in_expressions_from_macros)]` on by default assert_eq!("B", "B"); } //~^^ ERROR macro expansion ignores `assert_eq` and any tokens following diff --git a/tests/ui/macros/macro-in-expression-context.stderr b/tests/ui/macros/macro-in-expression-context.stderr index 43419f2678c22..b04348d701089 100644 --- a/tests/ui/macros/macro-in-expression-context.stderr +++ b/tests/ui/macros/macro-in-expression-context.stderr @@ -13,7 +13,7 @@ help: you might be missing a semicolon here LL | foo!(); | + -warning: trailing semicolon in macro used in expression position +error: trailing semicolon in macro used in expression position --> $DIR/macro-in-expression-context.rs:5:29 | LL | assert_eq!("A", "A"); @@ -26,13 +26,13 @@ LL | foo!() = note: for more information, see issue #79813 = note: macro invocations at the end of a block are treated as expressions = note: to ignore the value produced by the macro, add a semicolon after the invocation of `foo` - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 1 previous error; 1 warning emitted +error: aborting due to 2 previous errors Future incompatibility report: Future breakage diagnostic: -warning: trailing semicolon in macro used in expression position +error: trailing semicolon in macro used in expression position --> $DIR/macro-in-expression-context.rs:5:29 | LL | assert_eq!("A", "A"); @@ -45,6 +45,6 @@ LL | foo!() = note: for more information, see issue #79813 = note: macro invocations at the end of a block are treated as expressions = note: to ignore the value produced by the macro, add a semicolon after the invocation of `foo` - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) From ef608f1f5550602ea14559733677b68d5fe6a1cd Mon Sep 17 00:00:00 2001 From: Noratrieb <48135649+Noratrieb@users.noreply.github.com> Date: Sat, 26 Jul 2025 12:15:19 +0200 Subject: [PATCH 07/30] Introduce `target_spec_enum` macro to avoid duplication With this macro we only need to enumerate every variant once. This saves a lot of duplication already between the definition, the `FromStr` impl and the `ToJson` impl. It also enables us to do further things with it like JSON schema generation. --- compiler/rustc_target/src/lib.rs | 60 ++ compiler/rustc_target/src/spec/mod.rs | 893 ++++++-------------------- 2 files changed, 241 insertions(+), 712 deletions(-) diff --git a/compiler/rustc_target/src/lib.rs b/compiler/rustc_target/src/lib.rs index 91657fef80326..c6a23745b04e7 100644 --- a/compiler/rustc_target/src/lib.rs +++ b/compiler/rustc_target/src/lib.rs @@ -72,3 +72,63 @@ fn find_relative_libdir(sysroot: &Path) -> std::borrow::Cow<'static, str> { Some(libdir) => libdir.into(), } } + +macro_rules! target_spec_enum { + ( + $( #[$attr:meta] )* + pub enum $name:ident { + $( + $( #[$variant_attr:meta] )* + $variant:ident = $string:literal, + )* + } + parse_error_type = $parse_error_type:literal; + ) => { + $( #[$attr] )* + #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] + pub enum $name { + $( + $( #[$variant_attr] )* + $variant, + )* + } + + impl FromStr for $name { + type Err = String; + + fn from_str(s: &str) -> Result { + Ok(match s { + $( $string => Self::$variant, )* + _ => { + let all = [$( concat!("'", $string, "'") ),*].join(", "); + return Err(format!("invalid {}: '{s}'. allowed values: {all}", $parse_error_type)); + } + }) + } + } + + impl $name { + pub fn desc(&self) -> &'static str { + match self { + $( Self::$variant => $string, )* + } + } + } + + impl crate::json::ToJson for $name { + fn to_json(&self) -> crate::json::Json { + self.desc().to_json() + } + } + + crate::json::serde_deserialize_from_str!($name); + + + impl std::fmt::Display for $name { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.desc()) + } + } + }; +} +use target_spec_enum; diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index c64cd9a51b7d2..7cb0e0af46664 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -182,50 +182,15 @@ impl LinkerFlavorCli { } } -#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] -pub enum LldFlavor { - Wasm, - Ld64, - Ld, - Link, -} - -impl LldFlavor { - pub fn as_str(&self) -> &'static str { - match self { - LldFlavor::Wasm => "wasm", - LldFlavor::Ld64 => "darwin", - LldFlavor::Ld => "gnu", - LldFlavor::Link => "link", - } +crate::target_spec_enum! { + pub enum LldFlavor { + Wasm = "wasm", + Ld64 = "darwin", + Ld = "gnu", + Link = "link", } -} -impl FromStr for LldFlavor { - type Err = String; - - fn from_str(s: &str) -> Result { - Ok(match s { - "darwin" => LldFlavor::Ld64, - "gnu" => LldFlavor::Ld, - "link" => LldFlavor::Link, - "wasm" => LldFlavor::Wasm, - _ => { - return Err( - "invalid value for lld flavor: '{s}', expected one of 'darwin', 'gnu', 'link', 'wasm'" - .into(), - ); - } - }) - } -} - -crate::json::serde_deserialize_from_str!(LldFlavor); - -impl ToJson for LldFlavor { - fn to_json(&self) -> Json { - self.as_str().to_json() - } + parse_error_type = "LLD flavor"; } impl LinkerFlavor { @@ -822,10 +787,14 @@ impl LinkerFeatures { } } -#[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)] -pub enum PanicStrategy { - Unwind, - Abort, +crate::target_spec_enum! { + #[derive(Encodable, Decodable, HashStable_Generic)] + pub enum PanicStrategy { + Unwind = "unwind", + Abort = "abort", + } + + parse_error_type = "panic strategy"; } #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)] @@ -837,13 +806,6 @@ pub enum OnBrokenPipe { } impl PanicStrategy { - pub fn desc(&self) -> &str { - match *self { - PanicStrategy::Unwind => "unwind", - PanicStrategy::Abort => "abort", - } - } - pub const fn desc_symbol(&self) -> Symbol { match *self { PanicStrategy::Unwind => sym::unwind, @@ -856,129 +818,27 @@ impl PanicStrategy { } } -impl FromStr for PanicStrategy { - type Err = String; - fn from_str(s: &str) -> Result { - Ok(match s { - "unwind" => PanicStrategy::Unwind, - "abort" => PanicStrategy::Abort, - _ => { - return Err(format!( - "'{}' is not a valid value for \ - panic-strategy. Use 'unwind' or 'abort'.", - s - )); - } - }) +crate::target_spec_enum! { + pub enum RelroLevel { + Full = "full", + Partial = "partial", + Off = "off", + None = "none", } -} -crate::json::serde_deserialize_from_str!(PanicStrategy); - -impl ToJson for PanicStrategy { - fn to_json(&self) -> Json { - match *self { - PanicStrategy::Abort => "abort".to_json(), - PanicStrategy::Unwind => "unwind".to_json(), - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Hash)] -pub enum RelroLevel { - Full, - Partial, - Off, - None, -} - -impl RelroLevel { - pub fn desc(&self) -> &str { - match *self { - RelroLevel::Full => "full", - RelroLevel::Partial => "partial", - RelroLevel::Off => "off", - RelroLevel::None => "none", - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Hash)] -pub enum SymbolVisibility { - Hidden, - Protected, - Interposable, -} - -impl SymbolVisibility { - pub fn desc(&self) -> &str { - match *self { - SymbolVisibility::Hidden => "hidden", - SymbolVisibility::Protected => "protected", - SymbolVisibility::Interposable => "interposable", - } - } + parse_error_type = "relro level"; } -impl FromStr for SymbolVisibility { - type Err = String; - - fn from_str(s: &str) -> Result { - match s { - "hidden" => Ok(SymbolVisibility::Hidden), - "protected" => Ok(SymbolVisibility::Protected), - "interposable" => Ok(SymbolVisibility::Interposable), - _ => Err(format!( - "'{}' is not a valid value for \ - symbol-visibility. Use 'hidden', 'protected, or 'interposable'.", - s - )), - } - } -} - -crate::json::serde_deserialize_from_str!(SymbolVisibility); - -impl ToJson for SymbolVisibility { - fn to_json(&self) -> Json { - match *self { - SymbolVisibility::Hidden => "hidden".to_json(), - SymbolVisibility::Protected => "protected".to_json(), - SymbolVisibility::Interposable => "interposable".to_json(), - } +crate::target_spec_enum! { + pub enum SymbolVisibility { + Hidden = "hidden", + Protected = "protected", + Interposable = "interposable", } -} -impl FromStr for RelroLevel { - type Err = String; - - fn from_str(s: &str) -> Result { - match s { - "full" => Ok(RelroLevel::Full), - "partial" => Ok(RelroLevel::Partial), - "off" => Ok(RelroLevel::Off), - "none" => Ok(RelroLevel::None), - _ => Err(format!( - "'{}' is not a valid value for \ - relro-level. Use 'full', 'partial, 'off', or 'none'.", - s - )), - } - } + parse_error_type = "symbol visibility"; } -crate::json::serde_deserialize_from_str!(RelroLevel); - -impl ToJson for RelroLevel { - fn to_json(&self) -> Json { - match *self { - RelroLevel::Full => "full".to_json(), - RelroLevel::Partial => "partial".to_json(), - RelroLevel::Off => "off".to_json(), - RelroLevel::None => "None".to_json(), - } - } -} #[derive(Clone, Debug, PartialEq, Hash)] pub enum SmallDataThresholdSupport { @@ -1019,76 +879,31 @@ impl ToJson for SmallDataThresholdSupport { } } -#[derive(Clone, Copy, Debug, PartialEq, Hash)] -pub enum MergeFunctions { - Disabled, - Trampolines, - Aliases, -} - -impl MergeFunctions { - pub fn desc(&self) -> &str { - match *self { - MergeFunctions::Disabled => "disabled", - MergeFunctions::Trampolines => "trampolines", - MergeFunctions::Aliases => "aliases", - } +crate::target_spec_enum! { + pub enum MergeFunctions { + Disabled = "disabled", + Trampolines = "trampolines", + Aliases = "aliases", } -} -impl FromStr for MergeFunctions { - type Err = String; - - fn from_str(s: &str) -> Result { - match s { - "disabled" => Ok(MergeFunctions::Disabled), - "trampolines" => Ok(MergeFunctions::Trampolines), - "aliases" => Ok(MergeFunctions::Aliases), - _ => Err(format!( - "'{}' is not a valid value for \ - merge-functions. Use 'disabled', \ - 'trampolines', or 'aliases'.", - s - )), - } - } + parse_error_type = "value for merge-functions"; } -crate::json::serde_deserialize_from_str!(MergeFunctions); - -impl ToJson for MergeFunctions { - fn to_json(&self) -> Json { - match *self { - MergeFunctions::Disabled => "disabled".to_json(), - MergeFunctions::Trampolines => "trampolines".to_json(), - MergeFunctions::Aliases => "aliases".to_json(), - } +crate::target_spec_enum! { + pub enum RelocModel { + Static = "static", + Pic = "pic", + Pie = "pie", + DynamicNoPic = "dynamic-no-pic", + Ropi = "ropi", + Rwpi = "rwpi", + RopiRwpi = "ropi-rwpi", } -} -#[derive(Clone, Copy, PartialEq, Hash, Debug)] -pub enum RelocModel { - Static, - Pic, - Pie, - DynamicNoPic, - Ropi, - Rwpi, - RopiRwpi, + parse_error_type = "relocation model"; } impl RelocModel { - pub fn desc(&self) -> &str { - match *self { - RelocModel::Static => "static", - RelocModel::Pic => "pic", - RelocModel::Pie => "pie", - RelocModel::DynamicNoPic => "dynamic-no-pic", - RelocModel::Ropi => "ropi", - RelocModel::Rwpi => "rwpi", - RelocModel::RopiRwpi => "ropi-rwpi", - } - } pub const fn desc_symbol(&self) -> Symbol { match *self { RelocModel::Static => kw::Static, @@ -1114,236 +929,75 @@ impl RelocModel { } } -impl FromStr for RelocModel { - type Err = String; - - fn from_str(s: &str) -> Result { - Ok(match s { - "static" => RelocModel::Static, - "pic" => RelocModel::Pic, - "pie" => RelocModel::Pie, - "dynamic-no-pic" => RelocModel::DynamicNoPic, - "ropi" => RelocModel::Ropi, - "rwpi" => RelocModel::Rwpi, - "ropi-rwpi" => RelocModel::RopiRwpi, - _ => { - return Err(format!( - "invalid relocation model '{s}'. - Run `rustc --print relocation-models` to \ - see the list of supported values.'" - )); - } - }) - } -} - -crate::json::serde_deserialize_from_str!(RelocModel); - -impl ToJson for RelocModel { - fn to_json(&self) -> Json { - self.desc().to_json() +crate::target_spec_enum! { + pub enum CodeModel { + Tiny = "tiny", + Small = "small", + Kernel = "kernel", + Medium = "medium", + Large = "large", } -} -#[derive(Clone, Copy, PartialEq, Hash, Debug)] -pub enum CodeModel { - Tiny, - Small, - Kernel, - Medium, - Large, + parse_error_type = "code model"; } -impl FromStr for CodeModel { - type Err = String; - - fn from_str(s: &str) -> Result { - Ok(match s { - "tiny" => CodeModel::Tiny, - "small" => CodeModel::Small, - "kernel" => CodeModel::Kernel, - "medium" => CodeModel::Medium, - "large" => CodeModel::Large, - _ => { - return Err(format!( - "'{s}' is not a valid code model. \ - Run `rustc --print code-models` to \ - see the list of supported values." - )); - } - }) - } -} - -crate::json::serde_deserialize_from_str!(CodeModel); - -impl ToJson for CodeModel { - fn to_json(&self) -> Json { - match *self { - CodeModel::Tiny => "tiny", - CodeModel::Small => "small", - CodeModel::Kernel => "kernel", - CodeModel::Medium => "medium", - CodeModel::Large => "large", - } - .to_json() +crate::target_spec_enum! { + /// The float ABI setting to be configured in the LLVM target machine. + pub enum FloatAbi { + Soft = "soft", + Hard = "hard", } -} - -/// The float ABI setting to be configured in the LLVM target machine. -#[derive(Clone, Copy, PartialEq, Hash, Debug)] -pub enum FloatAbi { - Soft, - Hard, -} -impl FromStr for FloatAbi { - type Err = String; - - fn from_str(s: &str) -> Result { - Ok(match s { - "soft" => FloatAbi::Soft, - "hard" => FloatAbi::Hard, - _ => { - return Err(format!( - "'{}' is not a valid value for \ - llvm-floatabi. Use 'soft' or 'hard'.", - s - )); - } - }) - } + parse_error_type = "float abi"; } -crate::json::serde_deserialize_from_str!(FloatAbi); - -impl ToJson for FloatAbi { - fn to_json(&self) -> Json { - match *self { - FloatAbi::Soft => "soft", - FloatAbi::Hard => "hard", - } - .to_json() +crate::target_spec_enum! { + /// The Rustc-specific variant of the ABI used for this target. + pub enum RustcAbi { + /// On x86-32 only: make use of SSE and SSE2 for ABI purposes. + X86Sse2 = "x86-sse2", + /// On x86-32/64 only: do not use any FPU or SIMD registers for the ABI. + X86Softfloat = "x86-softfloat", } -} - -/// The Rustc-specific variant of the ABI used for this target. -#[derive(Clone, Copy, PartialEq, Hash, Debug)] -pub enum RustcAbi { - /// On x86-32 only: make use of SSE and SSE2 for ABI purposes. - X86Sse2, - /// On x86-32/64 only: do not use any FPU or SIMD registers for the ABI. - X86Softfloat, -} - -impl FromStr for RustcAbi { - type Err = String; - fn from_str(s: &str) -> Result { - Ok(match s { - "x86-sse2" => RustcAbi::X86Sse2, - "x86-softfloat" => RustcAbi::X86Softfloat, - _ => { - return Err(format!( - "'{s}' is not a valid value for rustc-abi. \ - Use 'x86-softfloat' or leave the field unset." - )); - } - }) - } + parse_error_type = "rustc abi"; } -crate::json::serde_deserialize_from_str!(RustcAbi); - -impl ToJson for RustcAbi { - fn to_json(&self) -> Json { - match *self { - RustcAbi::X86Sse2 => "x86-sse2", - RustcAbi::X86Softfloat => "x86-softfloat", - } - .to_json() +crate::target_spec_enum! { + pub enum TlsModel { + GeneralDynamic = "global-dynamic", + LocalDynamic = "local-dynamic", + InitialExec = "initial-exec", + LocalExec = "local-exec", + Emulated = "emulated", } -} -#[derive(Clone, Copy, PartialEq, Hash, Debug)] -pub enum TlsModel { - GeneralDynamic, - LocalDynamic, - InitialExec, - LocalExec, - Emulated, + parse_error_type = "TLS model"; } -impl FromStr for TlsModel { - type Err = String; - - fn from_str(s: &str) -> Result { - Ok(match s { - // Note the difference "general" vs "global" difference. The model name is "general", - // but the user-facing option name is "global" for consistency with other compilers. - "global-dynamic" => TlsModel::GeneralDynamic, - "local-dynamic" => TlsModel::LocalDynamic, - "initial-exec" => TlsModel::InitialExec, - "local-exec" => TlsModel::LocalExec, - "emulated" => TlsModel::Emulated, - _ => { - return Err(format!( - "'{s}' is not a valid TLS model. \ - Run `rustc --print tls-models` to \ - see the list of supported values." - )); - } - }) +crate::target_spec_enum! { + /// Everything is flattened to a single enum to make the json encoding/decoding less annoying. + pub enum LinkOutputKind { + /// Dynamically linked non position-independent executable. + DynamicNoPicExe = "dynamic-nopic-exe", + /// Dynamically linked position-independent executable. + DynamicPicExe = "dynamic-pic-exe", + /// Statically linked non position-independent executable. + StaticNoPicExe = "static-nopic-exe", + /// Statically linked position-independent executable. + StaticPicExe = "static-pic-exe", + /// Regular dynamic library ("dynamically linked"). + DynamicDylib = "dynamic-dylib", + /// Dynamic library with bundled libc ("statically linked"). + StaticDylib = "static-dylib", + /// WASI module with a lifetime past the _initialize entry point + WasiReactorExe = "wasi-reactor-exe", } -} - -crate::json::serde_deserialize_from_str!(TlsModel); - -impl ToJson for TlsModel { - fn to_json(&self) -> Json { - match *self { - TlsModel::GeneralDynamic => "global-dynamic", - TlsModel::LocalDynamic => "local-dynamic", - TlsModel::InitialExec => "initial-exec", - TlsModel::LocalExec => "local-exec", - TlsModel::Emulated => "emulated", - } - .to_json() - } -} -/// Everything is flattened to a single enum to make the json encoding/decoding less annoying. -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub enum LinkOutputKind { - /// Dynamically linked non position-independent executable. - DynamicNoPicExe, - /// Dynamically linked position-independent executable. - DynamicPicExe, - /// Statically linked non position-independent executable. - StaticNoPicExe, - /// Statically linked position-independent executable. - StaticPicExe, - /// Regular dynamic library ("dynamically linked"). - DynamicDylib, - /// Dynamic library with bundled libc ("statically linked"). - StaticDylib, - /// WASI module with a lifetime past the _initialize entry point - WasiReactorExe, + parse_error_type = "CRT object kind"; } impl LinkOutputKind { - fn as_str(&self) -> &'static str { - match self { - LinkOutputKind::DynamicNoPicExe => "dynamic-nopic-exe", - LinkOutputKind::DynamicPicExe => "dynamic-pic-exe", - LinkOutputKind::StaticNoPicExe => "static-nopic-exe", - LinkOutputKind::StaticPicExe => "static-pic-exe", - LinkOutputKind::DynamicDylib => "dynamic-dylib", - LinkOutputKind::StaticDylib => "static-dylib", - LinkOutputKind::WasiReactorExe => "wasi-reactor-exe", - } - } - pub fn can_link_dylib(self) -> bool { match self { LinkOutputKind::StaticNoPicExe | LinkOutputKind::StaticPicExe => false, @@ -1356,166 +1010,59 @@ impl LinkOutputKind { } } -impl FromStr for LinkOutputKind { - type Err = String; - - fn from_str(s: &str) -> Result { - Ok(match s { - "dynamic-nopic-exe" => LinkOutputKind::DynamicNoPicExe, - "dynamic-pic-exe" => LinkOutputKind::DynamicPicExe, - "static-nopic-exe" => LinkOutputKind::StaticNoPicExe, - "static-pic-exe" => LinkOutputKind::StaticPicExe, - "dynamic-dylib" => LinkOutputKind::DynamicDylib, - "static-dylib" => LinkOutputKind::StaticDylib, - "wasi-reactor-exe" => LinkOutputKind::WasiReactorExe, - _ => { - return Err(format!( - "invalid value for CRT object kind. \ - Use '(dynamic,static)-(nopic,pic)-exe' or \ - '(dynamic,static)-dylib' or 'wasi-reactor-exe'" - )); - } - }) - } -} - -crate::json::serde_deserialize_from_str!(LinkOutputKind); - -impl fmt::Display for LinkOutputKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(self.as_str()) - } -} - pub type LinkArgs = BTreeMap>>; pub type LinkArgsCli = BTreeMap>>; -/// Which kind of debuginfo does the target use? -/// -/// Useful in determining whether a target supports Split DWARF (a target with -/// `DebuginfoKind::Dwarf` and supporting `SplitDebuginfo::Unpacked` for example). -#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] -pub enum DebuginfoKind { - /// DWARF debuginfo (such as that used on `x86_64_unknown_linux_gnu`). - #[default] - Dwarf, - /// DWARF debuginfo in dSYM files (such as on Apple platforms). - DwarfDsym, - /// Program database files (such as on Windows). - Pdb, -} - -impl DebuginfoKind { - fn as_str(&self) -> &'static str { - match self { - DebuginfoKind::Dwarf => "dwarf", - DebuginfoKind::DwarfDsym => "dwarf-dsym", - DebuginfoKind::Pdb => "pdb", - } - } -} - -impl FromStr for DebuginfoKind { - type Err = String; - - fn from_str(s: &str) -> Result { - Ok(match s { - "dwarf" => DebuginfoKind::Dwarf, - "dwarf-dsym" => DebuginfoKind::DwarfDsym, - "pdb" => DebuginfoKind::Pdb, - _ => { - return Err(format!( - "'{s}' is not a valid value for debuginfo-kind. Use 'dwarf', \ - 'dwarf-dsym' or 'pdb'." - )); - } - }) - } -} - -crate::json::serde_deserialize_from_str!(DebuginfoKind); - -impl ToJson for DebuginfoKind { - fn to_json(&self) -> Json { - self.as_str().to_json() - } -} - -impl fmt::Display for DebuginfoKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(self.as_str()) - } -} - -#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] -pub enum SplitDebuginfo { - /// Split debug-information is disabled, meaning that on supported platforms - /// you can find all debug information in the executable itself. This is - /// only supported for ELF effectively. - /// - /// * Windows - not supported - /// * macOS - don't run `dsymutil` - /// * ELF - `.debug_*` sections - #[default] - Off, - - /// Split debug-information can be found in a "packed" location separate - /// from the final artifact. This is supported on all platforms. - /// - /// * Windows - `*.pdb` - /// * macOS - `*.dSYM` (run `dsymutil`) - /// * ELF - `*.dwp` (run `thorin`) - Packed, - - /// Split debug-information can be found in individual object files on the - /// filesystem. The main executable may point to the object files. +crate::target_spec_enum! { + /// Which kind of debuginfo does the target use? /// - /// * Windows - not supported - /// * macOS - supported, scattered object files - /// * ELF - supported, scattered `*.dwo` or `*.o` files (see `SplitDwarfKind`) - Unpacked, -} - -impl SplitDebuginfo { - fn as_str(&self) -> &'static str { - match self { - SplitDebuginfo::Off => "off", - SplitDebuginfo::Packed => "packed", - SplitDebuginfo::Unpacked => "unpacked", - } - } -} - -impl FromStr for SplitDebuginfo { - type Err = String; - - fn from_str(s: &str) -> Result { - Ok(match s { - "off" => SplitDebuginfo::Off, - "unpacked" => SplitDebuginfo::Unpacked, - "packed" => SplitDebuginfo::Packed, - _ => { - return Err(format!( - "'{s}' is not a valid value for \ - split-debuginfo. Use 'off', 'unpacked', or 'packed'.", - )); - } - }) - } -} - -crate::json::serde_deserialize_from_str!(SplitDebuginfo); - -impl ToJson for SplitDebuginfo { - fn to_json(&self) -> Json { - self.as_str().to_json() - } -} - -impl fmt::Display for SplitDebuginfo { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(self.as_str()) - } + /// Useful in determining whether a target supports Split DWARF (a target with + /// `DebuginfoKind::Dwarf` and supporting `SplitDebuginfo::Unpacked` for example). + #[derive(Default)] + pub enum DebuginfoKind { + /// DWARF debuginfo (such as that used on `x86_64_unknown_linux_gnu`). + #[default] + Dwarf = "dwarf", + /// DWARF debuginfo in dSYM files (such as on Apple platforms). + DwarfDsym = "dwarf-dsym", + /// Program database files (such as on Windows). + Pdb = "pdb", + } + + parse_error_type = "debuginfo kind"; +} + +crate::target_spec_enum! { + #[derive(Default)] + pub enum SplitDebuginfo { + /// Split debug-information is disabled, meaning that on supported platforms + /// you can find all debug information in the executable itself. This is + /// only supported for ELF effectively. + /// + /// * Windows - not supported + /// * macOS - don't run `dsymutil` + /// * ELF - `.debug_*` sections + #[default] + Off = "off", + + /// Split debug-information can be found in a "packed" location separate + /// from the final artifact. This is supported on all platforms. + /// + /// * Windows - `*.pdb` + /// * macOS - `*.dSYM` (run `dsymutil`) + /// * ELF - `*.dwp` (run `thorin`) + Packed = "packed", + + /// Split debug-information can be found in individual object files on the + /// filesystem. The main executable may point to the object files. + /// + /// * Windows - not supported + /// * macOS - supported, scattered object files + /// * ELF - supported, scattered `*.dwo` or `*.o` files (see `SplitDwarfKind`) + Unpacked = "unpacked", + } + + parse_error_type = "split debuginfo"; } #[derive(Clone, Debug, PartialEq, Eq, serde_derive::Deserialize)] @@ -1690,17 +1237,20 @@ impl ToJson for SanitizerSet { } } -#[derive(Clone, Copy, PartialEq, Hash, Debug)] -pub enum FramePointer { - /// Forces the machine code generator to always preserve the frame pointers. - Always, - /// Forces the machine code generator to preserve the frame pointers except for the leaf - /// functions (i.e. those that don't call other functions). - NonLeaf, - /// Allows the machine code generator to omit the frame pointers. - /// - /// This option does not guarantee that the frame pointers will be omitted. - MayOmit, +crate::target_spec_enum! { + pub enum FramePointer { + /// Forces the machine code generator to always preserve the frame pointers. + Always = "always", + /// Forces the machine code generator to preserve the frame pointers except for the leaf + /// functions (i.e. those that don't call other functions). + NonLeaf = "non-leaf", + /// Allows the machine code generator to omit the frame pointers. + /// + /// This option does not guarantee that the frame pointers will be omitted. + MayOmit = "may-omit", + } + + parse_error_type = "frame pointer"; } impl FramePointer { @@ -1717,91 +1267,41 @@ impl FramePointer { } } -impl FromStr for FramePointer { - type Err = String; - fn from_str(s: &str) -> Result { - Ok(match s { - "always" => Self::Always, - "non-leaf" => Self::NonLeaf, - "may-omit" => Self::MayOmit, - _ => return Err(format!("'{s}' is not a valid value for frame-pointer")), - }) - } -} - -crate::json::serde_deserialize_from_str!(FramePointer); - -impl ToJson for FramePointer { - fn to_json(&self) -> Json { - match *self { - Self::Always => "always", - Self::NonLeaf => "non-leaf", - Self::MayOmit => "may-omit", - } - .to_json() - } -} - -/// Controls use of stack canaries. -#[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)] -pub enum StackProtector { - /// Disable stack canary generation. - None, +crate::target_spec_enum! { + /// Controls use of stack canaries. + pub enum StackProtector { + /// Disable stack canary generation. + None = "none", - /// On LLVM, mark all generated LLVM functions with the `ssp` attribute (see - /// llvm/docs/LangRef.rst). This triggers stack canary generation in - /// functions which contain an array of a byte-sized type with more than - /// eight elements. - Basic, + /// On LLVM, mark all generated LLVM functions with the `ssp` attribute (see + /// llvm/docs/LangRef.rst). This triggers stack canary generation in + /// functions which contain an array of a byte-sized type with more than + /// eight elements. + Basic = "basic", - /// On LLVM, mark all generated LLVM functions with the `sspstrong` - /// attribute (see llvm/docs/LangRef.rst). This triggers stack canary - /// generation in functions which either contain an array, or which take - /// the address of a local variable. - Strong, - - /// Generate stack canaries in all functions. - All, -} + /// On LLVM, mark all generated LLVM functions with the `sspstrong` + /// attribute (see llvm/docs/LangRef.rst). This triggers stack canary + /// generation in functions which either contain an array, or which take + /// the address of a local variable. + Strong = "strong", -impl StackProtector { - fn as_str(&self) -> &'static str { - match self { - StackProtector::None => "none", - StackProtector::Basic => "basic", - StackProtector::Strong => "strong", - StackProtector::All => "all", - } + /// Generate stack canaries in all functions. + All = "all", } -} - -impl FromStr for StackProtector { - type Err = (); - fn from_str(s: &str) -> Result { - Ok(match s { - "none" => StackProtector::None, - "basic" => StackProtector::Basic, - "strong" => StackProtector::Strong, - "all" => StackProtector::All, - _ => return Err(()), - }) - } + parse_error_type = "stack protector"; } -impl fmt::Display for StackProtector { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(self.as_str()) +crate::target_spec_enum! { + pub enum BinaryFormat { + Coff = "coff", + Elf = "elf", + MachO = "mach-o", + Wasm = "wasm", + Xcoff = "xcoff", } -} -#[derive(PartialEq, Clone, Debug)] -pub enum BinaryFormat { - Coff, - Elf, - MachO, - Wasm, - Xcoff, + parse_error_type = "binary format"; } impl BinaryFormat { @@ -1817,37 +1317,6 @@ impl BinaryFormat { } } -impl FromStr for BinaryFormat { - type Err = String; - fn from_str(s: &str) -> Result { - match s { - "coff" => Ok(Self::Coff), - "elf" => Ok(Self::Elf), - "mach-o" => Ok(Self::MachO), - "wasm" => Ok(Self::Wasm), - "xcoff" => Ok(Self::Xcoff), - _ => Err(format!( - "'{s}' is not a valid value for binary_format. \ - Use 'coff', 'elf', 'mach-o', 'wasm' or 'xcoff' " - )), - } - } -} - -crate::json::serde_deserialize_from_str!(BinaryFormat); - -impl ToJson for BinaryFormat { - fn to_json(&self) -> Json { - match self { - Self::Coff => "coff", - Self::Elf => "elf", - Self::MachO => "mach-o", - Self::Wasm => "wasm", - Self::Xcoff => "xcoff", - } - .to_json() - } -} impl ToJson for Align { fn to_json(&self) -> Json { From 987a49ba38e29f8c8b8dde4aab71dfad0f28f3fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= Date: Tue, 29 Jul 2025 17:47:03 +0200 Subject: [PATCH 08/30] bootstrap: extract `cc` query into a new function --- src/bootstrap/src/core/build_steps/dist.rs | 49 +++++++++++++--------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index c8a54ad250cb3..819fae468aec0 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -184,26 +184,7 @@ fn make_win_dist( return; } - //Ask gcc where it keeps its stuff - let mut cmd = command(builder.cc(target)); - cmd.arg("-print-search-dirs"); - let gcc_out = cmd.run_capture_stdout(builder).stdout(); - - let mut bin_path: Vec<_> = env::split_paths(&env::var_os("PATH").unwrap_or_default()).collect(); - let mut lib_path = Vec::new(); - - for line in gcc_out.lines() { - let idx = line.find(':').unwrap(); - let key = &line[..idx]; - let trim_chars: &[_] = &[' ', '=']; - let value = env::split_paths(line[(idx + 1)..].trim_start_matches(trim_chars)); - - if key == "programs" { - bin_path.extend(value); - } else if key == "libraries" { - lib_path.extend(value); - } - } + let (bin_path, lib_path) = get_cc_search_dirs(target, builder); let compiler = if target == "i686-pc-windows-gnu" { "i686-w64-mingw32-gcc.exe" @@ -320,6 +301,34 @@ fn make_win_dist( } } + +fn get_cc_search_dirs( + target: TargetSelection, + builder: &Builder<'_>, +) -> (Vec, Vec) { + //Ask gcc where it keeps its stuff + let mut cmd = command(builder.cc(target)); + cmd.arg("-print-search-dirs"); + let gcc_out = cmd.run_capture_stdout(builder).stdout(); + + let mut bin_path: Vec<_> = env::split_paths(&env::var_os("PATH").unwrap_or_default()).collect(); + let mut lib_path = Vec::new(); + + for line in gcc_out.lines() { + let idx = line.find(':').unwrap(); + let key = &line[..idx]; + let trim_chars: &[_] = &[' ', '=']; + let value = env::split_paths(line[(idx + 1)..].trim_start_matches(trim_chars)); + + if key == "programs" { + bin_path.extend(value); + } else if key == "libraries" { + lib_path.extend(value); + } + } + (bin_path, lib_path) +} + #[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)] pub struct Mingw { pub host: TargetSelection, From 9cfe5f61ab66fb8fba8907ff45dfb9d0dee617ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= Date: Tue, 29 Jul 2025 17:56:00 +0200 Subject: [PATCH 09/30] bootstrap: split runtime DLL part out of `make_win_dist` --- src/bootstrap/src/core/build_steps/dist.rs | 74 ++++++++++------------ 1 file changed, 35 insertions(+), 39 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index 819fae468aec0..88b668e1936e8 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -174,12 +174,7 @@ fn find_files(files: &[&str], path: &[PathBuf]) -> Vec { found } -fn make_win_dist( - rust_root: &Path, - plat_root: &Path, - target: TargetSelection, - builder: &Builder<'_>, -) { +fn make_win_dist(plat_root: &Path, target: TargetSelection, builder: &Builder<'_>) { if builder.config.dry_run() { return; } @@ -194,12 +189,6 @@ fn make_win_dist( "gcc.exe" }; let target_tools = [compiler, "ld.exe", "dlltool.exe", "libwinpthread-1.dll"]; - let mut rustc_dlls = vec!["libwinpthread-1.dll"]; - if target.starts_with("i686-") { - rustc_dlls.push("libgcc_s_dw2-1.dll"); - } else { - rustc_dlls.push("libgcc_s_seh-1.dll"); - } // Libraries necessary to link the windows-gnu toolchains. // System libraries will be preferred if they are available (see #67429). @@ -255,25 +244,8 @@ fn make_win_dist( //Find mingw artifacts we want to bundle let target_tools = find_files(&target_tools, &bin_path); - let rustc_dlls = find_files(&rustc_dlls, &bin_path); let target_libs = find_files(&target_libs, &lib_path); - // Copy runtime dlls next to rustc.exe - let rust_bin_dir = rust_root.join("bin/"); - fs::create_dir_all(&rust_bin_dir).expect("creating rust_bin_dir failed"); - for src in &rustc_dlls { - builder.copy_link_to_folder(src, &rust_bin_dir); - } - - if builder.config.lld_enabled { - // rust-lld.exe also needs runtime dlls - let rust_target_bin_dir = rust_root.join("lib/rustlib").join(target).join("bin"); - fs::create_dir_all(&rust_target_bin_dir).expect("creating rust_target_bin_dir failed"); - for src in &rustc_dlls { - builder.copy_link_to_folder(src, &rust_target_bin_dir); - } - } - //Copy platform tools to platform-specific bin directory let plat_target_bin_self_contained_dir = plat_root.join("lib/rustlib").join(target).join("bin/self-contained"); @@ -301,6 +273,37 @@ fn make_win_dist( } } +fn runtime_dll_dist(rust_root: &Path, target: TargetSelection, builder: &Builder<'_>) { + if builder.config.dry_run() { + return; + } + + let (bin_path, _) = get_cc_search_dirs(target, builder); + + let mut rustc_dlls = vec!["libwinpthread-1.dll"]; + if target.starts_with("i686-") { + rustc_dlls.push("libgcc_s_dw2-1.dll"); + } else { + rustc_dlls.push("libgcc_s_seh-1.dll"); + } + let rustc_dlls = find_files(&rustc_dlls, &bin_path); + + // Copy runtime dlls next to rustc.exe + let rust_bin_dir = rust_root.join("bin/"); + fs::create_dir_all(&rust_bin_dir).expect("creating rust_bin_dir failed"); + for src in &rustc_dlls { + builder.copy_link_to_folder(src, &rust_bin_dir); + } + + if builder.config.lld_enabled { + // rust-lld.exe also needs runtime dlls + let rust_target_bin_dir = rust_root.join("lib/rustlib").join(target).join("bin"); + fs::create_dir_all(&rust_target_bin_dir).expect("creating rust_target_bin_dir failed"); + for src in &rustc_dlls { + builder.copy_link_to_folder(src, &rust_target_bin_dir); + } + } +} fn get_cc_search_dirs( target: TargetSelection, @@ -359,11 +362,7 @@ impl Step for Mingw { let mut tarball = Tarball::new(builder, "rust-mingw", &host.triple); tarball.set_product_name("Rust MinGW"); - // The first argument is a "temporary directory" which is just - // thrown away (this contains the runtime DLLs included in the rustc package - // above) and the second argument is where to place all the MinGW components - // (which is what we want). - make_win_dist(&tmpdir(builder), tarball.image_dir(), host, builder); + make_win_dist(tarball.image_dir(), host, builder); Some(tarball.generate()) } @@ -403,17 +402,14 @@ impl Step for Rustc { prepare_image(builder, compiler, tarball.image_dir()); // On MinGW we've got a few runtime DLL dependencies that we need to - // include. The first argument to this script is where to put these DLLs - // (the image we're creating), and the second argument is a junk directory - // to ignore all other MinGW stuff the script creates. - // + // include. // On 32-bit MinGW we're always including a DLL which needs some extra // licenses to distribute. On 64-bit MinGW we don't actually distribute // anything requiring us to distribute a license, but it's likely the // install will *also* include the rust-mingw package, which also needs // licenses, so to be safe we just include it here in all MinGW packages. if host.ends_with("pc-windows-gnu") && builder.config.dist_include_mingw_linker { - make_win_dist(tarball.image_dir(), &tmpdir(builder), host, builder); + runtime_dll_dist(tarball.image_dir(), host, builder); tarball.add_dir(builder.src.join("src/etc/third-party"), "share/doc"); } From ec40ee4c4eb6b105e67b7fb6a7a488d89a64fafb Mon Sep 17 00:00:00 2001 From: tiif Date: Wed, 30 Jul 2025 09:30:10 +0000 Subject: [PATCH 10/30] Add documentation for unstable_feature_bound --- src/doc/rustc-dev-guide/src/stability.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/doc/rustc-dev-guide/src/stability.md b/src/doc/rustc-dev-guide/src/stability.md index 230925252bac3..7a5efdb8ad72f 100644 --- a/src/doc/rustc-dev-guide/src/stability.md +++ b/src/doc/rustc-dev-guide/src/stability.md @@ -183,4 +183,7 @@ the `deprecated_in_future` lint is triggered which is default `allow`, but most of the standard library raises it to a warning with `#![warn(deprecated_in_future)]`. +## unstable_feature_bound +The `#[unstable_feature_bound(foo)]` attribute can be used together with `#[unstable]` attribute to mark an `impl` of stable type and stable trait as unstable. In std/core , an item annotated with `#[unstable_feature_bound(foo)]` can only be used by another item that is also annotated with `#[unstable_feature_bound(foo)]`. Outside of std/core, using an item with `#[unstable_feature_bound(foo)]` requires the feature to be enabled with `#![feature(foo)]` attribute on the crate. Currently, only `impl`s and free functions can be annotated with `#[unstable_feature_bound]`. + [blog]: https://www.ralfj.de/blog/2018/07/19/const.html From 712c28e8324fc507c986f982755b8bfde919b5dc Mon Sep 17 00:00:00 2001 From: tiif Date: Wed, 30 Jul 2025 11:54:32 +0200 Subject: [PATCH 11/30] Remove space Co-authored-by: Tshepang Mbambo --- src/doc/rustc-dev-guide/src/stability.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/src/stability.md b/src/doc/rustc-dev-guide/src/stability.md index 7a5efdb8ad72f..e8589b7f4310c 100644 --- a/src/doc/rustc-dev-guide/src/stability.md +++ b/src/doc/rustc-dev-guide/src/stability.md @@ -184,6 +184,6 @@ of the standard library raises it to a warning with `#![warn(deprecated_in_future)]`. ## unstable_feature_bound -The `#[unstable_feature_bound(foo)]` attribute can be used together with `#[unstable]` attribute to mark an `impl` of stable type and stable trait as unstable. In std/core , an item annotated with `#[unstable_feature_bound(foo)]` can only be used by another item that is also annotated with `#[unstable_feature_bound(foo)]`. Outside of std/core, using an item with `#[unstable_feature_bound(foo)]` requires the feature to be enabled with `#![feature(foo)]` attribute on the crate. Currently, only `impl`s and free functions can be annotated with `#[unstable_feature_bound]`. +The `#[unstable_feature_bound(foo)]` attribute can be used together with `#[unstable]` attribute to mark an `impl` of stable type and stable trait as unstable. In std/core, an item annotated with `#[unstable_feature_bound(foo)]` can only be used by another item that is also annotated with `#[unstable_feature_bound(foo)]`. Outside of std/core, using an item with `#[unstable_feature_bound(foo)]` requires the feature to be enabled with `#![feature(foo)]` attribute on the crate. Currently, only `impl`s and free functions can be annotated with `#[unstable_feature_bound]`. [blog]: https://www.ralfj.de/blog/2018/07/19/const.html From b3f369d9252e4c0d5dd9bd28b950c7730fcd2c3d Mon Sep 17 00:00:00 2001 From: Haowei Wu Date: Thu, 17 Jul 2025 16:12:28 -0700 Subject: [PATCH 12/30] Address some rustc inconsistency issues We noticed when building rustc multiple time in a roll, some files will not be consistent across the build despite the fact that they are built from same source under the same environment. This patch addresses the inconsistency issue we found on libunwind.a by sorting the order of the files passed to the linker. --- src/bootstrap/src/core/build_steps/compile.rs | 10 +++++++--- src/bootstrap/src/core/build_steps/llvm.rs | 8 ++++++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 09bb2e35bdaa2..11a5554691db8 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -2376,15 +2376,19 @@ pub fn run_cargo( let mut deps = Vec::new(); let mut toplevel = Vec::new(); let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| { - let (filenames, crate_types) = match msg { + let (filenames_vec, crate_types) = match msg { CargoMessage::CompilerArtifact { filenames, target: CargoTarget { crate_types }, .. - } => (filenames, crate_types), + } => { + let mut f: Vec = filenames.into_iter().map(|s| s.into_owned()).collect(); + f.sort(); // Sort the filenames + (f, crate_types) + } _ => return, }; - for filename in filenames { + for filename in filenames_vec { // Skip files like executables let mut keep = false; if filename.ends_with(".lib") diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index b2056f5cf3786..721ba6ca459e4 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -1528,8 +1528,12 @@ impl Step for Libunwind { // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845 let mut count = 0; - for entry in fs::read_dir(&out_dir).unwrap() { - let file = entry.unwrap().path().canonicalize().unwrap(); + let mut files = fs::read_dir(&out_dir) + .unwrap() + .map(|entry| entry.unwrap().path().canonicalize().unwrap()) + .collect::>(); + files.sort(); + for file in files { if file.is_file() && file.extension() == Some(OsStr::new("o")) { // Object file name without the hash prefix is "Unwind-EHABI", "Unwind-seh" or "libunwind". let base_name = unhashed_basename(&file); From 1dfa421361817ccf207efe9ab94dc06f6234536d Mon Sep 17 00:00:00 2001 From: Noratrieb <48135649+Noratrieb@users.noreply.github.com> Date: Sat, 26 Jul 2025 12:39:31 +0200 Subject: [PATCH 13/30] Add --print target-spec-json-schema This schema is helpful for people writing custom target spec JSON. It can provide autocomplete in the editor, and also serves as documentation when there are documentation comments on the structs, as `schemars` will put them in the schema. --- Cargo.lock | 63 +++++++++++++++++ .../rustc_codegen_ssa/src/back/command.rs | 2 +- compiler/rustc_driver_impl/src/lib.rs | 4 ++ compiler/rustc_session/src/config.rs | 5 +- compiler/rustc_target/Cargo.toml | 1 + compiler/rustc_target/src/lib.rs | 2 + compiler/rustc_target/src/spec/json.rs | 38 ++++++++-- compiler/rustc_target/src/spec/mod.rs | 70 ++++++++++++++++++- src/bootstrap/src/core/build_steps/dist.rs | 36 ++++++++++ src/bootstrap/src/utils/proc_macro_deps.rs | 1 + src/doc/rustc/src/targets/custom.md | 15 ++++ src/tools/tidy/src/deps.rs | 6 ++ .../help-diff.diff | 2 +- .../unstable-invalid-print-request-help.err | 2 +- tests/run-make/rustc-help/help-v.stdout | 2 +- tests/run-make/rustc-help/help.stdout | 2 +- .../print-without-arg.stderr | 2 +- tests/ui/invalid-compile-flags/print.stderr | 2 +- .../ui/print-request/print-lints-help.stderr | 2 +- 19 files changed, 241 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0d37e8b2f84c0..22e6a38c5ebbc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1133,6 +1133,12 @@ version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8975ffdaa0ef3661bfe02dbdcc06c9f829dfafe6a3c474de366a8d5e44276921" +[[package]] +name = "dyn-clone" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c7a8fb8a9fbf66c1f703fe16184d10ca0ee9d23be5b4436400408ba54a95005" + [[package]] name = "either" version = "1.15.0" @@ -3077,6 +3083,26 @@ dependencies = [ "thiserror 2.0.12", ] +[[package]] +name = "ref-cast" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0ae411dbe946a674d89546582cea4ba2bb8defac896622d6496f14c23ba5cf" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1165225c21bff1f3bbce98f5a1f889949bc902d3575308cc7b0de30b4f6d27c7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "regex" version = "1.11.1" @@ -4563,6 +4589,7 @@ dependencies = [ "rustc_macros", "rustc_serialize", "rustc_span", + "schemars", "serde", "serde_derive", "serde_json", @@ -4878,6 +4905,31 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "schemars" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82d20c4491bc164fa2f6c5d44565947a52ad80b9505d8e36f8d54c27c739fcd0" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33d020396d1d138dc19f1165df7545479dcd58d93810dc5d646a16e55abefa80" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.104", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -4946,6 +4998,17 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "serde_json" version = "1.0.141" diff --git a/compiler/rustc_codegen_ssa/src/back/command.rs b/compiler/rustc_codegen_ssa/src/back/command.rs index 05351bd6ca379..7420f18aacb35 100644 --- a/compiler/rustc_codegen_ssa/src/back/command.rs +++ b/compiler/rustc_codegen_ssa/src/back/command.rs @@ -109,7 +109,7 @@ impl Command { } Program::Lld(ref p, flavor) => { let mut c = process::Command::new(p); - c.arg("-flavor").arg(flavor.as_str()); + c.arg("-flavor").arg(flavor.desc()); c } }; diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index f3ed604210565..4e21926af813c 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -667,6 +667,10 @@ fn print_crate_info( TargetSpecJson => { println_info!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap()); } + TargetSpecJsonSchema => { + let schema = rustc_target::spec::json_schema(); + println_info!("{}", serde_json::to_string_pretty(&schema).unwrap()); + } AllTargetSpecsJson => { let mut targets = BTreeMap::new(); for name in rustc_target::spec::TARGETS { diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 8f624e0fb2fcb..6bd1173318ad0 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -69,6 +69,7 @@ pub const PRINT_KINDS: &[(&str, PrintKind)] = &[ ("target-libdir", PrintKind::TargetLibdir), ("target-list", PrintKind::TargetList), ("target-spec-json", PrintKind::TargetSpecJson), + ("target-spec-json-schema", PrintKind::TargetSpecJsonSchema), ("tls-models", PrintKind::TlsModels), // tidy-alphabetical-end ]; @@ -1052,6 +1053,7 @@ pub enum PrintKind { TargetLibdir, TargetList, TargetSpecJson, + TargetSpecJsonSchema, TlsModels, // tidy-alphabetical-end } @@ -2314,7 +2316,8 @@ fn is_print_request_stable(print_kind: PrintKind) -> bool { | PrintKind::CheckCfg | PrintKind::CrateRootLintLevels | PrintKind::SupportedCrateTypes - | PrintKind::TargetSpecJson => false, + | PrintKind::TargetSpecJson + | PrintKind::TargetSpecJsonSchema => false, _ => true, } } diff --git a/compiler/rustc_target/Cargo.toml b/compiler/rustc_target/Cargo.toml index 56932c24922e5..25e93e42685eb 100644 --- a/compiler/rustc_target/Cargo.toml +++ b/compiler/rustc_target/Cargo.toml @@ -12,6 +12,7 @@ rustc_fs_util = { path = "../rustc_fs_util" } rustc_macros = { path = "../rustc_macros" } rustc_serialize = { path = "../rustc_serialize" } rustc_span = { path = "../rustc_span" } +schemars = "1.0.4" serde = "1.0.219" serde_derive = "1.0.219" serde_json = "1.0.59" diff --git a/compiler/rustc_target/src/lib.rs b/compiler/rustc_target/src/lib.rs index c6a23745b04e7..b3fe1fffccebc 100644 --- a/compiler/rustc_target/src/lib.rs +++ b/compiler/rustc_target/src/lib.rs @@ -86,9 +86,11 @@ macro_rules! target_spec_enum { ) => { $( #[$attr] )* #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] + #[derive(schemars::JsonSchema)] pub enum $name { $( $( #[$variant_attr] )* + #[serde(rename = $string)] // for JSON schema generation only $variant, )* } diff --git a/compiler/rustc_target/src/spec/json.rs b/compiler/rustc_target/src/spec/json.rs index d27c1929aef74..cb56a03a43450 100644 --- a/compiler/rustc_target/src/spec/json.rs +++ b/compiler/rustc_target/src/spec/json.rs @@ -413,12 +413,12 @@ impl ToJson for Target { } } -#[derive(serde_derive::Deserialize)] +#[derive(serde_derive::Deserialize, schemars::JsonSchema)] struct LinkSelfContainedComponentsWrapper { components: Vec, } -#[derive(serde_derive::Deserialize)] +#[derive(serde_derive::Deserialize, schemars::JsonSchema)] #[serde(untagged)] enum TargetFamiliesJson { Array(StaticCow<[StaticCow]>), @@ -434,6 +434,18 @@ impl FromStr for EndianWrapper { } } crate::json::serde_deserialize_from_str!(EndianWrapper); +impl schemars::JsonSchema for EndianWrapper { + fn schema_name() -> std::borrow::Cow<'static, str> { + "Endian".into() + } + fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema! ({ + "type": "string", + "enum": ["big", "little"] + }) + .into() + } +} /// `ExternAbi` is in `rustc_abi`, which doesn't have access to the macro and serde. struct ExternAbiWrapper(rustc_abi::ExternAbi); @@ -446,8 +458,22 @@ impl FromStr for ExternAbiWrapper { } } crate::json::serde_deserialize_from_str!(ExternAbiWrapper); +impl schemars::JsonSchema for ExternAbiWrapper { + fn schema_name() -> std::borrow::Cow<'static, str> { + "ExternAbi".into() + } + fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + let all = + rustc_abi::ExternAbi::ALL_VARIANTS.iter().map(|abi| abi.as_str()).collect::>(); + schemars::json_schema! ({ + "type": "string", + "enum": all, + }) + .into() + } +} -#[derive(serde_derive::Deserialize)] +#[derive(serde_derive::Deserialize, schemars::JsonSchema)] struct TargetSpecJsonMetadata { description: Option>, tier: Option, @@ -455,7 +481,7 @@ struct TargetSpecJsonMetadata { std: Option, } -#[derive(serde_derive::Deserialize)] +#[derive(serde_derive::Deserialize, schemars::JsonSchema)] #[serde(rename_all = "kebab-case")] // Ensure that all unexpected fields get turned into errors. // This helps users stay up to date when the schema changes instead of silently @@ -598,3 +624,7 @@ struct TargetSpecJson { supports_xray: Option, entry_abi: Option, } + +pub fn json_schema() -> schemars::Schema { + schemars::schema_for!(TargetSpecJson) +} diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 7cb0e0af46664..f310f240588b1 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -69,6 +69,7 @@ mod json; pub use abi_map::{AbiMap, AbiMapping}; pub use base::apple; pub use base::avr::ef_avr_arch; +pub use json::json_schema; /// Linker is called through a C/C++ compiler. #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] @@ -522,6 +523,20 @@ linker_flavor_cli_impls! { } crate::json::serde_deserialize_from_str!(LinkerFlavorCli); +impl schemars::JsonSchema for LinkerFlavorCli { + fn schema_name() -> std::borrow::Cow<'static, str> { + "LinkerFlavor".into() + } + fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + let all: Vec<&'static str> = + Self::all().iter().map(|flavor| flavor.desc()).collect::>(); + schemars::json_schema! ({ + "type": "string", + "enum": all + }) + .into() + } +} impl ToJson for LinkerFlavorCli { fn to_json(&self) -> Json { @@ -575,6 +590,18 @@ impl FromStr for LinkSelfContainedDefault { } crate::json::serde_deserialize_from_str!(LinkSelfContainedDefault); +impl schemars::JsonSchema for LinkSelfContainedDefault { + fn schema_name() -> std::borrow::Cow<'static, str> { + "LinkSelfContainedDefault".into() + } + fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema! ({ + "type": "string", + "enum": ["false", "true", "wasm", "musl", "mingw"] + }) + .into() + } +} impl ToJson for LinkSelfContainedDefault { fn to_json(&self) -> Json { @@ -707,6 +734,20 @@ impl FromStr for LinkSelfContainedComponents { } crate::json::serde_deserialize_from_str!(LinkSelfContainedComponents); +impl schemars::JsonSchema for LinkSelfContainedComponents { + fn schema_name() -> std::borrow::Cow<'static, str> { + "LinkSelfContainedComponents".into() + } + fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + let all = + Self::all_components().iter().map(|component| component.as_str()).collect::>(); + schemars::json_schema! ({ + "type": "string", + "enum": all, + }) + .into() + } +} impl ToJson for LinkSelfContainedComponents { fn to_json(&self) -> Json { @@ -839,7 +880,6 @@ crate::target_spec_enum! { parse_error_type = "symbol visibility"; } - #[derive(Clone, Debug, PartialEq, Hash)] pub enum SmallDataThresholdSupport { None, @@ -867,6 +907,18 @@ impl FromStr for SmallDataThresholdSupport { } crate::json::serde_deserialize_from_str!(SmallDataThresholdSupport); +impl schemars::JsonSchema for SmallDataThresholdSupport { + fn schema_name() -> std::borrow::Cow<'static, str> { + "SmallDataThresholdSupport".into() + } + fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema! ({ + "type": "string", + "pattern": r#"^none|default-for-arch|llvm-module-flag=.+|llvm-arg=.+$"#, + }) + .into() + } +} impl ToJson for SmallDataThresholdSupport { fn to_json(&self) -> Value { @@ -1065,7 +1117,7 @@ crate::target_spec_enum! { parse_error_type = "split debuginfo"; } -#[derive(Clone, Debug, PartialEq, Eq, serde_derive::Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, serde_derive::Deserialize, schemars::JsonSchema)] #[serde(tag = "kind")] #[serde(rename_all = "kebab-case")] pub enum StackProbeType { @@ -1226,6 +1278,19 @@ impl FromStr for SanitizerSet { } crate::json::serde_deserialize_from_str!(SanitizerSet); +impl schemars::JsonSchema for SanitizerSet { + fn schema_name() -> std::borrow::Cow<'static, str> { + "SanitizerSet".into() + } + fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + let all = Self::all().iter().map(|sanitizer| sanitizer.as_str()).collect::>(); + schemars::json_schema! ({ + "type": "string", + "enum": all, + }) + .into() + } +} impl ToJson for SanitizerSet { fn to_json(&self) -> Json { @@ -1317,7 +1382,6 @@ impl BinaryFormat { } } - impl ToJson for Align { fn to_json(&self) -> Json { self.bits().to_json() diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index c8a54ad250cb3..4b1d3ceb84bc8 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -526,6 +526,8 @@ impl Step for Rustc { // Debugger scripts builder.ensure(DebuggerScripts { sysroot: image.to_owned(), host }); + builder.ensure(TargetSpecJsonSchema { sysroot: image.to_owned(), compiler }); + // HTML copyright files let file_list = builder.ensure(super::run::GenerateCopyright); for file in file_list { @@ -554,6 +556,40 @@ impl Step for Rustc { } } +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +pub struct TargetSpecJsonSchema { + sysroot: PathBuf, + compiler: Compiler, +} + +impl Step for TargetSpecJsonSchema { + type Output = (); + + fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { + run.never() + } + + /// Copies the output of --print=target-spec-json-schema into etc. + fn run(self, builder: &Builder<'_>) { + let mut rustc = command(builder.rustc(self.compiler)).fail_fast(); + rustc + .env("RUSTC_BOOTSTRAP", "1") + .args(["--print=target-spec-json-schema", "-Zunstable-options"]); + let schema = rustc.run_capture(builder).stdout(); + + let schema_dir = tmpdir(builder); + t!(fs::create_dir_all(&schema_dir)); + let schema_file = schema_dir.join("target-spec-json-schema.json"); + t!(std::fs::write(&schema_file, schema)); + + let sysroot = self.sysroot; + let dst = sysroot.join("etc"); + t!(fs::create_dir_all(&dst)); + + builder.install(&schema_file, &dst, FileType::Regular); + } +} + #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct DebuggerScripts { pub sysroot: PathBuf, diff --git a/src/bootstrap/src/utils/proc_macro_deps.rs b/src/bootstrap/src/utils/proc_macro_deps.rs index 21c7fc89d7dfd..07f65ec8e3930 100644 --- a/src/bootstrap/src/utils/proc_macro_deps.rs +++ b/src/bootstrap/src/utils/proc_macro_deps.rs @@ -38,6 +38,7 @@ pub static CRATES: &[&str] = &[ "rustc-hash", "self_cell", "serde", + "serde_derive_internals", "sha2", "smallvec", "stable_deref_trait", diff --git a/src/doc/rustc/src/targets/custom.md b/src/doc/rustc/src/targets/custom.md index 6c1494186a4ed..e1750e27f0b75 100644 --- a/src/doc/rustc/src/targets/custom.md +++ b/src/doc/rustc/src/targets/custom.md @@ -16,6 +16,21 @@ rustc +nightly -Z unstable-options --target=wasm32-unknown-unknown --print targe To use a custom target, see the (unstable) [`build-std` feature](../../cargo/reference/unstable.html#build-std) of `cargo`. +
+ +The target JSON properties are not stable and subject to change. +Always pin your compiler version when using custom targets! + +
+ +## JSON Schema + +`rustc` provides a JSON schema for the custom target JSON specification. +Because the schema is subject to change, you should always use the schema from the version of rustc which you are passing the target to. + +It can be found in `etc/target-spec-json-schema.json` in the sysroot (`rustc --print sysroot`) or printed with `rustc +nightly -Zunstable-options --print target-spec-json-schema`. +The existence and name of this schema is, just like the properties of the JSON specification, not stable and subject to change. + ## Custom Target Lookup Path When `rustc` is given an option `--target=TARGET` (where `TARGET` is any string), it uses the following logic: diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 21cbb143c5111..089a2c13ec380 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -281,6 +281,7 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "digest", "displaydoc", "dissimilar", + "dyn-clone", "either", "elsa", "ena", @@ -361,6 +362,8 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "rand_xorshift", // dependency for doc-tests in rustc_thread_pool "rand_xoshiro", "redox_syscall", + "ref-cast", + "ref-cast-impl", "regex", "regex-automata", "regex-syntax", @@ -372,12 +375,15 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "rustix", "ruzstd", // via object in thorin-dwp "ryu", + "schemars", + "schemars_derive", "scoped-tls", "scopeguard", "self_cell", "semver", "serde", "serde_derive", + "serde_derive_internals", "serde_json", "serde_path_to_error", "sha1", diff --git a/tests/run-make/print-request-help-stable-unstable/help-diff.diff b/tests/run-make/print-request-help-stable-unstable/help-diff.diff index 07eafca327108..044302a19a016 100644 --- a/tests/run-make/print-request-help-stable-unstable/help-diff.diff +++ b/tests/run-make/print-request-help-stable-unstable/help-diff.diff @@ -2,6 +2,6 @@ error: unknown print request: `xxx` | - = help: valid print requests are: `calling-conventions`, `cfg`, `code-models`, `crate-name`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `tls-models` -+ = help: valid print requests are: `all-target-specs-json`, `calling-conventions`, `cfg`, `check-cfg`, `code-models`, `crate-name`, `crate-root-lint-levels`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `supported-crate-types`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `target-spec-json`, `tls-models` ++ = help: valid print requests are: `all-target-specs-json`, `calling-conventions`, `cfg`, `check-cfg`, `code-models`, `crate-name`, `crate-root-lint-levels`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `supported-crate-types`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `target-spec-json`, `target-spec-json-schema`, `tls-models` = help: for more information, see the rustc book: https://doc.rust-lang.org/rustc/command-line-arguments.html#--print-print-compiler-information diff --git a/tests/run-make/print-request-help-stable-unstable/unstable-invalid-print-request-help.err b/tests/run-make/print-request-help-stable-unstable/unstable-invalid-print-request-help.err index 50ef340e3dd02..cc6c3c909b366 100644 --- a/tests/run-make/print-request-help-stable-unstable/unstable-invalid-print-request-help.err +++ b/tests/run-make/print-request-help-stable-unstable/unstable-invalid-print-request-help.err @@ -1,5 +1,5 @@ error: unknown print request: `xxx` | - = help: valid print requests are: `all-target-specs-json`, `calling-conventions`, `cfg`, `check-cfg`, `code-models`, `crate-name`, `crate-root-lint-levels`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `supported-crate-types`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `target-spec-json`, `tls-models` + = help: valid print requests are: `all-target-specs-json`, `calling-conventions`, `cfg`, `check-cfg`, `code-models`, `crate-name`, `crate-root-lint-levels`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `supported-crate-types`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `target-spec-json`, `target-spec-json-schema`, `tls-models` = help: for more information, see the rustc book: https://doc.rust-lang.org/rustc/command-line-arguments.html#--print-print-compiler-information diff --git a/tests/run-make/rustc-help/help-v.stdout b/tests/run-make/rustc-help/help-v.stdout index 3fc297fb08e7d..cd161c51ee3b9 100644 --- a/tests/run-make/rustc-help/help-v.stdout +++ b/tests/run-make/rustc-help/help-v.stdout @@ -43,7 +43,7 @@ Options: --print [=] Compiler information to print on stdout (or to a file) INFO may be one of - . + . -g Equivalent to -C debuginfo=2 -O Equivalent to -C opt-level=3 -o Write output to FILENAME diff --git a/tests/run-make/rustc-help/help.stdout b/tests/run-make/rustc-help/help.stdout index caffe28f49899..74ec083bdee7a 100644 --- a/tests/run-make/rustc-help/help.stdout +++ b/tests/run-make/rustc-help/help.stdout @@ -43,7 +43,7 @@ Options: --print [=] Compiler information to print on stdout (or to a file) INFO may be one of - . + . -g Equivalent to -C debuginfo=2 -O Equivalent to -C opt-level=3 -o Write output to FILENAME diff --git a/tests/ui/invalid-compile-flags/print-without-arg.stderr b/tests/ui/invalid-compile-flags/print-without-arg.stderr index 3048a59d0d00c..4163d4e060220 100644 --- a/tests/ui/invalid-compile-flags/print-without-arg.stderr +++ b/tests/ui/invalid-compile-flags/print-without-arg.stderr @@ -3,5 +3,5 @@ error: Argument to option 'print' missing --print [=] Compiler information to print on stdout (or to a file) INFO may be one of - . + . diff --git a/tests/ui/invalid-compile-flags/print.stderr b/tests/ui/invalid-compile-flags/print.stderr index e3374eb1e6e7e..e8adbfd87d761 100644 --- a/tests/ui/invalid-compile-flags/print.stderr +++ b/tests/ui/invalid-compile-flags/print.stderr @@ -1,5 +1,5 @@ error: unknown print request: `yyyy` | - = help: valid print requests are: `all-target-specs-json`, `calling-conventions`, `cfg`, `check-cfg`, `code-models`, `crate-name`, `crate-root-lint-levels`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `supported-crate-types`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `target-spec-json`, `tls-models` + = help: valid print requests are: `all-target-specs-json`, `calling-conventions`, `cfg`, `check-cfg`, `code-models`, `crate-name`, `crate-root-lint-levels`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `supported-crate-types`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `target-spec-json`, `target-spec-json-schema`, `tls-models` = help: for more information, see the rustc book: https://doc.rust-lang.org/rustc/command-line-arguments.html#--print-print-compiler-information diff --git a/tests/ui/print-request/print-lints-help.stderr b/tests/ui/print-request/print-lints-help.stderr index bc48b2fa73cc7..297a3aa79e1f3 100644 --- a/tests/ui/print-request/print-lints-help.stderr +++ b/tests/ui/print-request/print-lints-help.stderr @@ -1,6 +1,6 @@ error: unknown print request: `lints` | - = help: valid print requests are: `all-target-specs-json`, `calling-conventions`, `cfg`, `check-cfg`, `code-models`, `crate-name`, `crate-root-lint-levels`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `supported-crate-types`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `target-spec-json`, `tls-models` + = help: valid print requests are: `all-target-specs-json`, `calling-conventions`, `cfg`, `check-cfg`, `code-models`, `crate-name`, `crate-root-lint-levels`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `supported-crate-types`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `target-spec-json`, `target-spec-json-schema`, `tls-models` = help: use `-Whelp` to print a list of lints = help: for more information, see the rustc book: https://doc.rust-lang.org/rustc/command-line-arguments.html#--print-print-compiler-information From 1eb9b134f52ef9a3ffa28075bc1a1515bcfbaa8c Mon Sep 17 00:00:00 2001 From: Christopher Hotchkiss Date: Sat, 2 Aug 2025 10:46:29 -0700 Subject: [PATCH 14/30] Change visibility of Args new function Currently the Args new function is scope constrained to pub(super) but this stops me from being able to construct Args structs in unit tests. --- library/std/src/sys/args/common.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/args/common.rs b/library/std/src/sys/args/common.rs index e787105a05a73..33f3794ee6339 100644 --- a/library/std/src/sys/args/common.rs +++ b/library/std/src/sys/args/common.rs @@ -12,7 +12,7 @@ impl !Sync for Args {} impl Args { #[inline] - pub(super) fn new(args: Vec) -> Self { + pub fn new(args: Vec) -> Self { Args { iter: args.into_iter() } } } From 74e85a218b418db7ff29f0743efb12c130dfd3ca Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Sun, 3 Aug 2025 22:56:02 +0500 Subject: [PATCH 15/30] removed gate --- library/std/src/panic.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/library/std/src/panic.rs b/library/std/src/panic.rs index 234fb284a5904..3715160198230 100644 --- a/library/std/src/panic.rs +++ b/library/std/src/panic.rs @@ -108,8 +108,6 @@ impl<'a> PanicHookInfo<'a> { /// # Example /// /// ```should_panic - /// #![feature(panic_payload_as_str)] - /// /// std::panic::set_hook(Box::new(|panic_info| { /// if let Some(s) = panic_info.payload_as_str() { /// println!("panic occurred: {s:?}"); @@ -122,7 +120,7 @@ impl<'a> PanicHookInfo<'a> { /// ``` #[must_use] #[inline] - #[unstable(feature = "panic_payload_as_str", issue = "125175")] + #[stable(feature = "panic_payload_as_str", since = "CURRENT_RUSTC_VERSION")] pub fn payload_as_str(&self) -> Option<&str> { if let Some(s) = self.payload.downcast_ref::<&str>() { Some(s) From 23e6be2d900cb140c09ab36e3c166842a230d696 Mon Sep 17 00:00:00 2001 From: Anne Stijns Date: Sat, 12 Jul 2025 23:50:47 +0200 Subject: [PATCH 16/30] Port #[macro_export] to the new attribute parsing infrastructure --- compiler/rustc_attr_parsing/messages.ftl | 5 + .../src/attributes/macro_attrs.rs | 61 +++++++++++- compiler/rustc_attr_parsing/src/context.rs | 3 +- compiler/rustc_attr_parsing/src/lints.rs | 12 +++ compiler/rustc_expand/src/base.rs | 6 +- .../rustc_hir/src/attrs/data_structures.rs | 3 + .../rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_hir/src/lints.rs | 21 ++++- compiler/rustc_lint/src/non_local_def.rs | 10 +- compiler/rustc_lint_defs/src/builtin.rs | 7 +- compiler/rustc_passes/messages.ftl | 4 - compiler/rustc_passes/src/check_attr.rs | 40 +++----- compiler/rustc_passes/src/errors.rs | 6 -- src/librustdoc/html/render/search_index.rs | 23 +++-- src/librustdoc/json/conversions.rs | 9 +- src/librustdoc/passes/strip_hidden.rs | 5 +- src/librustdoc/visit_ast.rs | 10 +- .../src/macro_metavars_in_unsafe.rs | 7 +- ...invalid_macro_export_argument.allow.stderr | 40 ++++++++ .../invalid_macro_export_argument.deny.stderr | 93 +++++++++++++++++-- .../invalid_macro_export_argument.rs | 12 ++- tests/ui/attributes/malformed-attrs.rs | 2 +- tests/ui/attributes/malformed-attrs.stderr | 21 ++--- ...43106-gating-of-builtin-attrs-error.stderr | 30 +++--- .../lint/unused/unused-attr-duplicate.stderr | 24 ++--- 25 files changed, 328 insertions(+), 127 deletions(-) create mode 100644 tests/ui/attributes/invalid_macro_export_argument.allow.stderr diff --git a/compiler/rustc_attr_parsing/messages.ftl b/compiler/rustc_attr_parsing/messages.ftl index 35ff48cb5f24b..aa8046add7145 100644 --- a/compiler/rustc_attr_parsing/messages.ftl +++ b/compiler/rustc_attr_parsing/messages.ftl @@ -32,6 +32,11 @@ attr_parsing_ill_formed_attribute_input = {$num_suggestions -> *[other] valid forms for the attribute are {$suggestions} } +attr_parsing_invalid_macro_export_arguments = {$num_suggestions -> + [1] attribute must be of the form {$suggestions} + *[other] valid forms for the attribute are {$suggestions} + } + attr_parsing_incorrect_repr_format_align_one_arg = incorrect `repr(align)` attribute format: `align` takes exactly one argument in parentheses diff --git a/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs index 886f7a889d303..122d80cca046e 100644 --- a/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs @@ -1,10 +1,14 @@ use rustc_errors::DiagArgValue; use rustc_feature::{AttributeTemplate, template}; use rustc_hir::attrs::{AttributeKind, MacroUseArgs}; +use rustc_hir::lints::AttributeLintKind; use rustc_span::{Span, Symbol, sym}; use thin_vec::ThinVec; -use crate::attributes::{AcceptMapping, AttributeParser, NoArgsAttributeParser, OnDuplicate}; +use crate::attributes::{ + AcceptMapping, AttributeOrder, AttributeParser, NoArgsAttributeParser, OnDuplicate, + SingleAttributeParser, +}; use crate::context::{AcceptContext, FinalizeContext, Stage}; use crate::parser::ArgParser; use crate::session_diagnostics; @@ -113,3 +117,58 @@ impl AttributeParser for MacroUseParser { Some(AttributeKind::MacroUse { span: self.first_span?, arguments: self.state }) } } + +pub(crate) struct MacroExportParser; + +impl SingleAttributeParser for crate::attributes::macro_attrs::MacroExportParser { + const PATH: &[Symbol] = &[sym::macro_export]; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Warn; + const TEMPLATE: AttributeTemplate = template!(Word, List: "local_inner_macros"); + + fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option { + let suggestions = + || >::TEMPLATE.suggestions(false, "macro_export"); + let local_inner_macros = match args { + ArgParser::NoArgs => false, + ArgParser::List(list) => { + let Some(l) = list.single() else { + let span = cx.attr_span; + cx.emit_lint( + AttributeLintKind::InvalidMacroExportArguments { + suggestions: suggestions(), + }, + span, + ); + return None; + }; + match l.meta_item().and_then(|i| i.path().word_sym()) { + Some(sym::local_inner_macros) => true, + _ => { + let span = cx.attr_span; + cx.emit_lint( + AttributeLintKind::InvalidMacroExportArguments { + suggestions: suggestions(), + }, + span, + ); + return None; + } + } + } + ArgParser::NameValue(_) => { + let span = cx.attr_span; + let suggestions = suggestions(); + cx.emit_err(session_diagnostics::IllFormedAttributeInputLint { + num_suggestions: suggestions.len(), + suggestions: DiagArgValue::StrListSepByAnd( + suggestions.into_iter().map(|s| format!("`{s}`").into()).collect(), + ), + span, + }); + return None; + } + }; + Some(AttributeKind::MacroExport { span: cx.attr_span, local_inner_macros }) + } +} diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index b51db9b4b9e38..85db54709840d 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -32,7 +32,7 @@ use crate::attributes::lint_helpers::{ AsPtrParser, AutomaticallyDerivedParser, PassByValueParser, PubTransparentParser, }; use crate::attributes::loop_match::{ConstContinueParser, LoopMatchParser}; -use crate::attributes::macro_attrs::{MacroEscapeParser, MacroUseParser}; +use crate::attributes::macro_attrs::{MacroEscapeParser, MacroExportParser, MacroUseParser}; use crate::attributes::must_use::MustUseParser; use crate::attributes::no_implicit_prelude::NoImplicitPreludeParser; use crate::attributes::non_exhaustive::NonExhaustiveParser; @@ -164,6 +164,7 @@ attribute_parsers!( Single, Single, Single, + Single, Single, Single, Single, diff --git a/compiler/rustc_attr_parsing/src/lints.rs b/compiler/rustc_attr_parsing/src/lints.rs index 22f5531bc8079..359b0ef0dd12c 100644 --- a/compiler/rustc_attr_parsing/src/lints.rs +++ b/compiler/rustc_attr_parsing/src/lints.rs @@ -34,5 +34,17 @@ pub fn emit_attribute_lint(lint: &AttributeLint, lint_emi *first_span, session_diagnostics::EmptyAttributeList { attr_span: *first_span }, ), + AttributeLintKind::InvalidMacroExportArguments { suggestions } => lint_emitter + .emit_node_span_lint( + rustc_session::lint::builtin::INVALID_MACRO_EXPORT_ARGUMENTS, + *id, + *span, + session_diagnostics::IllFormedAttributeInput { + num_suggestions: suggestions.len(), + suggestions: DiagArgValue::StrListSepByAnd( + suggestions.into_iter().map(|s| format!("`{s}`").into()).collect(), + ), + }, + ), } } diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 1a9832b2fe26a..e1fd184533f6f 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -910,9 +910,9 @@ impl SyntaxExtension { let allow_internal_unsafe = ast::attr::find_by_name(attrs, sym::allow_internal_unsafe).is_some(); - let local_inner_macros = ast::attr::find_by_name(attrs, sym::macro_export) - .and_then(|macro_export| macro_export.meta_item_list()) - .is_some_and(|l| ast::attr::list_contains_name(&l, sym::local_inner_macros)); + let local_inner_macros = + *find_attr!(attrs, AttributeKind::MacroExport {local_inner_macros: l, ..} => l) + .unwrap_or(&false); let collapse_debuginfo = Self::get_collapse_debuginfo(sess, attrs, !is_local); tracing::debug!(?name, ?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe); diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 80618422b56d6..c8b49322b9801 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -360,6 +360,9 @@ pub enum AttributeKind { /// Represents `#[macro_escape]`. MacroEscape(Span), + /// Represents [`#[macro_export]`](https://doc.rust-lang.org/reference/macros-by-example.html#r-macro.decl.scope.path). + MacroExport { span: Span, local_inner_macros: bool }, + /// Represents `#[rustc_macro_transparency]`. MacroTransparency(Transparency), diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index 9644a597a3117..55488f0c08731 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -46,6 +46,7 @@ impl AttributeKind { LinkSection { .. } => Yes, // Needed for rustdoc LoopMatch(..) => No, MacroEscape(..) => No, + MacroExport { .. } => Yes, MacroTransparency(..) => Yes, MacroUse { .. } => No, Marker(..) => No, diff --git a/compiler/rustc_hir/src/lints.rs b/compiler/rustc_hir/src/lints.rs index c55a41eb2b76b..b096c671edabe 100644 --- a/compiler/rustc_hir/src/lints.rs +++ b/compiler/rustc_hir/src/lints.rs @@ -31,7 +31,22 @@ pub struct AttributeLint { #[derive(Clone, Debug, HashStable_Generic)] pub enum AttributeLintKind { - UnusedDuplicate { this: Span, other: Span, warning: bool }, - IllFormedAttributeInput { suggestions: Vec }, - EmptyAttribute { first_span: Span }, + UnusedDuplicate { + this: Span, + other: Span, + warning: bool, + }, + IllFormedAttributeInput { + suggestions: Vec, + }, + EmptyAttribute { + first_span: Span, + }, + + /// Copy of `IllFormedAttributeInput` + /// specifically for the `invalid_macro_export_arguments` lint until that is removed, + /// see + InvalidMacroExportArguments { + suggestions: Vec, + }, } diff --git a/compiler/rustc_lint/src/non_local_def.rs b/compiler/rustc_lint/src/non_local_def.rs index b877f909fc029..d0254eccb39ef 100644 --- a/compiler/rustc_lint/src/non_local_def.rs +++ b/compiler/rustc_lint/src/non_local_def.rs @@ -1,11 +1,12 @@ use rustc_errors::MultiSpan; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::{self, Visitor, VisitorExt}; -use rustc_hir::{Body, HirId, Item, ItemKind, Node, Path, TyKind}; +use rustc_hir::{Body, HirId, Item, ItemKind, Node, Path, TyKind, find_attr}; use rustc_middle::ty::TyCtxt; use rustc_session::{declare_lint, impl_lint_pass}; use rustc_span::def_id::{DefId, LOCAL_CRATE}; -use rustc_span::{ExpnKind, MacroKind, Span, kw, sym}; +use rustc_span::{ExpnKind, MacroKind, Span, kw}; use crate::lints::{NonLocalDefinitionsCargoUpdateNote, NonLocalDefinitionsDiag}; use crate::{LateContext, LateLintPass, LintContext, fluent_generated as fluent}; @@ -241,7 +242,10 @@ impl<'tcx> LateLintPass<'tcx> for NonLocalDefinitions { ) } ItemKind::Macro(_, _macro, MacroKind::Bang) - if cx.tcx.has_attr(item.owner_id.def_id, sym::macro_export) => + if find_attr!( + cx.tcx.get_all_attrs(item.owner_id.def_id), + AttributeKind::MacroExport { .. } + ) => { cx.emit_span_lint( NON_LOCAL_DEFINITIONS, diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 3b84c6b611016..9e5ceb8977c13 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -4188,8 +4188,13 @@ declare_lint! { /// You can't have multiple arguments in a `#[macro_export(..)]`, or mention arguments other than `local_inner_macros`. /// pub INVALID_MACRO_EXPORT_ARGUMENTS, - Warn, + Deny, "\"invalid_parameter\" isn't a valid argument for `#[macro_export]`", + @future_incompatible = FutureIncompatibleInfo { + reason: FutureIncompatibilityReason::FutureReleaseError, + reference: "issue #57571 ", + report_in_deps: true, + }; } declare_lint! { diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index 6a28fe2617edf..f9c0f43803bc8 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -399,10 +399,6 @@ passes_invalid_attr_at_crate_level = passes_invalid_attr_at_crate_level_item = the inner attribute doesn't annotate this {$kind} -passes_invalid_macro_export_arguments = invalid `#[macro_export]` argument - -passes_invalid_macro_export_arguments_too_many_items = `#[macro_export]` can only take 1 or 0 arguments - passes_lang_item_fn = {$name -> [panic_impl] `#[panic_handler]` *[other] `{$name}` lang item diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 2663d5fe99c7a..98494810768b0 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -38,9 +38,8 @@ use rustc_middle::{bug, span_bug}; use rustc_session::config::CrateType; use rustc_session::lint; use rustc_session::lint::builtin::{ - CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, INVALID_MACRO_EXPORT_ARGUMENTS, - MALFORMED_DIAGNOSTIC_ATTRIBUTES, MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES, - USELESS_DEPRECATED, + CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, MALFORMED_DIAGNOSTIC_ATTRIBUTES, + MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES, USELESS_DEPRECATED, }; use rustc_session::parse::feature_err; use rustc_span::edition::Edition; @@ -291,6 +290,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::Dummy | AttributeKind::RustcBuiltinMacro { .. }, ) => { /* do nothing */ } + Attribute::Parsed(AttributeKind::MacroExport { span, .. }) => { + self.check_macro_export(hir_id, *span, target) + } Attribute::Parsed(AttributeKind::AsPtr(attr_span)) => { self.check_applied_to_fn_or_method(hir_id, *attr_span, span, target) } @@ -383,7 +385,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { [sym::ffi_const, ..] => self.check_ffi_const(attr.span(), target), [sym::link, ..] => self.check_link(hir_id, attr, span, target), [sym::path, ..] => self.check_generic_attr_unparsed(hir_id, attr, target, Target::Mod), - [sym::macro_export, ..] => self.check_macro_export(hir_id, attr, target), [sym::should_panic, ..] => { self.check_generic_attr_unparsed(hir_id, attr, target, Target::Fn) } @@ -2432,32 +2433,14 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - fn check_macro_export(&self, hir_id: HirId, attr: &Attribute, target: Target) { + fn check_macro_export(&self, hir_id: HirId, attr_span: Span, target: Target) { if target != Target::MacroDef { self.tcx.emit_node_span_lint( UNUSED_ATTRIBUTES, hir_id, - attr.span(), + attr_span, errors::MacroExport::Normal, ); - } else if let Some(meta_item_list) = attr.meta_item_list() - && !meta_item_list.is_empty() - { - if meta_item_list.len() > 1 { - self.tcx.emit_node_span_lint( - INVALID_MACRO_EXPORT_ARGUMENTS, - hir_id, - attr.span(), - errors::MacroExport::TooManyItems, - ); - } else if !meta_item_list[0].has_name(sym::local_inner_macros) { - self.tcx.emit_node_span_lint( - INVALID_MACRO_EXPORT_ARGUMENTS, - hir_id, - meta_item_list[0].span(), - errors::MacroExport::InvalidArgument, - ); - } } else { // special case when `#[macro_export]` is applied to a macro 2.0 let (_, macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro(); @@ -2467,7 +2450,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { self.tcx.emit_node_span_lint( UNUSED_ATTRIBUTES, hir_id, - attr.span(), + attr_span, errors::MacroExport::OnDeclMacro, ); } @@ -2820,7 +2803,9 @@ impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> { // In the long run, the checks should be harmonized. if let ItemKind::Macro(_, macro_def, _) = item.kind { let def_id = item.owner_id.to_def_id(); - if macro_def.macro_rules && !self.tcx.has_attr(def_id, sym::macro_export) { + if macro_def.macro_rules + && !find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::MacroExport { .. }) + { check_non_exported_macro_for_invalid_attrs(self.tcx, item); } } @@ -2950,7 +2935,6 @@ fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) { // which were unsuccessfully resolved due to cannot determine // resolution for the attribute macro error. const ATTRS_TO_CHECK: &[Symbol] = &[ - sym::macro_export, sym::rustc_main, sym::derive, sym::test, @@ -2975,6 +2959,8 @@ fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) { (*span, sym::path) } else if let Attribute::Parsed(AttributeKind::AutomaticallyDerived(span)) = attr { (*span, sym::automatically_derived) + } else if let Attribute::Parsed(AttributeKind::MacroExport { span, .. }) = attr { + (*span, sym::macro_export) } else { continue; }; diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index c6ab6b0d60179..ed9973df0e1d2 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -786,12 +786,6 @@ pub(crate) enum MacroExport { #[diag(passes_macro_export_on_decl_macro)] #[note] OnDeclMacro, - - #[diag(passes_invalid_macro_export_arguments)] - InvalidArgument, - - #[diag(passes_invalid_macro_export_arguments_too_many_items)] - TooManyItems, } #[derive(Subdiagnostic)] diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index e2f86b8a8549e..3304c61380993 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -6,6 +6,8 @@ use std::collections::{BTreeMap, VecDeque}; use encode::{bitmap_to_string, write_vlqhex_to_string}; use rustc_ast::join_path_syms; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::find_attr; use rustc_middle::ty::TyCtxt; use rustc_span::def_id::DefId; use rustc_span::sym; @@ -421,16 +423,17 @@ pub(crate) fn build_index( if fqp.last() != Some(&item.name) { return None; } - let path = - if item.ty == ItemType::Macro && tcx.has_attr(defid, sym::macro_export) { - // `#[macro_export]` always exports to the crate root. - tcx.crate_name(defid.krate).to_string() - } else { - if fqp.len() < 2 { - return None; - } - join_path_syms(&fqp[..fqp.len() - 1]) - }; + let path = if item.ty == ItemType::Macro + && find_attr!(tcx.get_all_attrs(defid), AttributeKind::MacroExport { .. }) + { + // `#[macro_export]` always exports to the crate root. + tcx.crate_name(defid.krate).to_string() + } else { + if fqp.len() < 2 { + return None; + } + join_path_syms(&fqp[..fqp.len() - 1]) + }; if path == item.path { return None; } diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index f966d9265628b..dd54b4e30d15c 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -908,12 +908,8 @@ fn maybe_from_hir_attr( hir::Attribute::Parsed(kind) => kind, hir::Attribute::Unparsed(_) => { - return Some(if attr.has_name(sym::macro_export) { - Attribute::MacroExport - // FIXME: We should handle `#[doc(hidden)]`. - } else { - other_attr(tcx, attr) - }); + // FIXME: We should handle `#[doc(hidden)]`. + return Some(other_attr(tcx, attr)); } }; @@ -921,6 +917,7 @@ fn maybe_from_hir_attr( AK::Deprecation { .. } => return None, // Handled separately into Item::deprecation. AK::DocComment { .. } => unreachable!("doc comments stripped out earlier"), + AK::MacroExport { .. } => Attribute::MacroExport, AK::MustUse { reason, span: _ } => { Attribute::MustUse { reason: reason.map(|s| s.to_string()) } } diff --git a/src/librustdoc/passes/strip_hidden.rs b/src/librustdoc/passes/strip_hidden.rs index 3388ae46f056c..525d05b6a9860 100644 --- a/src/librustdoc/passes/strip_hidden.rs +++ b/src/librustdoc/passes/strip_hidden.rs @@ -2,9 +2,10 @@ use std::mem; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId}; +use rustc_hir::find_attr; use rustc_middle::ty::TyCtxt; -use rustc_span::symbol::sym; use tracing::debug; use crate::clean::utils::inherits_doc_hidden; @@ -114,7 +115,7 @@ impl DocFolder for Stripper<'_, '_> { // If the macro has the `#[macro_export]` attribute, it means it's accessible at the // crate level so it should be handled differently. clean::MacroItem(..) => { - i.attrs.other_attrs.iter().any(|attr| attr.has_name(sym::macro_export)) + find_attr!(&i.attrs.other_attrs, AttributeKind::MacroExport { .. }) } _ => false, }; diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 9058277d72eea..428149b95f468 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -5,10 +5,11 @@ use std::mem; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId, LocalDefIdSet}; use rustc_hir::intravisit::{Visitor, walk_body, walk_item}; -use rustc_hir::{CRATE_HIR_ID, Node}; +use rustc_hir::{CRATE_HIR_ID, Node, find_attr}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; use rustc_span::Span; @@ -167,7 +168,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { if !child.reexport_chain.is_empty() && let Res::Def(DefKind::Macro(_), def_id) = child.res && let Some(local_def_id) = def_id.as_local() - && self.cx.tcx.has_attr(def_id, sym::macro_export) + && find_attr!(self.cx.tcx.get_all_attrs(def_id), AttributeKind::MacroExport { .. }) && inserted.insert(def_id) { let item = self.cx.tcx.hir_expect_item(local_def_id); @@ -407,7 +408,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { || match item.kind { hir::ItemKind::Impl(..) => true, hir::ItemKind::Macro(_, _, MacroKind::Bang) => { - self.cx.tcx.has_attr(item.owner_id.def_id, sym::macro_export) + find_attr!(self.cx.tcx.get_all_attrs(item.owner_id.def_id), AttributeKind::MacroExport{..}) } _ => false, } @@ -525,7 +526,8 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { let def_id = item.owner_id.to_def_id(); let is_macro_2_0 = !macro_def.macro_rules; - let nonexported = !tcx.has_attr(def_id, sym::macro_export); + let nonexported = + !find_attr!(tcx.get_all_attrs(def_id), AttributeKind::MacroExport { .. }); if is_macro_2_0 || nonexported || self.inlining { self.add_to_current_mod(item, renamed, import_id); diff --git a/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs b/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs index 9071c9c95f9d7..c5acaf0999332 100644 --- a/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs +++ b/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs @@ -5,10 +5,12 @@ use itertools::Itertools; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{Visitor, walk_block, walk_expr, walk_stmt}; use rustc_hir::{BlockCheckMode, Expr, ExprKind, HirId, Stmt, UnsafeSource}; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::find_attr; use rustc_lint::{LateContext, LateLintPass, Level, LintContext}; use rustc_middle::lint::LevelAndSource; use rustc_session::impl_lint_pass; -use rustc_span::{Span, SyntaxContext, sym}; +use rustc_span::{Span, SyntaxContext}; use std::collections::BTreeMap; use std::collections::btree_map::Entry; @@ -146,7 +148,8 @@ struct BodyVisitor<'a, 'tcx> { } fn is_public_macro(cx: &LateContext<'_>, def_id: LocalDefId) -> bool { - (cx.effective_visibilities.is_exported(def_id) || cx.tcx.has_attr(def_id, sym::macro_export)) + ( cx.effective_visibilities.is_exported(def_id) || + find_attr!(cx.tcx.get_all_attrs(def_id), AttributeKind::MacroExport{..}) ) && !cx.tcx.is_doc_hidden(def_id) } diff --git a/tests/ui/attributes/invalid_macro_export_argument.allow.stderr b/tests/ui/attributes/invalid_macro_export_argument.allow.stderr new file mode 100644 index 0000000000000..2db60a6897282 --- /dev/null +++ b/tests/ui/attributes/invalid_macro_export_argument.allow.stderr @@ -0,0 +1,40 @@ +Future incompatibility report: Future breakage diagnostic: +warning: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` + --> $DIR/invalid_macro_export_argument.rs:7:1 + | +LL | #[macro_export(hello, world)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 + +Future breakage diagnostic: +warning: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` + --> $DIR/invalid_macro_export_argument.rs:14:1 + | +LL | #[macro_export(not_local_inner_macros)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 + +Future breakage diagnostic: +warning: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` + --> $DIR/invalid_macro_export_argument.rs:31:1 + | +LL | #[macro_export()] + | ^^^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 + +Future breakage diagnostic: +warning: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` + --> $DIR/invalid_macro_export_argument.rs:38:1 + | +LL | #[macro_export("blah")] + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 + diff --git a/tests/ui/attributes/invalid_macro_export_argument.deny.stderr b/tests/ui/attributes/invalid_macro_export_argument.deny.stderr index 9d44bd162c7b7..fd50b824d0a26 100644 --- a/tests/ui/attributes/invalid_macro_export_argument.deny.stderr +++ b/tests/ui/attributes/invalid_macro_export_argument.deny.stderr @@ -1,26 +1,103 @@ -error: `#[macro_export]` can only take 1 or 0 arguments +error: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` --> $DIR/invalid_macro_export_argument.rs:7:1 | LL | #[macro_export(hello, world)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 note: the lint level is defined here --> $DIR/invalid_macro_export_argument.rs:4:24 | LL | #![cfg_attr(deny, deny(invalid_macro_export_arguments))] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: invalid `#[macro_export]` argument - --> $DIR/invalid_macro_export_argument.rs:13:16 +error: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` + --> $DIR/invalid_macro_export_argument.rs:14:1 | LL | #[macro_export(not_local_inner_macros)] - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 + +error: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` + --> $DIR/invalid_macro_export_argument.rs:31:1 + | +LL | #[macro_export()] + | ^^^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 -error: invalid `#[macro_export]` argument - --> $DIR/invalid_macro_export_argument.rs:33:16 +error: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` + --> $DIR/invalid_macro_export_argument.rs:38:1 | LL | #[macro_export("blah")] - | ^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 + +error: aborting due to 4 previous errors + +Future incompatibility report: Future breakage diagnostic: +error: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` + --> $DIR/invalid_macro_export_argument.rs:7:1 + | +LL | #[macro_export(hello, world)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 +note: the lint level is defined here + --> $DIR/invalid_macro_export_argument.rs:4:24 + | +LL | #![cfg_attr(deny, deny(invalid_macro_export_arguments))] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Future breakage diagnostic: +error: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` + --> $DIR/invalid_macro_export_argument.rs:14:1 + | +LL | #[macro_export(not_local_inner_macros)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 +note: the lint level is defined here + --> $DIR/invalid_macro_export_argument.rs:4:24 + | +LL | #![cfg_attr(deny, deny(invalid_macro_export_arguments))] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 3 previous errors +Future breakage diagnostic: +error: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` + --> $DIR/invalid_macro_export_argument.rs:31:1 + | +LL | #[macro_export()] + | ^^^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 +note: the lint level is defined here + --> $DIR/invalid_macro_export_argument.rs:4:24 + | +LL | #![cfg_attr(deny, deny(invalid_macro_export_arguments))] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Future breakage diagnostic: +error: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` + --> $DIR/invalid_macro_export_argument.rs:38:1 + | +LL | #[macro_export("blah")] + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 +note: the lint level is defined here + --> $DIR/invalid_macro_export_argument.rs:4:24 + | +LL | #![cfg_attr(deny, deny(invalid_macro_export_arguments))] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/attributes/invalid_macro_export_argument.rs b/tests/ui/attributes/invalid_macro_export_argument.rs index c5fe39d062a4e..05a40913434e8 100644 --- a/tests/ui/attributes/invalid_macro_export_argument.rs +++ b/tests/ui/attributes/invalid_macro_export_argument.rs @@ -5,13 +5,15 @@ #![cfg_attr(allow, allow(invalid_macro_export_arguments))] #[macro_export(hello, world)] -//[deny]~^ ERROR `#[macro_export]` can only take 1 or 0 arguments +//[deny]~^ ERROR valid forms for the attribute are +//[deny]~| WARN this was previously accepted macro_rules! a { () => () } #[macro_export(not_local_inner_macros)] -//[deny]~^ ERROR invalid `#[macro_export]` argument +//[deny]~^ ERROR valid forms for the attribute are +//[deny]~| WARN this was previously accepted macro_rules! b { () => () } @@ -20,18 +22,22 @@ macro_rules! b { macro_rules! c { () => () } + #[macro_export(local_inner_macros)] macro_rules! d { () => () } #[macro_export()] +//[deny]~^ ERROR valid forms for the attribute are +//[deny]~| WARN this was previously accepted macro_rules! e { () => () } #[macro_export("blah")] -//[deny]~^ ERROR invalid `#[macro_export]` argument +//[deny]~^ ERROR valid forms for the attribute are +//[deny]~| WARN this was previously accepted macro_rules! f { () => () } diff --git a/tests/ui/attributes/malformed-attrs.rs b/tests/ui/attributes/malformed-attrs.rs index 0d5bf69d548ce..76e2e931f17b8 100644 --- a/tests/ui/attributes/malformed-attrs.rs +++ b/tests/ui/attributes/malformed-attrs.rs @@ -209,7 +209,7 @@ extern crate wloop; //~^ ERROR can't find crate for `wloop` [E0463] #[macro_export = 18] -//~^ ERROR malformed `macro_export` attribute input +//~^ ERROR valid forms for the attribute are #[allow_internal_unsafe = 1] //~^ ERROR malformed //~| ERROR allow_internal_unsafe side-steps the unsafe_code lint diff --git a/tests/ui/attributes/malformed-attrs.stderr b/tests/ui/attributes/malformed-attrs.stderr index 1b51075b4e888..62cea759f9ccc 100644 --- a/tests/ui/attributes/malformed-attrs.stderr +++ b/tests/ui/attributes/malformed-attrs.stderr @@ -136,21 +136,6 @@ error: malformed `no_link` attribute input LL | #[no_link()] | ^^^^^^^^^^^^ help: must be of the form: `#[no_link]` -error: malformed `macro_export` attribute input - --> $DIR/malformed-attrs.rs:211:1 - | -LL | #[macro_export = 18] - | ^^^^^^^^^^^^^^^^^^^^ - | -help: the following are the possible correct uses - | -LL - #[macro_export = 18] -LL + #[macro_export(local_inner_macros)] - | -LL - #[macro_export = 18] -LL + #[macro_export] - | - error: malformed `allow_internal_unsafe` attribute input --> $DIR/malformed-attrs.rs:213:1 | @@ -558,6 +543,12 @@ error: valid forms for the attribute are `#[macro_use(name1, name2, ...)]` and ` LL | #[macro_use = 1] | ^^^^^^^^^^^^^^^^ +error: valid forms for the attribute are `#[macro_export(local_inner_macros)]` and `#[macro_export]` + --> $DIR/malformed-attrs.rs:211:1 + | +LL | #[macro_export = 18] + | ^^^^^^^^^^^^^^^^^^^^ + error[E0565]: malformed `type_const` attribute input --> $DIR/malformed-attrs.rs:140:5 | diff --git a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs-error.stderr b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs-error.stderr index 4cba54bf67c12..6d3b1e4e27380 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs-error.stderr +++ b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs-error.stderr @@ -91,21 +91,6 @@ error[E0518]: attribute should be applied to function or closure LL | #![inline] | ^^^^^^^^^^ not a function or closure -error: `macro_export` attribute cannot be used at crate level - --> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:12:1 - | -LL | #![macro_export] - | ^^^^^^^^^^^^^^^^ -... -LL | mod inline { - | ------ the inner attribute doesn't annotate this module - | -help: perhaps you meant to use an outer attribute - | -LL - #![macro_export] -LL + #[macro_export] - | - error: `rustc_main` attribute cannot be used at crate level --> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:14:1 | @@ -136,6 +121,21 @@ LL - #![repr()] LL + #[repr()] | +error: `macro_export` attribute cannot be used at crate level + --> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:12:1 + | +LL | #![macro_export] + | ^^^^^^^^^^^^^^^^ +... +LL | mod inline { + | ------ the inner attribute doesn't annotate this module + | +help: perhaps you meant to use an outer attribute + | +LL - #![macro_export] +LL + #[macro_export] + | + error: `path` attribute cannot be used at crate level --> $DIR/issue-43106-gating-of-builtin-attrs-error.rs:21:1 | diff --git a/tests/ui/lint/unused/unused-attr-duplicate.stderr b/tests/ui/lint/unused/unused-attr-duplicate.stderr index e277f5203c698..817556aa165be 100644 --- a/tests/ui/lint/unused/unused-attr-duplicate.stderr +++ b/tests/ui/lint/unused/unused-attr-duplicate.stderr @@ -104,18 +104,6 @@ note: attribute also specified here LL | #![no_builtins] | ^^^^^^^^^^^^^^^ -error: unused attribute - --> $DIR/unused-attr-duplicate.rs:40:5 - | -LL | #[macro_export] - | ^^^^^^^^^^^^^^^ help: remove this attribute - | -note: attribute also specified here - --> $DIR/unused-attr-duplicate.rs:39:5 - | -LL | #[macro_export] - | ^^^^^^^^^^^^^^^ - error: unused attribute --> $DIR/unused-attr-duplicate.rs:37:1 | @@ -128,6 +116,18 @@ note: attribute also specified here LL | #[macro_use] | ^^^^^^^^^^^^ +error: unused attribute + --> $DIR/unused-attr-duplicate.rs:40:5 + | +LL | #[macro_export] + | ^^^^^^^^^^^^^^^ help: remove this attribute + | +note: attribute also specified here + --> $DIR/unused-attr-duplicate.rs:39:5 + | +LL | #[macro_export] + | ^^^^^^^^^^^^^^^ + error: unused attribute --> $DIR/unused-attr-duplicate.rs:47:1 | From f6ce4ac9d38fca2df5bc408de8f4c2567d2f2709 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 2 Aug 2025 17:36:34 +0000 Subject: [PATCH 17/30] Anonymize binders in tail call sig --- compiler/rustc_mir_build/src/check_tail_calls.rs | 6 +++++- tests/ui/explicit-tail-calls/higher-ranked-arg.rs | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 tests/ui/explicit-tail-calls/higher-ranked-arg.rs diff --git a/compiler/rustc_mir_build/src/check_tail_calls.rs b/compiler/rustc_mir_build/src/check_tail_calls.rs index 6ed100899d8c5..036e20c22b8f4 100644 --- a/compiler/rustc_mir_build/src/check_tail_calls.rs +++ b/compiler/rustc_mir_build/src/check_tail_calls.rs @@ -60,9 +60,13 @@ impl<'tcx> TailCallCkVisitor<'_, 'tcx> { let BodyTy::Fn(caller_sig) = self.thir.body_type else { span_bug!( call.span, - "`become` outside of functions should have been disallowed by hit_typeck" + "`become` outside of functions should have been disallowed by hir_typeck" ) }; + // While the `caller_sig` does have its regions erased, it does not have its + // binders anonymized. We call `erase_regions` once again to anonymize any binders + // within the signature, such as in function pointer or `dyn Trait` args. + let caller_sig = self.tcx.erase_regions(caller_sig); let ExprKind::Scope { value, .. } = call.kind else { span_bug!(call.span, "expected scope, found: {call:?}") diff --git a/tests/ui/explicit-tail-calls/higher-ranked-arg.rs b/tests/ui/explicit-tail-calls/higher-ranked-arg.rs new file mode 100644 index 0000000000000..e60686ab5111d --- /dev/null +++ b/tests/ui/explicit-tail-calls/higher-ranked-arg.rs @@ -0,0 +1,13 @@ +// Regression test for . +//@ check-pass + +#![feature(explicit_tail_calls)] +#![expect(incomplete_features)] + +fn foo(x: fn(&i32)) { + become bar(x); +} + +fn bar(_: fn(&i32)) {} + +fn main() {} From c7ea022166d2b6d55c3f69bbf69a31b0d7b053e2 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 4 Aug 2025 16:24:41 +0000 Subject: [PATCH 18/30] Enforce tail call type is related to body return type in borrowck --- compiler/rustc_borrowck/src/type_check/mod.rs | 10 +++++++--- .../ret-ty-borrowck-constraints.rs | 16 ++++++++++++++++ .../ret-ty-borrowck-constraints.stderr | 10 ++++++++++ 3 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.rs create mode 100644 tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.stderr diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index f5fedbf95c1c1..91973f33bd320 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -845,9 +845,13 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ); } - if let TerminatorKind::Call { destination, target, .. } = term.kind { - self.check_call_dest(term, &sig, destination, target, term_location); - } + let (destination, target) = + if let TerminatorKind::Call { destination, target, .. } = term.kind { + (destination, target) + } else { + (RETURN_PLACE.into(), Some(BasicBlock::ZERO)) + }; + self.check_call_dest(term, &sig, destination, target, term_location); // The ordinary liveness rules will ensure that all // regions in the type of the callee are live here. We diff --git a/tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.rs b/tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.rs new file mode 100644 index 0000000000000..111ae849c0f6a --- /dev/null +++ b/tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.rs @@ -0,0 +1,16 @@ +#![feature(explicit_tail_calls)] +#![expect(incomplete_features)] + +fn link(x: &str) -> &'static str { + become passthrough(x); + //~^ ERROR lifetime may not live long enough +} + +fn passthrough(t: T) -> T { t } + +fn main() { + let x = String::from("hello, world"); + let s = link(&x); + drop(x); + println!("{s}"); +} diff --git a/tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.stderr b/tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.stderr new file mode 100644 index 0000000000000..26a8e1f0122ad --- /dev/null +++ b/tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.stderr @@ -0,0 +1,10 @@ +error: lifetime may not live long enough + --> $DIR/ret-ty-borrowck-constraints.rs:5:5 + | +LL | fn link(x: &str) -> &'static str { + | - let's call the lifetime of this reference `'1` +LL | become passthrough(x); + | ^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'static` + +error: aborting due to 1 previous error + From 904e2af3a97e81637b9816d71411d52e26bd1550 Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Fri, 1 Aug 2025 18:25:57 +0200 Subject: [PATCH 19/30] Port `#[coroutine]` to the new attribute system Related to https://github.com/rust-lang/rust/issues/131229#issue-2565886367. --- compiler/rustc_ast_lowering/src/expr.rs | 18 ++++++------------ .../rustc_attr_parsing/src/attributes/body.rs | 15 +++++++++++++++ .../rustc_attr_parsing/src/attributes/mod.rs | 1 + compiler/rustc_attr_parsing/src/context.rs | 2 ++ .../rustc_hir/src/attrs/data_structures.rs | 3 +++ .../rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_passes/src/check_attr.rs | 10 +++++----- tests/ui/attributes/malformed-attrs.stderr | 15 +++++++++------ 8 files changed, 42 insertions(+), 23 deletions(-) create mode 100644 compiler/rustc_attr_parsing/src/attributes/body.rs diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 1245d48975470..fb42cfea30b41 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -98,7 +98,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } let expr_hir_id = self.lower_node_id(e.id); - self.lower_attrs(expr_hir_id, &e.attrs, e.span); + let attrs = self.lower_attrs(expr_hir_id, &e.attrs, e.span); let kind = match &e.kind { ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)), @@ -232,10 +232,10 @@ impl<'hir> LoweringContext<'_, 'hir> { *fn_arg_span, ), None => self.lower_expr_closure( + attrs, binder, *capture_clause, e.id, - expr_hir_id, *constness, *movability, fn_decl, @@ -1052,10 +1052,10 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_expr_closure( &mut self, + attrs: &[rustc_hir::Attribute], binder: &ClosureBinder, capture_clause: CaptureBy, closure_id: NodeId, - closure_hir_id: hir::HirId, constness: Const, movability: Movability, decl: &FnDecl, @@ -1067,15 +1067,9 @@ impl<'hir> LoweringContext<'_, 'hir> { let (binder_clause, generic_params) = self.lower_closure_binder(binder); let (body_id, closure_kind) = self.with_new_scopes(fn_decl_span, move |this| { - let mut coroutine_kind = if this - .attrs - .get(&closure_hir_id.local_id) - .is_some_and(|attrs| attrs.iter().any(|attr| attr.has_name(sym::coroutine))) - { - Some(hir::CoroutineKind::Coroutine(Movability::Movable)) - } else { - None - }; + + let mut coroutine_kind = find_attr!(attrs, AttributeKind::Coroutine(_) => hir::CoroutineKind::Coroutine(Movability::Movable)); + // FIXME(contracts): Support contracts on closures? let body_id = this.lower_fn_body(decl, None, |this| { this.coroutine_kind = coroutine_kind; diff --git a/compiler/rustc_attr_parsing/src/attributes/body.rs b/compiler/rustc_attr_parsing/src/attributes/body.rs new file mode 100644 index 0000000000000..ab9330216f6c6 --- /dev/null +++ b/compiler/rustc_attr_parsing/src/attributes/body.rs @@ -0,0 +1,15 @@ +//! Attributes that can be found in function body. + +use rustc_hir::attrs::AttributeKind; +use rustc_span::{Symbol, sym}; + +use super::{NoArgsAttributeParser, OnDuplicate}; +use crate::context::Stage; + +pub(crate) struct CoroutineParser; + +impl NoArgsAttributeParser for CoroutineParser { + const PATH: &[Symbol] = &[sym::coroutine]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const CREATE: fn(rustc_span::Span) -> AttributeKind = |span| AttributeKind::Coroutine(span); +} diff --git a/compiler/rustc_attr_parsing/src/attributes/mod.rs b/compiler/rustc_attr_parsing/src/attributes/mod.rs index c574ef78bdf79..f7946ade6d2b2 100644 --- a/compiler/rustc_attr_parsing/src/attributes/mod.rs +++ b/compiler/rustc_attr_parsing/src/attributes/mod.rs @@ -26,6 +26,7 @@ use crate::parser::ArgParser; use crate::session_diagnostics::UnusedMultiple; pub(crate) mod allow_unstable; +pub(crate) mod body; pub(crate) mod cfg; pub(crate) mod cfg_old; pub(crate) mod codegen_attrs; diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index b51db9b4b9e38..ec74f6fd1c6f4 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -16,6 +16,7 @@ use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym}; use crate::attributes::allow_unstable::{ AllowConstFnUnstableParser, AllowInternalUnstableParser, UnstableFeatureBoundParser, }; +use crate::attributes::body::CoroutineParser; use crate::attributes::codegen_attrs::{ ColdParser, CoverageParser, ExportNameParser, NakedParser, NoMangleParser, OptimizeParser, TargetFeatureParser, TrackCallerParser, UsedParser, @@ -184,6 +185,7 @@ attribute_parsers!( Single>, Single>, Single>, + Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 80618422b56d6..d9d2ec48948e7 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -297,6 +297,9 @@ pub enum AttributeKind { /// Represents `#[const_trait]`. ConstTrait(Span), + /// Represents `#[coroutine]`. + Coroutine(Span), + /// Represents `#[coverage(..)]`. Coverage(Span, CoverageAttrKind), diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index 9644a597a3117..b66e5bbeabe73 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -28,6 +28,7 @@ impl AttributeKind { ConstStability { .. } => Yes, ConstStabilityIndirect => No, ConstTrait(..) => No, + Coroutine(..) => No, Coverage(..) => No, DenyExplicitImpl(..) => No, Deprecation { .. } => Yes, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 2663d5fe99c7a..890028d977d30 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -324,6 +324,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { &Attribute::Parsed(AttributeKind::Coverage(attr_span, _)) => { self.check_coverage(attr_span, span, target) } + &Attribute::Parsed(AttributeKind::Coroutine(attr_span)) => { + self.check_coroutine(attr_span, target) + } Attribute::Unparsed(attr_item) => { style = Some(attr_item.style); match attr.path().as_slice() { @@ -390,9 +393,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { [sym::autodiff_forward, ..] | [sym::autodiff_reverse, ..] => { self.check_autodiff(hir_id, attr, span, target) } - [sym::coroutine, ..] => { - self.check_coroutine(attr, target); - } [sym::linkage, ..] => self.check_linkage(attr, span, target), [ // ok @@ -2651,11 +2651,11 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - fn check_coroutine(&self, attr: &Attribute, target: Target) { + fn check_coroutine(&self, attr_span: Span, target: Target) { match target { Target::Closure => return, _ => { - self.dcx().emit_err(errors::CoroutineOnNonClosure { span: attr.span() }); + self.dcx().emit_err(errors::CoroutineOnNonClosure { span: attr_span }); } } } diff --git a/tests/ui/attributes/malformed-attrs.stderr b/tests/ui/attributes/malformed-attrs.stderr index 1b51075b4e888..e8ae4715398f4 100644 --- a/tests/ui/attributes/malformed-attrs.stderr +++ b/tests/ui/attributes/malformed-attrs.stderr @@ -55,12 +55,6 @@ error: malformed `patchable_function_entry` attribute input LL | #[patchable_function_entry] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[patchable_function_entry(prefix_nops = m, entry_nops = n)]` -error: malformed `coroutine` attribute input - --> $DIR/malformed-attrs.rs:108:5 - | -LL | #[coroutine = 63] || {} - | ^^^^^^^^^^^^^^^^^ help: must be of the form: `#[coroutine]` - error: malformed `must_not_suspend` attribute input --> $DIR/malformed-attrs.rs:129:1 | @@ -436,6 +430,15 @@ LL | #[proc_macro = 18] | | didn't expect any arguments here | help: must be of the form: `#[proc_macro]` +error[E0565]: malformed `coroutine` attribute input + --> $DIR/malformed-attrs.rs:108:5 + | +LL | #[coroutine = 63] || {} + | ^^^^^^^^^^^^----^ + | | | + | | didn't expect any arguments here + | help: must be of the form: `#[coroutine]` + error[E0565]: malformed `proc_macro_attribute` attribute input --> $DIR/malformed-attrs.rs:113:1 | From b4f404b581a3e93c146ca2ea711fa03dca77327b Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 4 Aug 2025 17:23:56 +0200 Subject: [PATCH 20/30] Fix wrong font being used for tooltips `i` icons --- src/librustdoc/html/static/css/rustdoc.css | 4 ++++ tests/rustdoc-gui/notable-trait.goml | 4 ++-- tests/rustdoc-gui/src/test_docs/lib.rs | 14 ++++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css index 99b3da8b2cd47..c48863b4681ef 100644 --- a/src/librustdoc/html/static/css/rustdoc.css +++ b/src/librustdoc/html/static/css/rustdoc.css @@ -1838,6 +1838,10 @@ instead, we check that it's not a "finger" cursor. border-right: 3px solid var(--target-border-color); } +a.tooltip { + font-family: var(--font-family); +} + .code-header a.tooltip { color: inherit; margin-right: 15px; diff --git a/tests/rustdoc-gui/notable-trait.goml b/tests/rustdoc-gui/notable-trait.goml index 7fc70e0675df4..423a273fde746 100644 --- a/tests/rustdoc-gui/notable-trait.goml +++ b/tests/rustdoc-gui/notable-trait.goml @@ -8,10 +8,10 @@ define-function: ( [x, i_x], block { // Checking they have the same y position. - compare-elements-position: ( + compare-elements-position-near: ( "//*[@id='method.create_an_iterator_from_read']//a[normalize-space()='NotableStructWithLongName']", "//*[@id='method.create_an_iterator_from_read']//*[@class='tooltip']", - ["y"], + {"y": 1}, ) // Checking they don't have the same x position. compare-elements-position-false: ( diff --git a/tests/rustdoc-gui/src/test_docs/lib.rs b/tests/rustdoc-gui/src/test_docs/lib.rs index e8afe8b568727..623f5b33e9bc9 100644 --- a/tests/rustdoc-gui/src/test_docs/lib.rs +++ b/tests/rustdoc-gui/src/test_docs/lib.rs @@ -767,3 +767,17 @@ pub mod impls_indent { pub fn bar() {} } } + +pub mod tooltips { + pub struct X; + + impl X { + pub fn bar() -> Vec { + Vec::new() + } + } + + pub fn bar() -> Vec { + Vec::new() + } +} From 22607491bb944a715a15c15749f563986e6984bf Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 4 Aug 2025 17:41:48 +0200 Subject: [PATCH 21/30] Add GUI regression test for tooltips `i` icons --- tests/rustdoc-gui/tooltips.goml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 tests/rustdoc-gui/tooltips.goml diff --git a/tests/rustdoc-gui/tooltips.goml b/tests/rustdoc-gui/tooltips.goml new file mode 100644 index 0000000000000..6e79196be2731 --- /dev/null +++ b/tests/rustdoc-gui/tooltips.goml @@ -0,0 +1,15 @@ +// This test checks that the right font is applied to the `i` tooltip element. + +define-function: ( + "check-font", + [path], + block { + go-to: "file://" + |DOC_PATH| + "/test_docs/" + |path| + assert-css: ( + "a.tooltip", {"font-family": '"Source Serif 4", NanumBarunGothic, serif'}, ALL, + ) + } +) + +call-function: ("check-font", {"path": "tooltips/fn.bar.html"}) +call-function: ("check-font", {"path": "tooltips/struct.X.html"}) From 91e606b715ac4e8f59fac86d42ec2ad23f4ef169 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 28 Feb 2025 23:37:37 +0000 Subject: [PATCH 22/30] Tweak auto trait errors Make suggestions to remove params and super traits tool-only, and make the suggestion span more accurate. ``` error[E0567]: auto traits cannot have generic parameters --> $DIR/auto-trait-validation.rs:6:19 | LL | auto trait Generic {} | -------^^^ | | | auto trait cannot have generic parameters error[E0568]: auto traits cannot have super traits or lifetime bounds --> $DIR/auto-trait-validation.rs:8:20 | LL | auto trait Bound : Copy {} | ----- ^^^^ | | | auto traits cannot have super traits or lifetime bounds ``` ``` error[E0380]: auto traits cannot have associated items --> $DIR/issue-23080.rs:5:8 | LL | unsafe auto trait Trait { | ----- auto traits cannot have associated items LL | fn method(&self) { | ^^^^^^ ``` --- compiler/rustc_ast_passes/messages.ftl | 2 +- .../rustc_ast_passes/src/ast_validation.rs | 16 +++-- compiler/rustc_ast_passes/src/errors.rs | 9 +-- tests/ui/auto-traits/assoc-ty.current.stderr | 2 +- tests/ui/auto-traits/assoc-ty.next.stderr | 2 +- .../auto-traits/auto-trait-validation.fixed | 11 ++++ tests/ui/auto-traits/auto-trait-validation.rs | 15 +++++ .../auto-traits/auto-trait-validation.stderr | 65 ++++++++++++++++--- .../ui/auto-traits/bad-generics-on-dyn.stderr | 2 +- tests/ui/auto-traits/has-arguments.stderr | 2 +- tests/ui/auto-traits/issue-117789.stderr | 2 +- .../auto-traits/issue-23080-2.current.stderr | 2 +- .../ui/auto-traits/issue-23080-2.next.stderr | 2 +- tests/ui/auto-traits/issue-23080.stderr | 11 ++-- tests/ui/auto-traits/issue-84075.stderr | 2 +- .../typeck-auto-trait-no-supertraits-2.stderr | 6 +- .../typeck-auto-trait-no-supertraits.stderr | 4 +- tests/ui/methods/issues/issue-105732.stderr | 2 +- .../supertrait-auto-trait.stderr | 4 +- 19 files changed, 118 insertions(+), 43 deletions(-) diff --git a/compiler/rustc_ast_passes/messages.ftl b/compiler/rustc_ast_passes/messages.ftl index af93d55c89826..9b9c1105e47f2 100644 --- a/compiler/rustc_ast_passes/messages.ftl +++ b/compiler/rustc_ast_passes/messages.ftl @@ -40,7 +40,7 @@ ast_passes_auto_generic = auto traits cannot have generic parameters ast_passes_auto_items = auto traits cannot have associated items .label = {ast_passes_auto_items} - .suggestion = remove these associated items + .suggestion = remove the associated items ast_passes_auto_super_lifetime = auto traits cannot have super traits or lifetime bounds .label = {ast_passes_auto_super_lifetime} diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 895a457ec1d56..e99e5cc4ae65b 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -699,19 +699,23 @@ impl<'a> AstValidator<'a> { } } - fn deny_super_traits(&self, bounds: &GenericBounds, ident_span: Span) { + fn deny_super_traits(&self, bounds: &GenericBounds, ident: Span) { if let [.., last] = &bounds[..] { - let span = ident_span.shrink_to_hi().to(last.span()); - self.dcx().emit_err(errors::AutoTraitBounds { span, ident: ident_span }); + let span = bounds.iter().map(|b| b.span()).collect(); + let removal = ident.shrink_to_hi().to(last.span()); + self.dcx().emit_err(errors::AutoTraitBounds { span, removal, ident }); } } - fn deny_where_clause(&self, where_clause: &WhereClause, ident_span: Span) { + fn deny_where_clause(&self, where_clause: &WhereClause, ident: Span) { if !where_clause.predicates.is_empty() { // FIXME: The current diagnostic is misleading since it only talks about // super trait and lifetime bounds while we should just say “bounds”. - self.dcx() - .emit_err(errors::AutoTraitBounds { span: where_clause.span, ident: ident_span }); + self.dcx().emit_err(errors::AutoTraitBounds { + span: vec![where_clause.span], + removal: where_clause.span, + ident, + }); } } diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index fd4b2528541e3..2e3b1510755f1 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -344,7 +344,7 @@ pub(crate) struct ModuleNonAscii { #[diag(ast_passes_auto_generic, code = E0567)] pub(crate) struct AutoTraitGeneric { #[primary_span] - #[suggestion(code = "", applicability = "machine-applicable")] + #[suggestion(code = "", applicability = "machine-applicable", style = "tool-only")] pub span: Span, #[label] pub ident: Span, @@ -354,8 +354,9 @@ pub(crate) struct AutoTraitGeneric { #[diag(ast_passes_auto_super_lifetime, code = E0568)] pub(crate) struct AutoTraitBounds { #[primary_span] - #[suggestion(code = "", applicability = "machine-applicable")] - pub span: Span, + pub span: Vec, + #[suggestion(code = "", applicability = "machine-applicable", style = "tool-only")] + pub removal: Span, #[label] pub ident: Span, } @@ -365,7 +366,7 @@ pub(crate) struct AutoTraitBounds { pub(crate) struct AutoTraitItems { #[primary_span] pub spans: Vec, - #[suggestion(code = "", applicability = "machine-applicable")] + #[suggestion(code = "", applicability = "machine-applicable", style = "tool-only")] pub total: Span, #[label] pub ident: Span, diff --git a/tests/ui/auto-traits/assoc-ty.current.stderr b/tests/ui/auto-traits/assoc-ty.current.stderr index 77a1c8fb654f1..d793ae6652675 100644 --- a/tests/ui/auto-traits/assoc-ty.current.stderr +++ b/tests/ui/auto-traits/assoc-ty.current.stderr @@ -5,7 +5,7 @@ LL | auto trait Trait { | ----- auto traits cannot have associated items LL | LL | type Output; - | -----^^^^^^- help: remove these associated items + | ^^^^^^ error[E0658]: auto traits are experimental and possibly buggy --> $DIR/assoc-ty.rs:8:1 diff --git a/tests/ui/auto-traits/assoc-ty.next.stderr b/tests/ui/auto-traits/assoc-ty.next.stderr index 4ce00d1747564..a41f7d9927858 100644 --- a/tests/ui/auto-traits/assoc-ty.next.stderr +++ b/tests/ui/auto-traits/assoc-ty.next.stderr @@ -5,7 +5,7 @@ LL | auto trait Trait { | ----- auto traits cannot have associated items LL | LL | type Output; - | -----^^^^^^- help: remove these associated items + | ^^^^^^ error[E0658]: auto traits are experimental and possibly buggy --> $DIR/assoc-ty.rs:8:1 diff --git a/tests/ui/auto-traits/auto-trait-validation.fixed b/tests/ui/auto-traits/auto-trait-validation.fixed index 8a445448c8581..b24dc1cb2c3d3 100644 --- a/tests/ui/auto-traits/auto-trait-validation.fixed +++ b/tests/ui/auto-traits/auto-trait-validation.fixed @@ -11,4 +11,15 @@ auto trait LifetimeBound {} //~^ ERROR auto traits cannot have super traits or lifetime bounds [E0568] auto trait MyTrait { } //~^ ERROR auto traits cannot have associated items [E0380] +auto trait AssocTy { } +//~^ ERROR auto traits cannot have associated items [E0380] +auto trait All { + //~^ ERROR auto traits cannot have generic parameters [E0567] + +} +// We can't test both generic params and super-traits because the suggestion span overlaps. +auto trait All2 { + //~^ ERROR auto traits cannot have super traits or lifetime bounds [E0568] + +} fn main() {} diff --git a/tests/ui/auto-traits/auto-trait-validation.rs b/tests/ui/auto-traits/auto-trait-validation.rs index b5e7505d86a24..9665e5bc3932f 100644 --- a/tests/ui/auto-traits/auto-trait-validation.rs +++ b/tests/ui/auto-traits/auto-trait-validation.rs @@ -11,4 +11,19 @@ auto trait LifetimeBound : 'static {} //~^ ERROR auto traits cannot have super traits or lifetime bounds [E0568] auto trait MyTrait { fn foo() {} } //~^ ERROR auto traits cannot have associated items [E0380] +auto trait AssocTy { type Bar; } +//~^ ERROR auto traits cannot have associated items [E0380] +auto trait All<'a, T> { + //~^ ERROR auto traits cannot have generic parameters [E0567] + type Bar; + //~^ ERROR auto traits cannot have associated items [E0380] + fn foo() {} +} +// We can't test both generic params and super-traits because the suggestion span overlaps. +auto trait All2: Copy + 'static { + //~^ ERROR auto traits cannot have super traits or lifetime bounds [E0568] + type Bar; + //~^ ERROR auto traits cannot have associated items [E0380] + fn foo() {} +} fn main() {} diff --git a/tests/ui/auto-traits/auto-trait-validation.stderr b/tests/ui/auto-traits/auto-trait-validation.stderr index a6e5ac54869d2..60757db6d1ed2 100644 --- a/tests/ui/auto-traits/auto-trait-validation.stderr +++ b/tests/ui/auto-traits/auto-trait-validation.stderr @@ -2,23 +2,23 @@ error[E0567]: auto traits cannot have generic parameters --> $DIR/auto-trait-validation.rs:6:19 | LL | auto trait Generic {} - | -------^^^ help: remove the parameters + | -------^^^ | | | auto trait cannot have generic parameters error[E0568]: auto traits cannot have super traits or lifetime bounds - --> $DIR/auto-trait-validation.rs:8:17 + --> $DIR/auto-trait-validation.rs:8:20 | LL | auto trait Bound : Copy {} - | -----^^^^^^^ help: remove the super traits or lifetime bounds + | ----- ^^^^ | | | auto traits cannot have super traits or lifetime bounds error[E0568]: auto traits cannot have super traits or lifetime bounds - --> $DIR/auto-trait-validation.rs:10:25 + --> $DIR/auto-trait-validation.rs:10:28 | LL | auto trait LifetimeBound : 'static {} - | -------------^^^^^^^^^^ help: remove the super traits or lifetime bounds + | ------------- ^^^^^^^ | | | auto traits cannot have super traits or lifetime bounds @@ -26,12 +26,59 @@ error[E0380]: auto traits cannot have associated items --> $DIR/auto-trait-validation.rs:12:25 | LL | auto trait MyTrait { fn foo() {} } - | ------- ---^^^----- - | | | - | | help: remove these associated items + | ------- ^^^ + | | + | auto traits cannot have associated items + +error[E0380]: auto traits cannot have associated items + --> $DIR/auto-trait-validation.rs:14:27 + | +LL | auto trait AssocTy { type Bar; } + | ------- ^^^ + | | | auto traits cannot have associated items -error: aborting due to 4 previous errors +error[E0567]: auto traits cannot have generic parameters + --> $DIR/auto-trait-validation.rs:16:15 + | +LL | auto trait All<'a, T> { + | ---^^^^^^^ + | | + | auto trait cannot have generic parameters + +error[E0380]: auto traits cannot have associated items + --> $DIR/auto-trait-validation.rs:18:10 + | +LL | auto trait All<'a, T> { + | --- auto traits cannot have associated items +LL | +LL | type Bar; + | ^^^ +LL | +LL | fn foo() {} + | ^^^ + +error[E0568]: auto traits cannot have super traits or lifetime bounds + --> $DIR/auto-trait-validation.rs:23:18 + | +LL | auto trait All2: Copy + 'static { + | ---- ^^^^ ^^^^^^^ + | | + | auto traits cannot have super traits or lifetime bounds + +error[E0380]: auto traits cannot have associated items + --> $DIR/auto-trait-validation.rs:25:10 + | +LL | auto trait All2: Copy + 'static { + | ---- auto traits cannot have associated items +LL | +LL | type Bar; + | ^^^ +LL | +LL | fn foo() {} + | ^^^ + +error: aborting due to 9 previous errors Some errors have detailed explanations: E0380, E0567, E0568. For more information about an error, try `rustc --explain E0380`. diff --git a/tests/ui/auto-traits/bad-generics-on-dyn.stderr b/tests/ui/auto-traits/bad-generics-on-dyn.stderr index 06c7cbcd76da6..a6977c2037e7f 100644 --- a/tests/ui/auto-traits/bad-generics-on-dyn.stderr +++ b/tests/ui/auto-traits/bad-generics-on-dyn.stderr @@ -2,7 +2,7 @@ error[E0567]: auto traits cannot have generic parameters --> $DIR/bad-generics-on-dyn.rs:3:18 | LL | auto trait Trait1<'a> {} - | ------^^^^ help: remove the parameters + | ------^^^^ | | | auto trait cannot have generic parameters diff --git a/tests/ui/auto-traits/has-arguments.stderr b/tests/ui/auto-traits/has-arguments.stderr index b8a680e6a5cad..5228b6d2d1ac8 100644 --- a/tests/ui/auto-traits/has-arguments.stderr +++ b/tests/ui/auto-traits/has-arguments.stderr @@ -2,7 +2,7 @@ error[E0567]: auto traits cannot have generic parameters --> $DIR/has-arguments.rs:3:18 | LL | auto trait Trait1<'outer> {} - | ------^^^^^^^^ help: remove the parameters + | ------^^^^^^^^ | | | auto trait cannot have generic parameters diff --git a/tests/ui/auto-traits/issue-117789.stderr b/tests/ui/auto-traits/issue-117789.stderr index 99efb21341758..1e047c7d2e07b 100644 --- a/tests/ui/auto-traits/issue-117789.stderr +++ b/tests/ui/auto-traits/issue-117789.stderr @@ -2,7 +2,7 @@ error[E0567]: auto traits cannot have generic parameters --> $DIR/issue-117789.rs:1:17 | LL | auto trait Trait

{} - | -----^^^ help: remove the parameters + | -----^^^ | | | auto trait cannot have generic parameters diff --git a/tests/ui/auto-traits/issue-23080-2.current.stderr b/tests/ui/auto-traits/issue-23080-2.current.stderr index 62c7b37041fea..3af97f57d484a 100644 --- a/tests/ui/auto-traits/issue-23080-2.current.stderr +++ b/tests/ui/auto-traits/issue-23080-2.current.stderr @@ -4,7 +4,7 @@ error[E0380]: auto traits cannot have associated items LL | unsafe auto trait Trait { | ----- auto traits cannot have associated items LL | type Output; - | -----^^^^^^- help: remove these associated items + | ^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/auto-traits/issue-23080-2.next.stderr b/tests/ui/auto-traits/issue-23080-2.next.stderr index 62c7b37041fea..3af97f57d484a 100644 --- a/tests/ui/auto-traits/issue-23080-2.next.stderr +++ b/tests/ui/auto-traits/issue-23080-2.next.stderr @@ -4,7 +4,7 @@ error[E0380]: auto traits cannot have associated items LL | unsafe auto trait Trait { | ----- auto traits cannot have associated items LL | type Output; - | -----^^^^^^- help: remove these associated items + | ^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/auto-traits/issue-23080.stderr b/tests/ui/auto-traits/issue-23080.stderr index 5cea45060c824..02a7551910291 100644 --- a/tests/ui/auto-traits/issue-23080.stderr +++ b/tests/ui/auto-traits/issue-23080.stderr @@ -1,13 +1,10 @@ error[E0380]: auto traits cannot have associated items --> $DIR/issue-23080.rs:5:8 | -LL | unsafe auto trait Trait { - | ----- auto traits cannot have associated items -LL | fn method(&self) { - | _____- ^^^^^^ -LL | | println!("Hello"); -LL | | } - | |_____- help: remove these associated items +LL | unsafe auto trait Trait { + | ----- auto traits cannot have associated items +LL | fn method(&self) { + | ^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/auto-traits/issue-84075.stderr b/tests/ui/auto-traits/issue-84075.stderr index 943d521ce9e27..4edf2ecdf06d3 100644 --- a/tests/ui/auto-traits/issue-84075.stderr +++ b/tests/ui/auto-traits/issue-84075.stderr @@ -2,7 +2,7 @@ error[E0568]: auto traits cannot have super traits or lifetime bounds --> $DIR/issue-84075.rs:5:18 | LL | auto trait Magic where Self: Copy {} - | ----- ^^^^^^^^^^^^^^^^ help: remove the super traits or lifetime bounds + | ----- ^^^^^^^^^^^^^^^^ | | | auto traits cannot have super traits or lifetime bounds diff --git a/tests/ui/auto-traits/typeck-auto-trait-no-supertraits-2.stderr b/tests/ui/auto-traits/typeck-auto-trait-no-supertraits-2.stderr index 27e38ce06a435..bc17fefc944da 100644 --- a/tests/ui/auto-traits/typeck-auto-trait-no-supertraits-2.stderr +++ b/tests/ui/auto-traits/typeck-auto-trait-no-supertraits-2.stderr @@ -1,8 +1,8 @@ error[E0568]: auto traits cannot have super traits or lifetime bounds - --> $DIR/typeck-auto-trait-no-supertraits-2.rs:4:17 + --> $DIR/typeck-auto-trait-no-supertraits-2.rs:4:20 | LL | auto trait Magic : Sized where Option : Magic {} - | -----^^^^^^^^ help: remove the super traits or lifetime bounds + | ----- ^^^^^ | | | auto traits cannot have super traits or lifetime bounds @@ -10,7 +10,7 @@ error[E0568]: auto traits cannot have super traits or lifetime bounds --> $DIR/typeck-auto-trait-no-supertraits-2.rs:4:26 | LL | auto trait Magic : Sized where Option : Magic {} - | ----- ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove the super traits or lifetime bounds + | ----- ^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | auto traits cannot have super traits or lifetime bounds diff --git a/tests/ui/auto-traits/typeck-auto-trait-no-supertraits.stderr b/tests/ui/auto-traits/typeck-auto-trait-no-supertraits.stderr index 23aae13639c77..bc9791a5799c8 100644 --- a/tests/ui/auto-traits/typeck-auto-trait-no-supertraits.stderr +++ b/tests/ui/auto-traits/typeck-auto-trait-no-supertraits.stderr @@ -1,8 +1,8 @@ error[E0568]: auto traits cannot have super traits or lifetime bounds - --> $DIR/typeck-auto-trait-no-supertraits.rs:28:17 + --> $DIR/typeck-auto-trait-no-supertraits.rs:28:19 | LL | auto trait Magic: Copy {} - | -----^^^^^^ help: remove the super traits or lifetime bounds + | ----- ^^^^ | | | auto traits cannot have super traits or lifetime bounds diff --git a/tests/ui/methods/issues/issue-105732.stderr b/tests/ui/methods/issues/issue-105732.stderr index 6244f983550ee..93ce695f27b84 100644 --- a/tests/ui/methods/issues/issue-105732.stderr +++ b/tests/ui/methods/issues/issue-105732.stderr @@ -4,7 +4,7 @@ error[E0380]: auto traits cannot have associated items LL | auto trait Foo { | --- auto traits cannot have associated items LL | fn g(&self); - | ---^-------- help: remove these associated items + | ^ error[E0599]: no method named `g` found for reference `&Self` in the current scope --> $DIR/issue-105732.rs:10:14 diff --git a/tests/ui/traits/inductive-overflow/supertrait-auto-trait.stderr b/tests/ui/traits/inductive-overflow/supertrait-auto-trait.stderr index 3a3b99f6c5b10..45602d676b31f 100644 --- a/tests/ui/traits/inductive-overflow/supertrait-auto-trait.stderr +++ b/tests/ui/traits/inductive-overflow/supertrait-auto-trait.stderr @@ -1,8 +1,8 @@ error[E0568]: auto traits cannot have super traits or lifetime bounds - --> $DIR/supertrait-auto-trait.rs:8:17 + --> $DIR/supertrait-auto-trait.rs:8:19 | LL | auto trait Magic: Copy {} - | -----^^^^^^ help: remove the super traits or lifetime bounds + | ----- ^^^^ | | | auto traits cannot have super traits or lifetime bounds From a573fd958eee4b4ec76bdaa3dcacf1ab3c670d45 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 4 Aug 2025 16:24:41 +0000 Subject: [PATCH 23/30] Don't actually pass BB to check_call_dest --- compiler/rustc_borrowck/src/type_check/mod.rs | 114 +++++++++--------- 1 file changed, 54 insertions(+), 60 deletions(-) diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index 91973f33bd320..148d0de3bab28 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -769,9 +769,13 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { } TerminatorKind::Call { func, args, .. } | TerminatorKind::TailCall { func, args, .. } => { - let call_source = match term.kind { - TerminatorKind::Call { call_source, .. } => call_source, - TerminatorKind::TailCall { .. } => CallSource::Normal, + let (call_source, destination, is_diverging) = match term.kind { + TerminatorKind::Call { call_source, destination, target, .. } => { + (call_source, destination, target.is_none()) + } + TerminatorKind::TailCall { .. } => { + (CallSource::Normal, RETURN_PLACE.into(), false) + } _ => unreachable!(), }; @@ -845,13 +849,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ); } - let (destination, target) = - if let TerminatorKind::Call { destination, target, .. } = term.kind { - (destination, target) - } else { - (RETURN_PLACE.into(), Some(BasicBlock::ZERO)) - }; - self.check_call_dest(term, &sig, destination, target, term_location); + self.check_call_dest(term, &sig, destination, is_diverging, term_location); // The ordinary liveness rules will ensure that all // regions in the type of the callee are live here. We @@ -1878,65 +1876,61 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { term: &Terminator<'tcx>, sig: &ty::FnSig<'tcx>, destination: Place<'tcx>, - target: Option, + is_diverging: bool, term_location: Location, ) { let tcx = self.tcx(); - match target { - Some(_) => { - let dest_ty = destination.ty(self.body, tcx).ty; - let dest_ty = self.normalize(dest_ty, term_location); - let category = match destination.as_local() { - Some(RETURN_PLACE) => { - if let DefiningTy::Const(def_id, _) | DefiningTy::InlineConst(def_id, _) = - self.universal_regions.defining_ty - { - if tcx.is_static(def_id) { - ConstraintCategory::UseAsStatic - } else { - ConstraintCategory::UseAsConst - } + if is_diverging { + // The signature in this call can reference region variables, + // so erase them before calling a query. + let output_ty = self.tcx().erase_regions(sig.output()); + if !output_ty + .is_privately_uninhabited(self.tcx(), self.infcx.typing_env(self.infcx.param_env)) + { + span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig); + } + } else { + let dest_ty = destination.ty(self.body, tcx).ty; + let dest_ty = self.normalize(dest_ty, term_location); + let category = match destination.as_local() { + Some(RETURN_PLACE) => { + if let DefiningTy::Const(def_id, _) | DefiningTy::InlineConst(def_id, _) = + self.universal_regions.defining_ty + { + if tcx.is_static(def_id) { + ConstraintCategory::UseAsStatic } else { - ConstraintCategory::Return(ReturnConstraint::Normal) + ConstraintCategory::UseAsConst } + } else { + ConstraintCategory::Return(ReturnConstraint::Normal) } - Some(l) if !self.body.local_decls[l].is_user_variable() => { - ConstraintCategory::Boring - } - // The return type of a call is interesting for diagnostics. - _ => ConstraintCategory::Assignment, - }; - - let locations = term_location.to_locations(); - - if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) { - span_mirbug!( - self, - term, - "call dest mismatch ({:?} <- {:?}): {:?}", - dest_ty, - sig.output(), - terr - ); } - - // When `unsized_fn_params` is not enabled, - // this check is done at `check_local`. - if self.unsized_feature_enabled() { - let span = term.source_info.span; - self.ensure_place_sized(dest_ty, span); + Some(l) if !self.body.local_decls[l].is_user_variable() => { + ConstraintCategory::Boring } + // The return type of a call is interesting for diagnostics. + _ => ConstraintCategory::Assignment, + }; + + let locations = term_location.to_locations(); + + if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) { + span_mirbug!( + self, + term, + "call dest mismatch ({:?} <- {:?}): {:?}", + dest_ty, + sig.output(), + terr + ); } - None => { - // The signature in this call can reference region variables, - // so erase them before calling a query. - let output_ty = self.tcx().erase_regions(sig.output()); - if !output_ty.is_privately_uninhabited( - self.tcx(), - self.infcx.typing_env(self.infcx.param_env), - ) { - span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig); - } + + // When `unsized_fn_params` is not enabled, + // this check is done at `check_local`. + if self.unsized_feature_enabled() { + let span = term.source_info.span; + self.ensure_place_sized(dest_ty, span); } } } From d2e3ea9ba72a74e5de383e440239f768411b2315 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= Date: Wed, 30 Jul 2025 00:36:07 +0200 Subject: [PATCH 24/30] windows-gnullvm: include `libunwind.dll` in dist --- src/bootstrap/src/core/build_steps/dist.rs | 31 +++++++++++++++++----- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index 88b668e1936e8..acc278ba8bf86 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -278,14 +278,31 @@ fn runtime_dll_dist(rust_root: &Path, target: TargetSelection, builder: &Builder return; } - let (bin_path, _) = get_cc_search_dirs(target, builder); - - let mut rustc_dlls = vec!["libwinpthread-1.dll"]; - if target.starts_with("i686-") { - rustc_dlls.push("libgcc_s_dw2-1.dll"); + let (bin_path, libs_path) = get_cc_search_dirs(target, builder); + + let mut rustc_dlls = vec![]; + // windows-gnu and windows-gnullvm require different runtime libs + if target.ends_with("windows-gnu") { + rustc_dlls.push("libwinpthread-1.dll"); + if target.starts_with("i686-") { + rustc_dlls.push("libgcc_s_dw2-1.dll"); + } else { + rustc_dlls.push("libgcc_s_seh-1.dll"); + } + } else if target.ends_with("windows-gnullvm") { + rustc_dlls.push("libunwind.dll"); } else { - rustc_dlls.push("libgcc_s_seh-1.dll"); + panic!("Vendoring of runtime DLLs for `{target}` is not supported`"); } + // FIXME(#144656): Remove this whole `let ...` + let bin_path = if target.ends_with("windows-gnullvm") && builder.host_target != target { + bin_path + .into_iter() + .chain(libs_path.iter().map(|path| path.with_file_name("bin"))) + .collect() + } else { + bin_path + }; let rustc_dlls = find_files(&rustc_dlls, &bin_path); // Copy runtime dlls next to rustc.exe @@ -408,7 +425,7 @@ impl Step for Rustc { // anything requiring us to distribute a license, but it's likely the // install will *also* include the rust-mingw package, which also needs // licenses, so to be safe we just include it here in all MinGW packages. - if host.ends_with("pc-windows-gnu") && builder.config.dist_include_mingw_linker { + if host.contains("pc-windows-gnu") && builder.config.dist_include_mingw_linker { runtime_dll_dist(tarball.image_dir(), host, builder); tarball.add_dir(builder.src.join("src/etc/third-party"), "share/doc"); } From 81081f45136638b8b018b550222afb11196b2c25 Mon Sep 17 00:00:00 2001 From: binarycat Date: Mon, 4 Aug 2025 14:21:00 -0500 Subject: [PATCH 25/30] compiletest: add hint for when a ui test produces no errors --- src/tools/compiletest/src/runtest.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 35670ba89e997..84c6df5c74461 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -356,7 +356,7 @@ impl<'test> TestCx<'test> { if proc_res.status.success() { let err = &format!("{} test did not emit an error", self.config.mode); let extra_note = (self.config.mode == crate::common::TestMode::Ui) - .then_some("note: by default, ui tests are expected not to compile"); + .then_some("note: by default, ui tests are expected not to compile.\nhint: use check-pass, build-pass, or run-pass directive to change this behavior."); self.fatal_proc_rec_general(err, extra_note, proc_res, || ()); } From 7196d8cd661b875401126a81641d2effc40b3d85 Mon Sep 17 00:00:00 2001 From: Oneirical Date: Sun, 13 Jul 2025 16:25:27 -0400 Subject: [PATCH 26/30] Rehome tests/ui/issues/ tests [3/?] --- .../extern-c-two-doubles-x86_64-5754.rs} | 2 +- ...fixed-size-arrays-zero-size-types-8898.rs} | 1 + .../trait-associated-const-usage-43483.rs} | 1 + ...cursive-associated-type-overflow-21946.rs} | 1 + ...ive-associated-type-overflow-21946.stderr} | 2 +- .../mismatched-pointer-type-in-self-7061.rs} | 1 + ...smatched-pointer-type-in-self-7061.stderr} | 2 +- .../region-checker-map-closure-13665.rs} | 1 + ...asability-violation-with-closure-21600.rs} | 1 + ...ility-violation-with-closure-21600.stderr} | 4 ++-- .../const-pattern-rewrite-error-32086.rs} | 1 + .../const-pattern-rewrite-error-32086.stderr} | 4 ++-- .../auxiliary/aux-5521.rs} | 0 .../cross-crate-map-usage-5521.rs} | 7 +++--- .../typo-suggestion-improvement-46332.rs} | 1 + .../typo-suggestion-improvement-46332.stderr} | 2 +- .../destructor-run-for-let-ignore-6892.rs} | 1 + .../drop-count-assertion-16151.rs} | 1 + ...-compatible-trait-implementation-20939.rs} | 1 + ...patible-trait-implementation-20939.stderr} | 2 +- ...unused-type-parameter-regression-36075.rs} | 1 + tests/ui/issues/issue-9188.rs | 11 --------- .../fold-iterator-error-23966.rs} | 1 + .../fold-iterator-error-23966.stderr} | 2 +- .../lifetime-inference-miss-15735.rs} | 1 + .../infinite-loop-simplify-cfg-75704.rs} | 1 + ...ttern-if-variant-not-imported-19100.fixed} | 1 + ...-pattern-if-variant-not-imported-19100.rs} | 1 + ...tern-if-variant-not-imported-19100.stderr} | 4 ++-- ...-method-resolution-over-inherent-22684.rs} | 1 + ...hod-resolution-over-inherent-22684.stderr} | 2 +- .../float-integer-subtraction-error-24352.rs} | 1 + ...at-integer-subtraction-error-24352.stderr} | 2 +- .../for-loop-in-vec-type-mismatchrs-50585.rs} | 1 + ...-loop-in-vec-type-mismatchrs-50585.stderr} | 2 +- ...rts-with-stringify-type-mismatch-48364.rs} | 1 + ...with-stringify-type-mismatch-48364.stderr} | 2 +- .../circular-module-imports-32797.rs} | 1 + .../matching-partially-moved-value-17385.rs} | 1 + ...tching-partially-moved-value-17385.stderr} | 8 +++---- .../f32-literal-rounding-32805.rs} | 1 + .../private-field-access-violation-3763.rs} | 1 + ...rivate-field-access-violation-3763.stderr} | 10 ++++---- .../cannot-find-value-in-scope-22811.rs} | 1 + .../cannot-find-value-in-scope-22811.stderr} | 2 +- .../unresolved-module-error-33293.rs} | 1 + .../unresolved-module-error-33293.stderr} | 2 +- .../tuple-struct-field-naming-47073.rs} | 1 + .../tuple-struct-field-naming-47073.stderr} | 4 ++-- .../auxiliary/aux-9188.rs} | 0 ...same-symbol-name-for-inner-statics-9188.rs | 11 +++++++++ ...it-selection-overflow-prevention-72839.rs} | 1 + ...election-overflow-prevention-72839.stderr} | 2 +- ...trait-object-lifetime-conversion-47638.rs} | 1 + ...-impl-overflow-with-where-clause-20413.rs} | 1 + ...l-overflow-with-where-clause-20413.stderr} | 24 +++++++++---------- ...patible-types-with-question-mark-51632.rs} | 1 + ...ble-types-with-question-mark-51632.stderr} | 2 +- 58 files changed, 89 insertions(+), 58 deletions(-) rename tests/ui/{issues/issue-5754.rs => abi/extern-c-two-doubles-x86_64-5754.rs} (81%) rename tests/ui/{issues/issue-8898.rs => array-slice-vec/fixed-size-arrays-zero-size-types-8898.rs} (91%) rename tests/ui/{issues/issue-43483.rs => associated-consts/trait-associated-const-usage-43483.rs} (79%) rename tests/ui/{issues/issue-21946.rs => associated-types/recursive-associated-type-overflow-21946.rs} (80%) rename tests/ui/{issues/issue-21946.stderr => associated-types/recursive-associated-type-overflow-21946.stderr} (82%) rename tests/ui/{issues/issue-7061.rs => borrowck/mismatched-pointer-type-in-self-7061.rs} (85%) rename tests/ui/{issues/issue-7061.stderr => borrowck/mismatched-pointer-type-in-self-7061.stderr} (90%) rename tests/ui/{issues/issue-13665.rs => borrowck/region-checker-map-closure-13665.rs} (86%) rename tests/ui/{issues/issue-21600.rs => closures/aliasability-violation-with-closure-21600.rs} (89%) rename tests/ui/{issues/issue-21600.stderr => closures/aliasability-violation-with-closure-21600.stderr} (89%) rename tests/ui/{issues/issue-32086.rs => consts/const-pattern-rewrite-error-32086.rs} (82%) rename tests/ui/{issues/issue-32086.stderr => consts/const-pattern-rewrite-error-32086.stderr} (85%) rename tests/ui/{issues/auxiliary/issue-5521.rs => cross-crate/auxiliary/aux-5521.rs} (100%) rename tests/ui/{issues/issue-5521.rs => cross-crate/cross-crate-map-usage-5521.rs} (59%) rename tests/ui/{issues/issue-46332.rs => did_you_mean/typo-suggestion-improvement-46332.rs} (84%) rename tests/ui/{issues/issue-46332.stderr => did_you_mean/typo-suggestion-improvement-46332.stderr} (88%) rename tests/ui/{issues/issue-6892.rs => drop/destructor-run-for-let-ignore-6892.rs} (96%) rename tests/ui/{issues/issue-16151.rs => drop/drop-count-assertion-16151.rs} (92%) rename tests/ui/{issues/issue-20939.rs => dyn-compatibility/dyn-compatible-trait-implementation-20939.rs} (74%) rename tests/ui/{issues/issue-20939.stderr => dyn-compatibility/dyn-compatible-trait-implementation-20939.stderr} (84%) rename tests/ui/{issues/issue-36075.rs => generics/unused-type-parameter-regression-36075.rs} (81%) delete mode 100644 tests/ui/issues/issue-9188.rs rename tests/ui/{issues/issue-23966.rs => iterators/fold-iterator-error-23966.rs} (58%) rename tests/ui/{issues/issue-23966.stderr => iterators/fold-iterator-error-23966.stderr} (92%) rename tests/ui/{issues/issue-15735.rs => lifetimes/lifetime-inference-miss-15735.rs} (81%) rename tests/ui/{issues/issue-75704.rs => loops/infinite-loop-simplify-cfg-75704.rs} (71%) rename tests/ui/{issues/issue-19100.fixed => match/unreachable-pattern-if-variant-not-imported-19100.fixed} (91%) rename tests/ui/{issues/issue-19100.rs => match/unreachable-pattern-if-variant-not-imported-19100.rs} (91%) rename tests/ui/{issues/issue-19100.stderr => match/unreachable-pattern-if-variant-not-imported-19100.stderr} (80%) rename tests/ui/{issues/issue-22684.rs => methods/trait-method-resolution-over-inherent-22684.rs} (87%) rename tests/ui/{issues/issue-22684.stderr => methods/trait-method-resolution-over-inherent-22684.stderr} (82%) rename tests/ui/{issues/issue-24352.rs => mismatched_types/float-integer-subtraction-error-24352.rs} (55%) rename tests/ui/{issues/issue-24352.stderr => mismatched_types/float-integer-subtraction-error-24352.stderr} (92%) rename tests/ui/{issues/issue-50585.rs => mismatched_types/for-loop-in-vec-type-mismatchrs-50585.rs} (63%) rename tests/ui/{issues/issue-50585.stderr => mismatched_types/for-loop-in-vec-type-mismatchrs-50585.stderr} (89%) rename tests/ui/{issues/issue-48364.rs => mismatched_types/starts-with-stringify-type-mismatch-48364.rs} (67%) rename tests/ui/{issues/issue-48364.stderr => mismatched_types/starts-with-stringify-type-mismatch-48364.stderr} (88%) rename tests/ui/{issues/issue-32797.rs => modules/circular-module-imports-32797.rs} (74%) rename tests/ui/{issues/issue-17385.rs => moves/matching-partially-moved-value-17385.rs} (90%) rename tests/ui/{issues/issue-17385.stderr => moves/matching-partially-moved-value-17385.stderr} (83%) rename tests/ui/{issues/issue-32805.rs => numbers-arithmetic/f32-literal-rounding-32805.rs} (85%) rename tests/ui/{issues/issue-3763.rs => privacy/private-field-access-violation-3763.rs} (94%) rename tests/ui/{issues/issue-3763.stderr => privacy/private-field-access-violation-3763.stderr} (80%) rename tests/ui/{issues/issue-2281-part1.rs => resolve/cannot-find-value-in-scope-22811.rs} (64%) rename tests/ui/{issues/issue-2281-part1.stderr => resolve/cannot-find-value-in-scope-22811.stderr} (84%) rename tests/ui/{issues/issue-33293.rs => resolve/unresolved-module-error-33293.rs} (74%) rename tests/ui/{issues/issue-33293.stderr => resolve/unresolved-module-error-33293.stderr} (87%) rename tests/ui/{issues/issue-47073-zero-padded-tuple-struct-indices.rs => structs/tuple-struct-field-naming-47073.rs} (86%) rename tests/ui/{issues/issue-47073-zero-padded-tuple-struct-indices.stderr => structs/tuple-struct-field-naming-47073.stderr} (81%) rename tests/ui/{issues/auxiliary/issue-9188.rs => symbol-names/auxiliary/aux-9188.rs} (100%) create mode 100644 tests/ui/symbol-names/same-symbol-name-for-inner-statics-9188.rs rename tests/ui/{issues/issue-72839-error-overflow.rs => trait-bounds/trait-selection-overflow-prevention-72839.rs} (89%) rename tests/ui/{issues/issue-72839-error-overflow.stderr => trait-bounds/trait-selection-overflow-prevention-72839.stderr} (80%) rename tests/ui/{issues/issue-47638.rs => trait-objects/trait-object-lifetime-conversion-47638.rs} (78%) rename tests/ui/{issues/issue-20413.rs => traits/trait-impl-overflow-with-where-clause-20413.rs} (93%) rename tests/ui/{issues/issue-20413.stderr => traits/trait-impl-overflow-with-where-clause-20413.stderr} (92%) rename tests/ui/{issues/issue-51632-try-desugar-incompatible-types.rs => try-trait/incompatible-types-with-question-mark-51632.rs} (81%) rename tests/ui/{issues/issue-51632-try-desugar-incompatible-types.stderr => try-trait/incompatible-types-with-question-mark-51632.stderr} (92%) diff --git a/tests/ui/issues/issue-5754.rs b/tests/ui/abi/extern-c-two-doubles-x86_64-5754.rs similarity index 81% rename from tests/ui/issues/issue-5754.rs rename to tests/ui/abi/extern-c-two-doubles-x86_64-5754.rs index 0aa0988295948..7f44ef9c68535 100644 --- a/tests/ui/issues/issue-5754.rs +++ b/tests/ui/abi/extern-c-two-doubles-x86_64-5754.rs @@ -1,8 +1,8 @@ +// https://github.com/rust-lang/rust/issues/5754 //@ build-pass #![allow(dead_code)] #![allow(improper_ctypes)] - struct TwoDoubles { r: f64, i: f64 diff --git a/tests/ui/issues/issue-8898.rs b/tests/ui/array-slice-vec/fixed-size-arrays-zero-size-types-8898.rs similarity index 91% rename from tests/ui/issues/issue-8898.rs rename to tests/ui/array-slice-vec/fixed-size-arrays-zero-size-types-8898.rs index 4447704f059c2..fe627b00f53bc 100644 --- a/tests/ui/issues/issue-8898.rs +++ b/tests/ui/array-slice-vec/fixed-size-arrays-zero-size-types-8898.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/8898 //@ run-pass fn assert_repr_eq(obj : T, expected : String) { diff --git a/tests/ui/issues/issue-43483.rs b/tests/ui/associated-consts/trait-associated-const-usage-43483.rs similarity index 79% rename from tests/ui/issues/issue-43483.rs rename to tests/ui/associated-consts/trait-associated-const-usage-43483.rs index 2c62671d0c711..c24157d45e776 100644 --- a/tests/ui/issues/issue-43483.rs +++ b/tests/ui/associated-consts/trait-associated-const-usage-43483.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/43483 //@ check-pass #![allow(dead_code)] #![allow(unused_variables)] diff --git a/tests/ui/issues/issue-21946.rs b/tests/ui/associated-types/recursive-associated-type-overflow-21946.rs similarity index 80% rename from tests/ui/issues/issue-21946.rs rename to tests/ui/associated-types/recursive-associated-type-overflow-21946.rs index d0c052cb2fd39..ba84ea1130080 100644 --- a/tests/ui/issues/issue-21946.rs +++ b/tests/ui/associated-types/recursive-associated-type-overflow-21946.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/21946 trait Foo { type A; } diff --git a/tests/ui/issues/issue-21946.stderr b/tests/ui/associated-types/recursive-associated-type-overflow-21946.stderr similarity index 82% rename from tests/ui/issues/issue-21946.stderr rename to tests/ui/associated-types/recursive-associated-type-overflow-21946.stderr index d1b4a808d2ec6..37fb0ed7eb882 100644 --- a/tests/ui/issues/issue-21946.stderr +++ b/tests/ui/associated-types/recursive-associated-type-overflow-21946.stderr @@ -1,5 +1,5 @@ error[E0275]: overflow evaluating the requirement `::A == _` - --> $DIR/issue-21946.rs:8:14 + --> $DIR/recursive-associated-type-overflow-21946.rs:9:14 | LL | type A = ::A; | ^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/issues/issue-7061.rs b/tests/ui/borrowck/mismatched-pointer-type-in-self-7061.rs similarity index 85% rename from tests/ui/issues/issue-7061.rs rename to tests/ui/borrowck/mismatched-pointer-type-in-self-7061.rs index c5d5a9d9498df..521a5ee9c37ec 100644 --- a/tests/ui/issues/issue-7061.rs +++ b/tests/ui/borrowck/mismatched-pointer-type-in-self-7061.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/7061 //@ dont-require-annotations: NOTE struct BarStruct; diff --git a/tests/ui/issues/issue-7061.stderr b/tests/ui/borrowck/mismatched-pointer-type-in-self-7061.stderr similarity index 90% rename from tests/ui/issues/issue-7061.stderr rename to tests/ui/borrowck/mismatched-pointer-type-in-self-7061.stderr index b4c0ebfbdd537..39b9072dc3031 100644 --- a/tests/ui/issues/issue-7061.stderr +++ b/tests/ui/borrowck/mismatched-pointer-type-in-self-7061.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-7061.rs:6:46 + --> $DIR/mismatched-pointer-type-in-self-7061.rs:7:46 | LL | fn foo(&'a mut self) -> Box { self } | -------------- ^^^^ expected `Box`, found `&mut BarStruct` diff --git a/tests/ui/issues/issue-13665.rs b/tests/ui/borrowck/region-checker-map-closure-13665.rs similarity index 86% rename from tests/ui/issues/issue-13665.rs rename to tests/ui/borrowck/region-checker-map-closure-13665.rs index e1d8be16f4500..72efa42fe3835 100644 --- a/tests/ui/issues/issue-13665.rs +++ b/tests/ui/borrowck/region-checker-map-closure-13665.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/13665 //@ run-pass fn foo<'r>() { diff --git a/tests/ui/issues/issue-21600.rs b/tests/ui/closures/aliasability-violation-with-closure-21600.rs similarity index 89% rename from tests/ui/issues/issue-21600.rs rename to tests/ui/closures/aliasability-violation-with-closure-21600.rs index 2e22e5e6fa2e0..d4c658319abb4 100644 --- a/tests/ui/issues/issue-21600.rs +++ b/tests/ui/closures/aliasability-violation-with-closure-21600.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/21600 fn call_it(f: F) where F: Fn() { f(); } struct A; diff --git a/tests/ui/issues/issue-21600.stderr b/tests/ui/closures/aliasability-violation-with-closure-21600.stderr similarity index 89% rename from tests/ui/issues/issue-21600.stderr rename to tests/ui/closures/aliasability-violation-with-closure-21600.stderr index f79059344245c..2d2397a2141d9 100644 --- a/tests/ui/issues/issue-21600.stderr +++ b/tests/ui/closures/aliasability-violation-with-closure-21600.stderr @@ -1,5 +1,5 @@ error[E0596]: cannot borrow `x` as mutable, as it is a captured variable in a `Fn` closure - --> $DIR/issue-21600.rs:14:20 + --> $DIR/aliasability-violation-with-closure-21600.rs:15:20 | LL | fn call_it(f: F) where F: Fn() { f(); } | - change this to accept `FnMut` instead of `Fn` @@ -11,7 +11,7 @@ LL | call_it(|| x.gen_mut()); | expects `Fn` instead of `FnMut` error[E0596]: cannot borrow `x` as mutable, as it is a captured variable in a `Fn` closure - --> $DIR/issue-21600.rs:14:17 + --> $DIR/aliasability-violation-with-closure-21600.rs:15:17 | LL | fn call_it(f: F) where F: Fn() { f(); } | - change this to accept `FnMut` instead of `Fn` diff --git a/tests/ui/issues/issue-32086.rs b/tests/ui/consts/const-pattern-rewrite-error-32086.rs similarity index 82% rename from tests/ui/issues/issue-32086.rs rename to tests/ui/consts/const-pattern-rewrite-error-32086.rs index d595d1dd7e6d1..d35dfe576879e 100644 --- a/tests/ui/issues/issue-32086.rs +++ b/tests/ui/consts/const-pattern-rewrite-error-32086.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/32086 struct S(u8); const C: S = S(10); diff --git a/tests/ui/issues/issue-32086.stderr b/tests/ui/consts/const-pattern-rewrite-error-32086.stderr similarity index 85% rename from tests/ui/issues/issue-32086.stderr rename to tests/ui/consts/const-pattern-rewrite-error-32086.stderr index e566dea89088d..47616b0663214 100644 --- a/tests/ui/issues/issue-32086.stderr +++ b/tests/ui/consts/const-pattern-rewrite-error-32086.stderr @@ -1,5 +1,5 @@ error[E0532]: expected tuple struct or tuple variant, found constant `C` - --> $DIR/issue-32086.rs:5:9 + --> $DIR/const-pattern-rewrite-error-32086.rs:6:9 | LL | struct S(u8); | ------------- similarly named tuple struct `S` defined here @@ -8,7 +8,7 @@ LL | let C(a) = S(11); | ^ help: a tuple struct with a similar name exists: `S` error[E0532]: expected tuple struct or tuple variant, found constant `C` - --> $DIR/issue-32086.rs:6:9 + --> $DIR/const-pattern-rewrite-error-32086.rs:7:9 | LL | struct S(u8); | ------------- similarly named tuple struct `S` defined here diff --git a/tests/ui/issues/auxiliary/issue-5521.rs b/tests/ui/cross-crate/auxiliary/aux-5521.rs similarity index 100% rename from tests/ui/issues/auxiliary/issue-5521.rs rename to tests/ui/cross-crate/auxiliary/aux-5521.rs diff --git a/tests/ui/issues/issue-5521.rs b/tests/ui/cross-crate/cross-crate-map-usage-5521.rs similarity index 59% rename from tests/ui/issues/issue-5521.rs rename to tests/ui/cross-crate/cross-crate-map-usage-5521.rs index 45896ae81284d..ffce846be2c13 100644 --- a/tests/ui/issues/issue-5521.rs +++ b/tests/ui/cross-crate/cross-crate-map-usage-5521.rs @@ -1,10 +1,9 @@ +// https://github.com/rust-lang/rust/issues/5521 //@ run-pass #![allow(dead_code)] -//@ aux-build:issue-5521.rs +//@ aux-build:aux-5521.rs - - -extern crate issue_5521 as foo; +extern crate aux_5521 as foo; fn bar(a: foo::map) { if false { diff --git a/tests/ui/issues/issue-46332.rs b/tests/ui/did_you_mean/typo-suggestion-improvement-46332.rs similarity index 84% rename from tests/ui/issues/issue-46332.rs rename to tests/ui/did_you_mean/typo-suggestion-improvement-46332.rs index bed74e3138a66..3dd686a66b0e7 100644 --- a/tests/ui/issues/issue-46332.rs +++ b/tests/ui/did_you_mean/typo-suggestion-improvement-46332.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/46332 // Original Levenshtein distance for both of this is 1. We improved accuracy with // additional case insensitive comparison. diff --git a/tests/ui/issues/issue-46332.stderr b/tests/ui/did_you_mean/typo-suggestion-improvement-46332.stderr similarity index 88% rename from tests/ui/issues/issue-46332.stderr rename to tests/ui/did_you_mean/typo-suggestion-improvement-46332.stderr index 8c0c1dfa6ee86..502f81518785c 100644 --- a/tests/ui/issues/issue-46332.stderr +++ b/tests/ui/did_you_mean/typo-suggestion-improvement-46332.stderr @@ -1,5 +1,5 @@ error[E0422]: cannot find struct, variant or union type `TyUInt` in this scope - --> $DIR/issue-46332.rs:9:5 + --> $DIR/typo-suggestion-improvement-46332.rs:10:5 | LL | struct TyUint {} | ------------- similarly named struct `TyUint` defined here diff --git a/tests/ui/issues/issue-6892.rs b/tests/ui/drop/destructor-run-for-let-ignore-6892.rs similarity index 96% rename from tests/ui/issues/issue-6892.rs rename to tests/ui/drop/destructor-run-for-let-ignore-6892.rs index 7d99aef4ac5c1..0fcf133c2b188 100644 --- a/tests/ui/issues/issue-6892.rs +++ b/tests/ui/drop/destructor-run-for-let-ignore-6892.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/6892 //@ run-pass #![allow(dead_code)] // Ensures that destructors are run for expressions of the form "let _ = e;" diff --git a/tests/ui/issues/issue-16151.rs b/tests/ui/drop/drop-count-assertion-16151.rs similarity index 92% rename from tests/ui/issues/issue-16151.rs rename to tests/ui/drop/drop-count-assertion-16151.rs index b18108e0a8ad8..ede6bc23e733a 100644 --- a/tests/ui/issues/issue-16151.rs +++ b/tests/ui/drop/drop-count-assertion-16151.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/16151 //@ run-pass // FIXME(static_mut_refs): Do not allow `static_mut_refs` lint diff --git a/tests/ui/issues/issue-20939.rs b/tests/ui/dyn-compatibility/dyn-compatible-trait-implementation-20939.rs similarity index 74% rename from tests/ui/issues/issue-20939.rs rename to tests/ui/dyn-compatibility/dyn-compatible-trait-implementation-20939.rs index c0c222978970d..c7938b275e944 100644 --- a/tests/ui/issues/issue-20939.rs +++ b/tests/ui/dyn-compatibility/dyn-compatible-trait-implementation-20939.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/20939 trait Foo {} impl<'a> Foo for dyn Foo + 'a {} diff --git a/tests/ui/issues/issue-20939.stderr b/tests/ui/dyn-compatibility/dyn-compatible-trait-implementation-20939.stderr similarity index 84% rename from tests/ui/issues/issue-20939.stderr rename to tests/ui/dyn-compatibility/dyn-compatible-trait-implementation-20939.stderr index 00357155c8a90..196d8b6a880e2 100644 --- a/tests/ui/issues/issue-20939.stderr +++ b/tests/ui/dyn-compatibility/dyn-compatible-trait-implementation-20939.stderr @@ -1,5 +1,5 @@ error[E0371]: the object type `(dyn Foo + 'a)` automatically implements the trait `Foo` - --> $DIR/issue-20939.rs:3:1 + --> $DIR/dyn-compatible-trait-implementation-20939.rs:4:1 | LL | impl<'a> Foo for dyn Foo + 'a {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `(dyn Foo + 'a)` automatically implements trait `Foo` diff --git a/tests/ui/issues/issue-36075.rs b/tests/ui/generics/unused-type-parameter-regression-36075.rs similarity index 81% rename from tests/ui/issues/issue-36075.rs rename to tests/ui/generics/unused-type-parameter-regression-36075.rs index a563332ad78e9..4d6eb617b599a 100644 --- a/tests/ui/issues/issue-36075.rs +++ b/tests/ui/generics/unused-type-parameter-regression-36075.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/36075 //@ check-pass #![allow(dead_code)] trait DeclarationParser { diff --git a/tests/ui/issues/issue-9188.rs b/tests/ui/issues/issue-9188.rs deleted file mode 100644 index df2f90a0f16bb..0000000000000 --- a/tests/ui/issues/issue-9188.rs +++ /dev/null @@ -1,11 +0,0 @@ -//@ run-pass -//@ aux-build:issue-9188.rs - - -extern crate issue_9188; - -pub fn main() { - let a = issue_9188::bar(); - let b = issue_9188::foo::(); - assert_eq!(*a, *b); -} diff --git a/tests/ui/issues/issue-23966.rs b/tests/ui/iterators/fold-iterator-error-23966.rs similarity index 58% rename from tests/ui/issues/issue-23966.rs rename to tests/ui/iterators/fold-iterator-error-23966.rs index 5fdec28ac2cd2..970c943da0b92 100644 --- a/tests/ui/issues/issue-23966.rs +++ b/tests/ui/iterators/fold-iterator-error-23966.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/23966 fn main() { "".chars().fold(|_, _| (), ()); //~^ ERROR E0277 diff --git a/tests/ui/issues/issue-23966.stderr b/tests/ui/iterators/fold-iterator-error-23966.stderr similarity index 92% rename from tests/ui/issues/issue-23966.stderr rename to tests/ui/iterators/fold-iterator-error-23966.stderr index 3f7a4fa312f12..15249a935972a 100644 --- a/tests/ui/issues/issue-23966.stderr +++ b/tests/ui/iterators/fold-iterator-error-23966.stderr @@ -1,5 +1,5 @@ error[E0277]: expected a `FnMut(_, char)` closure, found `()` - --> $DIR/issue-23966.rs:2:32 + --> $DIR/fold-iterator-error-23966.rs:3:32 | LL | "".chars().fold(|_, _| (), ()); | ---- ^^ expected an `FnMut(_, char)` closure, found `()` diff --git a/tests/ui/issues/issue-15735.rs b/tests/ui/lifetimes/lifetime-inference-miss-15735.rs similarity index 81% rename from tests/ui/issues/issue-15735.rs rename to tests/ui/lifetimes/lifetime-inference-miss-15735.rs index f5b3803f1553f..c75d59a2f4b4f 100644 --- a/tests/ui/issues/issue-15735.rs +++ b/tests/ui/lifetimes/lifetime-inference-miss-15735.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/15735 //@ check-pass #![allow(dead_code)] struct A<'a> { diff --git a/tests/ui/issues/issue-75704.rs b/tests/ui/loops/infinite-loop-simplify-cfg-75704.rs similarity index 71% rename from tests/ui/issues/issue-75704.rs rename to tests/ui/loops/infinite-loop-simplify-cfg-75704.rs index 1672bf0b4c338..8bc5fba7a6833 100644 --- a/tests/ui/issues/issue-75704.rs +++ b/tests/ui/loops/infinite-loop-simplify-cfg-75704.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/75704 // Caused an infinite loop during SimlifyCfg MIR transform previously. // //@ build-pass diff --git a/tests/ui/issues/issue-19100.fixed b/tests/ui/match/unreachable-pattern-if-variant-not-imported-19100.fixed similarity index 91% rename from tests/ui/issues/issue-19100.fixed rename to tests/ui/match/unreachable-pattern-if-variant-not-imported-19100.fixed index 1162490048cd2..40c92322519fa 100644 --- a/tests/ui/issues/issue-19100.fixed +++ b/tests/ui/match/unreachable-pattern-if-variant-not-imported-19100.fixed @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/19100 //@ run-rustfix #![allow(non_snake_case)] diff --git a/tests/ui/issues/issue-19100.rs b/tests/ui/match/unreachable-pattern-if-variant-not-imported-19100.rs similarity index 91% rename from tests/ui/issues/issue-19100.rs rename to tests/ui/match/unreachable-pattern-if-variant-not-imported-19100.rs index fefed0daa72bb..9ef6fd77b50c3 100644 --- a/tests/ui/issues/issue-19100.rs +++ b/tests/ui/match/unreachable-pattern-if-variant-not-imported-19100.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/19100 //@ run-rustfix #![allow(non_snake_case)] diff --git a/tests/ui/issues/issue-19100.stderr b/tests/ui/match/unreachable-pattern-if-variant-not-imported-19100.stderr similarity index 80% rename from tests/ui/issues/issue-19100.stderr rename to tests/ui/match/unreachable-pattern-if-variant-not-imported-19100.stderr index ebbf083b7dea8..7356a4a003b45 100644 --- a/tests/ui/issues/issue-19100.stderr +++ b/tests/ui/match/unreachable-pattern-if-variant-not-imported-19100.stderr @@ -1,5 +1,5 @@ error[E0170]: pattern binding `Bar` is named the same as one of the variants of the type `Foo` - --> $DIR/issue-19100.rs:17:1 + --> $DIR/unreachable-pattern-if-variant-not-imported-19100.rs:18:1 | LL | Bar if true | ^^^ help: to match on the variant, qualify the path: `Foo::Bar` @@ -7,7 +7,7 @@ LL | Bar if true = note: `#[deny(bindings_with_variant_name)]` on by default error[E0170]: pattern binding `Baz` is named the same as one of the variants of the type `Foo` - --> $DIR/issue-19100.rs:21:1 + --> $DIR/unreachable-pattern-if-variant-not-imported-19100.rs:22:1 | LL | Baz if false | ^^^ help: to match on the variant, qualify the path: `Foo::Baz` diff --git a/tests/ui/issues/issue-22684.rs b/tests/ui/methods/trait-method-resolution-over-inherent-22684.rs similarity index 87% rename from tests/ui/issues/issue-22684.rs rename to tests/ui/methods/trait-method-resolution-over-inherent-22684.rs index a5b042706ed1c..9f317b576e69f 100644 --- a/tests/ui/issues/issue-22684.rs +++ b/tests/ui/methods/trait-method-resolution-over-inherent-22684.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/22684 mod foo { pub struct Foo; impl Foo { diff --git a/tests/ui/issues/issue-22684.stderr b/tests/ui/methods/trait-method-resolution-over-inherent-22684.stderr similarity index 82% rename from tests/ui/issues/issue-22684.stderr rename to tests/ui/methods/trait-method-resolution-over-inherent-22684.stderr index e2ca54caeac05..0ab7701fa9e6e 100644 --- a/tests/ui/issues/issue-22684.stderr +++ b/tests/ui/methods/trait-method-resolution-over-inherent-22684.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-22684.rs:17:17 + --> $DIR/trait-method-resolution-over-inherent-22684.rs:18:17 | LL | let _: () = foo::Foo.bar(); | -- ^^^^^^^^^^^^^^ expected `()`, found `bool` diff --git a/tests/ui/issues/issue-24352.rs b/tests/ui/mismatched_types/float-integer-subtraction-error-24352.rs similarity index 55% rename from tests/ui/issues/issue-24352.rs rename to tests/ui/mismatched_types/float-integer-subtraction-error-24352.rs index 5c8246d179f9d..eb632398c62b4 100644 --- a/tests/ui/issues/issue-24352.rs +++ b/tests/ui/mismatched_types/float-integer-subtraction-error-24352.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/24352 fn main() { 1.0f64 - 1.0; 1.0f64 - 1 //~ ERROR E0277 diff --git a/tests/ui/issues/issue-24352.stderr b/tests/ui/mismatched_types/float-integer-subtraction-error-24352.stderr similarity index 92% rename from tests/ui/issues/issue-24352.stderr rename to tests/ui/mismatched_types/float-integer-subtraction-error-24352.stderr index 3e0f812b5c757..7dc1fa777fc7b 100644 --- a/tests/ui/issues/issue-24352.stderr +++ b/tests/ui/mismatched_types/float-integer-subtraction-error-24352.stderr @@ -1,5 +1,5 @@ error[E0277]: cannot subtract `{integer}` from `f64` - --> $DIR/issue-24352.rs:3:12 + --> $DIR/float-integer-subtraction-error-24352.rs:4:12 | LL | 1.0f64 - 1 | ^ no implementation for `f64 - {integer}` diff --git a/tests/ui/issues/issue-50585.rs b/tests/ui/mismatched_types/for-loop-in-vec-type-mismatchrs-50585.rs similarity index 63% rename from tests/ui/issues/issue-50585.rs rename to tests/ui/mismatched_types/for-loop-in-vec-type-mismatchrs-50585.rs index ca2ece8d53bec..4abef0bee81bd 100644 --- a/tests/ui/issues/issue-50585.rs +++ b/tests/ui/mismatched_types/for-loop-in-vec-type-mismatchrs-50585.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/50585 fn main() { |y: Vec<[(); for x in 0..2 {}]>| {}; //~^ ERROR mismatched types diff --git a/tests/ui/issues/issue-50585.stderr b/tests/ui/mismatched_types/for-loop-in-vec-type-mismatchrs-50585.stderr similarity index 89% rename from tests/ui/issues/issue-50585.stderr rename to tests/ui/mismatched_types/for-loop-in-vec-type-mismatchrs-50585.stderr index 7e83ea35fbbda..d60d97a02ab12 100644 --- a/tests/ui/issues/issue-50585.stderr +++ b/tests/ui/mismatched_types/for-loop-in-vec-type-mismatchrs-50585.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-50585.rs:2:18 + --> $DIR/for-loop-in-vec-type-mismatchrs-50585.rs:3:18 | LL | |y: Vec<[(); for x in 0..2 {}]>| {}; | ^^^^^^^^^^^^^^^^ expected `usize`, found `()` diff --git a/tests/ui/issues/issue-48364.rs b/tests/ui/mismatched_types/starts-with-stringify-type-mismatch-48364.rs similarity index 67% rename from tests/ui/issues/issue-48364.rs rename to tests/ui/mismatched_types/starts-with-stringify-type-mismatch-48364.rs index 14ee75e7c9cb6..13ba8b1e59c09 100644 --- a/tests/ui/issues/issue-48364.rs +++ b/tests/ui/mismatched_types/starts-with-stringify-type-mismatch-48364.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/48364 fn foo() -> bool { b"".starts_with(stringify!(foo)) //~^ ERROR mismatched types diff --git a/tests/ui/issues/issue-48364.stderr b/tests/ui/mismatched_types/starts-with-stringify-type-mismatch-48364.stderr similarity index 88% rename from tests/ui/issues/issue-48364.stderr rename to tests/ui/mismatched_types/starts-with-stringify-type-mismatch-48364.stderr index 74bfa1e06933f..bb767d50bb0c7 100644 --- a/tests/ui/issues/issue-48364.stderr +++ b/tests/ui/mismatched_types/starts-with-stringify-type-mismatch-48364.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-48364.rs:2:21 + --> $DIR/starts-with-stringify-type-mismatch-48364.rs:3:21 | LL | b"".starts_with(stringify!(foo)) | ----------- ^^^^^^^^^^^^^^^ expected `&[u8]`, found `&str` diff --git a/tests/ui/issues/issue-32797.rs b/tests/ui/modules/circular-module-imports-32797.rs similarity index 74% rename from tests/ui/issues/issue-32797.rs rename to tests/ui/modules/circular-module-imports-32797.rs index 470d661cb2851..5a2f29907957d 100644 --- a/tests/ui/issues/issue-32797.rs +++ b/tests/ui/modules/circular-module-imports-32797.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/32797 //@ check-pass pub use bar::*; diff --git a/tests/ui/issues/issue-17385.rs b/tests/ui/moves/matching-partially-moved-value-17385.rs similarity index 90% rename from tests/ui/issues/issue-17385.rs rename to tests/ui/moves/matching-partially-moved-value-17385.rs index 7400aadb059f7..c50fe048bfbb8 100644 --- a/tests/ui/issues/issue-17385.rs +++ b/tests/ui/moves/matching-partially-moved-value-17385.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/17385 struct X(isize); enum Enum { diff --git a/tests/ui/issues/issue-17385.stderr b/tests/ui/moves/matching-partially-moved-value-17385.stderr similarity index 83% rename from tests/ui/issues/issue-17385.stderr rename to tests/ui/moves/matching-partially-moved-value-17385.stderr index 3c451a859e94c..906f7868bccbf 100644 --- a/tests/ui/issues/issue-17385.stderr +++ b/tests/ui/moves/matching-partially-moved-value-17385.stderr @@ -1,5 +1,5 @@ error[E0382]: use of moved value: `foo` - --> $DIR/issue-17385.rs:18:5 + --> $DIR/matching-partially-moved-value-17385.rs:19:5 | LL | let foo = X(1); | --- move occurs because `foo` has type `X`, which does not implement the `Copy` trait @@ -9,7 +9,7 @@ LL | match foo { | ^^^^^^^^^ value used here after move | note: if `X` implemented `Clone`, you could clone the value - --> $DIR/issue-17385.rs:1:1 + --> $DIR/matching-partially-moved-value-17385.rs:2:1 | LL | struct X(isize); | ^^^^^^^^ consider implementing `Clone` for this type @@ -18,7 +18,7 @@ LL | drop(foo); | --- you could clone this value error[E0382]: use of moved value: `e` - --> $DIR/issue-17385.rs:25:11 + --> $DIR/matching-partially-moved-value-17385.rs:26:11 | LL | let e = Enum::Variant2; | - move occurs because `e` has type `Enum`, which does not implement the `Copy` trait @@ -28,7 +28,7 @@ LL | match e { | ^ value used here after move | note: if `Enum` implemented `Clone`, you could clone the value - --> $DIR/issue-17385.rs:3:1 + --> $DIR/matching-partially-moved-value-17385.rs:4:1 | LL | enum Enum { | ^^^^^^^^^ consider implementing `Clone` for this type diff --git a/tests/ui/issues/issue-32805.rs b/tests/ui/numbers-arithmetic/f32-literal-rounding-32805.rs similarity index 85% rename from tests/ui/issues/issue-32805.rs rename to tests/ui/numbers-arithmetic/f32-literal-rounding-32805.rs index 717c00a248ad4..59efdb9a1aaf3 100644 --- a/tests/ui/issues/issue-32805.rs +++ b/tests/ui/numbers-arithmetic/f32-literal-rounding-32805.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/32805 //@ run-pass fn const_mir() -> f32 { 9007199791611905.0 } diff --git a/tests/ui/issues/issue-3763.rs b/tests/ui/privacy/private-field-access-violation-3763.rs similarity index 94% rename from tests/ui/issues/issue-3763.rs rename to tests/ui/privacy/private-field-access-violation-3763.rs index 893009a2cd9d2..3fc2337086d75 100644 --- a/tests/ui/issues/issue-3763.rs +++ b/tests/ui/privacy/private-field-access-violation-3763.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/3763 // Regression test for #3763 mod my_mod { diff --git a/tests/ui/issues/issue-3763.stderr b/tests/ui/privacy/private-field-access-violation-3763.stderr similarity index 80% rename from tests/ui/issues/issue-3763.stderr rename to tests/ui/privacy/private-field-access-violation-3763.stderr index d101e4c33add7..6ba83dc4d784f 100644 --- a/tests/ui/issues/issue-3763.stderr +++ b/tests/ui/privacy/private-field-access-violation-3763.stderr @@ -1,17 +1,17 @@ error[E0616]: field `priv_field` of struct `MyStruct` is private - --> $DIR/issue-3763.rs:17:32 + --> $DIR/private-field-access-violation-3763.rs:18:32 | LL | let _woohoo = (&my_struct).priv_field; | ^^^^^^^^^^ private field error[E0616]: field `priv_field` of struct `MyStruct` is private - --> $DIR/issue-3763.rs:20:41 + --> $DIR/private-field-access-violation-3763.rs:21:41 | LL | let _woohoo = (Box::new(my_struct)).priv_field; | ^^^^^^^^^^ private field error[E0624]: method `happyfun` is private - --> $DIR/issue-3763.rs:23:18 + --> $DIR/private-field-access-violation-3763.rs:24:18 | LL | fn happyfun(&self) {} | ------------------ private method defined here @@ -20,7 +20,7 @@ LL | (&my_struct).happyfun(); | ^^^^^^^^ private method error[E0624]: method `happyfun` is private - --> $DIR/issue-3763.rs:25:27 + --> $DIR/private-field-access-violation-3763.rs:26:27 | LL | fn happyfun(&self) {} | ------------------ private method defined here @@ -29,7 +29,7 @@ LL | (Box::new(my_struct)).happyfun(); | ^^^^^^^^ private method error[E0616]: field `priv_field` of struct `MyStruct` is private - --> $DIR/issue-3763.rs:26:26 + --> $DIR/private-field-access-violation-3763.rs:27:26 | LL | let nope = my_struct.priv_field; | ^^^^^^^^^^ private field diff --git a/tests/ui/issues/issue-2281-part1.rs b/tests/ui/resolve/cannot-find-value-in-scope-22811.rs similarity index 64% rename from tests/ui/issues/issue-2281-part1.rs rename to tests/ui/resolve/cannot-find-value-in-scope-22811.rs index 8340ade2239d1..fc07ae5e60ef4 100644 --- a/tests/ui/issues/issue-2281-part1.rs +++ b/tests/ui/resolve/cannot-find-value-in-scope-22811.rs @@ -1 +1,2 @@ +// https://github.com/rust-lang/rust/issues/22811 fn main() { println!("{}", foobar); } //~ ERROR cannot find value `foobar` in this scope diff --git a/tests/ui/issues/issue-2281-part1.stderr b/tests/ui/resolve/cannot-find-value-in-scope-22811.stderr similarity index 84% rename from tests/ui/issues/issue-2281-part1.stderr rename to tests/ui/resolve/cannot-find-value-in-scope-22811.stderr index 47a1ef8cc0277..529fd7e8f495f 100644 --- a/tests/ui/issues/issue-2281-part1.stderr +++ b/tests/ui/resolve/cannot-find-value-in-scope-22811.stderr @@ -1,5 +1,5 @@ error[E0425]: cannot find value `foobar` in this scope - --> $DIR/issue-2281-part1.rs:1:28 + --> $DIR/cannot-find-value-in-scope-22811.rs:2:28 | LL | fn main() { println!("{}", foobar); } | ^^^^^^ not found in this scope diff --git a/tests/ui/issues/issue-33293.rs b/tests/ui/resolve/unresolved-module-error-33293.rs similarity index 74% rename from tests/ui/issues/issue-33293.rs rename to tests/ui/resolve/unresolved-module-error-33293.rs index 115ae3aad204c..354f9914d4431 100644 --- a/tests/ui/issues/issue-33293.rs +++ b/tests/ui/resolve/unresolved-module-error-33293.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/33293 fn main() { match 0 { aaa::bbb(_) => () diff --git a/tests/ui/issues/issue-33293.stderr b/tests/ui/resolve/unresolved-module-error-33293.stderr similarity index 87% rename from tests/ui/issues/issue-33293.stderr rename to tests/ui/resolve/unresolved-module-error-33293.stderr index a82813194d77b..28528148387fb 100644 --- a/tests/ui/issues/issue-33293.stderr +++ b/tests/ui/resolve/unresolved-module-error-33293.stderr @@ -1,5 +1,5 @@ error[E0433]: failed to resolve: use of unresolved module or unlinked crate `aaa` - --> $DIR/issue-33293.rs:3:9 + --> $DIR/unresolved-module-error-33293.rs:4:9 | LL | aaa::bbb(_) => () | ^^^ use of unresolved module or unlinked crate `aaa` diff --git a/tests/ui/issues/issue-47073-zero-padded-tuple-struct-indices.rs b/tests/ui/structs/tuple-struct-field-naming-47073.rs similarity index 86% rename from tests/ui/issues/issue-47073-zero-padded-tuple-struct-indices.rs rename to tests/ui/structs/tuple-struct-field-naming-47073.rs index 6cd1f144359ba..6cf27e55c4bbb 100644 --- a/tests/ui/issues/issue-47073-zero-padded-tuple-struct-indices.rs +++ b/tests/ui/structs/tuple-struct-field-naming-47073.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/47073 type Guilty = bool; type FineDollars = u32; diff --git a/tests/ui/issues/issue-47073-zero-padded-tuple-struct-indices.stderr b/tests/ui/structs/tuple-struct-field-naming-47073.stderr similarity index 81% rename from tests/ui/issues/issue-47073-zero-padded-tuple-struct-indices.stderr rename to tests/ui/structs/tuple-struct-field-naming-47073.stderr index 0a6fe24d5e349..efbdaeca4ea03 100644 --- a/tests/ui/issues/issue-47073-zero-padded-tuple-struct-indices.stderr +++ b/tests/ui/structs/tuple-struct-field-naming-47073.stderr @@ -1,5 +1,5 @@ error[E0609]: no field `00` on type `Verdict` - --> $DIR/issue-47073-zero-padded-tuple-struct-indices.rs:8:30 + --> $DIR/tuple-struct-field-naming-47073.rs:9:30 | LL | let _condemned = justice.00; | ^^ unknown field @@ -11,7 +11,7 @@ LL + let _condemned = justice.0; | error[E0609]: no field `001` on type `Verdict` - --> $DIR/issue-47073-zero-padded-tuple-struct-indices.rs:10:31 + --> $DIR/tuple-struct-field-naming-47073.rs:11:31 | LL | let _punishment = justice.001; | ^^^ unknown field diff --git a/tests/ui/issues/auxiliary/issue-9188.rs b/tests/ui/symbol-names/auxiliary/aux-9188.rs similarity index 100% rename from tests/ui/issues/auxiliary/issue-9188.rs rename to tests/ui/symbol-names/auxiliary/aux-9188.rs diff --git a/tests/ui/symbol-names/same-symbol-name-for-inner-statics-9188.rs b/tests/ui/symbol-names/same-symbol-name-for-inner-statics-9188.rs new file mode 100644 index 0000000000000..a1014bb813fbe --- /dev/null +++ b/tests/ui/symbol-names/same-symbol-name-for-inner-statics-9188.rs @@ -0,0 +1,11 @@ +// https://github.com/rust-lang/rust/issues/9188 +//@ run-pass +//@ aux-build:aux-9188.rs + +extern crate aux_9188 as lib; + +pub fn main() { + let a = lib::bar(); + let b = lib::foo::(); + assert_eq!(*a, *b); +} diff --git a/tests/ui/issues/issue-72839-error-overflow.rs b/tests/ui/trait-bounds/trait-selection-overflow-prevention-72839.rs similarity index 89% rename from tests/ui/issues/issue-72839-error-overflow.rs rename to tests/ui/trait-bounds/trait-selection-overflow-prevention-72839.rs index 6562d228409f3..436657e3de5ee 100644 --- a/tests/ui/issues/issue-72839-error-overflow.rs +++ b/tests/ui/trait-bounds/trait-selection-overflow-prevention-72839.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/72839 // Regression test for issue #72839 // Tests that we do not overflow during trait selection after // a type error occurs diff --git a/tests/ui/issues/issue-72839-error-overflow.stderr b/tests/ui/trait-bounds/trait-selection-overflow-prevention-72839.stderr similarity index 80% rename from tests/ui/issues/issue-72839-error-overflow.stderr rename to tests/ui/trait-bounds/trait-selection-overflow-prevention-72839.stderr index 35be632f57975..da7500f77e1a8 100644 --- a/tests/ui/issues/issue-72839-error-overflow.stderr +++ b/tests/ui/trait-bounds/trait-selection-overflow-prevention-72839.stderr @@ -1,5 +1,5 @@ error[E0425]: cannot find value `missing_var` in this scope - --> $DIR/issue-72839-error-overflow.rs:18:8 + --> $DIR/trait-selection-overflow-prevention-72839.rs:19:8 | LL | if missing_var % 8 == 0 {} | ^^^^^^^^^^^ not found in this scope diff --git a/tests/ui/issues/issue-47638.rs b/tests/ui/trait-objects/trait-object-lifetime-conversion-47638.rs similarity index 78% rename from tests/ui/issues/issue-47638.rs rename to tests/ui/trait-objects/trait-object-lifetime-conversion-47638.rs index e5a51ce0c06f0..c70dc74f3e551 100644 --- a/tests/ui/issues/issue-47638.rs +++ b/tests/ui/trait-objects/trait-object-lifetime-conversion-47638.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/47638 //@ run-pass #![allow(unused_variables)] fn id<'c, 'b>(f: &'c &'b dyn Fn(&i32)) -> &'c &'b dyn Fn(&'static i32) { diff --git a/tests/ui/issues/issue-20413.rs b/tests/ui/traits/trait-impl-overflow-with-where-clause-20413.rs similarity index 93% rename from tests/ui/issues/issue-20413.rs rename to tests/ui/traits/trait-impl-overflow-with-where-clause-20413.rs index 138a235e675e3..e8c27ff5cc895 100644 --- a/tests/ui/issues/issue-20413.rs +++ b/tests/ui/traits/trait-impl-overflow-with-where-clause-20413.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/20413 trait Foo { fn answer(self); } diff --git a/tests/ui/issues/issue-20413.stderr b/tests/ui/traits/trait-impl-overflow-with-where-clause-20413.stderr similarity index 92% rename from tests/ui/issues/issue-20413.stderr rename to tests/ui/traits/trait-impl-overflow-with-where-clause-20413.stderr index 42f3cd2d06274..72aff1b9ee8b7 100644 --- a/tests/ui/issues/issue-20413.stderr +++ b/tests/ui/traits/trait-impl-overflow-with-where-clause-20413.stderr @@ -1,5 +1,5 @@ error[E0392]: type parameter `T` is never used - --> $DIR/issue-20413.rs:5:15 + --> $DIR/trait-impl-overflow-with-where-clause-20413.rs:6:15 | LL | struct NoData; | ^ unused type parameter @@ -8,14 +8,14 @@ LL | struct NoData; = help: if you intended `T` to be a const parameter, use `const T: /* Type */` instead error[E0275]: overflow evaluating the requirement `NoData>>>>>>: Foo` - --> $DIR/issue-20413.rs:8:36 + --> $DIR/trait-impl-overflow-with-where-clause-20413.rs:9:36 | LL | impl Foo for T where NoData: Foo { | ^^^ | - = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`issue_20413`) + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`trait_impl_overflow_with_where_clause_20413`) note: required for `NoData>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>` to implement `Foo` - --> $DIR/issue-20413.rs:8:9 + --> $DIR/trait-impl-overflow-with-where-clause-20413.rs:9:9 | LL | impl Foo for T where NoData: Foo { | ^^^ ^ --- unsatisfied trait bound introduced here @@ -23,19 +23,19 @@ LL | impl Foo for T where NoData: Foo { = note: required for `NoData` to implement `Foo` error[E0275]: overflow evaluating the requirement `AlmostNoData>>>>>>: Bar` - --> $DIR/issue-20413.rs:27:42 + --> $DIR/trait-impl-overflow-with-where-clause-20413.rs:28:42 | LL | impl Bar for T where EvenLessData: Baz { | ^^^ | - = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`issue_20413`) + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`trait_impl_overflow_with_where_clause_20413`) note: required for `EvenLessData>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>` to implement `Baz` - --> $DIR/issue-20413.rs:34:9 + --> $DIR/trait-impl-overflow-with-where-clause-20413.rs:35:9 | LL | impl Baz for T where AlmostNoData: Bar { | ^^^ ^ --- unsatisfied trait bound introduced here note: required for `AlmostNoData>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>` to implement `Bar` - --> $DIR/issue-20413.rs:27:9 + --> $DIR/trait-impl-overflow-with-where-clause-20413.rs:28:9 | LL | impl Bar for T where EvenLessData: Baz { | ^^^ ^ --- unsatisfied trait bound introduced here @@ -43,19 +43,19 @@ LL | impl Bar for T where EvenLessData: Baz { = note: required for `EvenLessData` to implement `Baz` error[E0275]: overflow evaluating the requirement `EvenLessData>>>>>>: Baz` - --> $DIR/issue-20413.rs:34:42 + --> $DIR/trait-impl-overflow-with-where-clause-20413.rs:35:42 | LL | impl Baz for T where AlmostNoData: Bar { | ^^^ | - = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`issue_20413`) + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`trait_impl_overflow_with_where_clause_20413`) note: required for `AlmostNoData>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>` to implement `Bar` - --> $DIR/issue-20413.rs:27:9 + --> $DIR/trait-impl-overflow-with-where-clause-20413.rs:28:9 | LL | impl Bar for T where EvenLessData: Baz { | ^^^ ^ --- unsatisfied trait bound introduced here note: required for `EvenLessData>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>` to implement `Baz` - --> $DIR/issue-20413.rs:34:9 + --> $DIR/trait-impl-overflow-with-where-clause-20413.rs:35:9 | LL | impl Baz for T where AlmostNoData: Bar { | ^^^ ^ --- unsatisfied trait bound introduced here diff --git a/tests/ui/issues/issue-51632-try-desugar-incompatible-types.rs b/tests/ui/try-trait/incompatible-types-with-question-mark-51632.rs similarity index 81% rename from tests/ui/issues/issue-51632-try-desugar-incompatible-types.rs rename to tests/ui/try-trait/incompatible-types-with-question-mark-51632.rs index 35402dff67553..4b2081d14d089 100644 --- a/tests/ui/issues/issue-51632-try-desugar-incompatible-types.rs +++ b/tests/ui/try-trait/incompatible-types-with-question-mark-51632.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/51632 #![allow(dead_code)] fn missing_discourses() -> Result { diff --git a/tests/ui/issues/issue-51632-try-desugar-incompatible-types.stderr b/tests/ui/try-trait/incompatible-types-with-question-mark-51632.stderr similarity index 92% rename from tests/ui/issues/issue-51632-try-desugar-incompatible-types.stderr rename to tests/ui/try-trait/incompatible-types-with-question-mark-51632.stderr index 99fce1eeea6f6..c624605d76ac2 100644 --- a/tests/ui/issues/issue-51632-try-desugar-incompatible-types.stderr +++ b/tests/ui/try-trait/incompatible-types-with-question-mark-51632.stderr @@ -1,5 +1,5 @@ error[E0308]: `?` operator has incompatible types - --> $DIR/issue-51632-try-desugar-incompatible-types.rs:8:5 + --> $DIR/incompatible-types-with-question-mark-51632.rs:9:5 | LL | fn forbidden_narratives() -> Result { | ----------------- expected `Result` because of return type From 868bdde25b030e0b71a29a5dbc04a891036e702e Mon Sep 17 00:00:00 2001 From: Sebastian Poeplau Date: Fri, 1 Aug 2025 12:39:50 +0200 Subject: [PATCH 27/30] Preserve the .debug_gdb_scripts section Make sure that compiler and linker don't optimize the section's contents away by adding the global holding the data to "llvm.used". The volatile load in the main shim is retained because "llvm.used", which translates to SHF_GNU_RETAIN on ELF targets, requires a reasonably recent linker; emitting the volatile load ensures compatibility with older linkers, at least when libstd is used. Pretty printers in dylib dependencies are now emitted by the main crate instead of the dylib; apart from matching how rlibs are handled, this approach has the advantage that `omit_gdb_pretty_printer_section` keeps working with dylib dependencies. --- compiler/rustc_codegen_gcc/src/debuginfo.rs | 3 +- compiler/rustc_codegen_llvm/src/base.rs | 12 +++---- .../rustc_codegen_llvm/src/debuginfo/gdb.rs | 30 ++++++++-------- .../rustc_codegen_llvm/src/debuginfo/mod.rs | 36 +++++++++++-------- compiler/rustc_codegen_ssa/src/base.rs | 10 +----- .../rustc_codegen_ssa/src/traits/debuginfo.rs | 2 +- tests/codegen-llvm/gdb_debug_script_load.rs | 4 ++- tests/run-make/symbols-all-mangled/rmake.rs | 35 ++++++++++-------- 8 files changed, 72 insertions(+), 60 deletions(-) diff --git a/compiler/rustc_codegen_gcc/src/debuginfo.rs b/compiler/rustc_codegen_gcc/src/debuginfo.rs index 4c8585192a1b1..4c0b643952320 100644 --- a/compiler/rustc_codegen_gcc/src/debuginfo.rs +++ b/compiler/rustc_codegen_gcc/src/debuginfo.rs @@ -254,7 +254,8 @@ impl<'gcc, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { // TODO(antoyo): implement. } - fn debuginfo_finalize(&self) { + fn debuginfo_finalize(&mut self) { + // TODO: emit section `.debug_gdb_scripts`. self.context.set_debug_info(true) } diff --git a/compiler/rustc_codegen_llvm/src/base.rs b/compiler/rustc_codegen_llvm/src/base.rs index 5dda836988c81..d7da03bf490fd 100644 --- a/compiler/rustc_codegen_llvm/src/base.rs +++ b/compiler/rustc_codegen_llvm/src/base.rs @@ -109,11 +109,16 @@ pub(crate) fn compile_codegen_unit( } // Finalize code coverage by injecting the coverage map. Note, the coverage map will - // also be added to the `llvm.compiler.used` variable, created next. + // also be added to the `llvm.compiler.used` variable, created below. if cx.sess().instrument_coverage() { cx.coverageinfo_finalize(); } + // Finalize debuginfo. This adds to `llvm.used`, created below. + if cx.sess().opts.debuginfo != DebugInfo::None { + cx.debuginfo_finalize(); + } + // Create the llvm.used and llvm.compiler.used variables. if !cx.used_statics.is_empty() { cx.create_used_variable_impl(c"llvm.used", &cx.used_statics); @@ -130,11 +135,6 @@ pub(crate) fn compile_codegen_unit( llvm::LLVMDeleteGlobal(old_g); } } - - // Finalize debuginfo - if cx.sess().opts.debuginfo != DebugInfo::None { - cx.debuginfo_finalize(); - } } ModuleCodegen::new_regular(cgu_name.to_string(), llvm_module) diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs index 6eb7042da6171..b3e978be5701f 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs @@ -1,5 +1,7 @@ // .debug_gdb_scripts binary section. +use std::ffi::CString; + use rustc_codegen_ssa::base::collect_debugger_visualizers_transitive; use rustc_codegen_ssa::traits::*; use rustc_hir::def_id::LOCAL_CRATE; @@ -31,7 +33,12 @@ pub(crate) fn insert_reference_to_gdb_debug_scripts_section_global(bx: &mut Buil pub(crate) fn get_or_insert_gdb_debug_scripts_section_global<'ll>( cx: &CodegenCx<'ll, '_>, ) -> &'ll Value { - let c_section_var_name = c"__rustc_debug_gdb_scripts_section__"; + let c_section_var_name = CString::new(format!( + "__rustc_debug_gdb_scripts_section_{}_{:08x}", + cx.tcx.crate_name(LOCAL_CRATE), + cx.tcx.stable_crate_id(LOCAL_CRATE), + )) + .unwrap(); let section_var_name = c_section_var_name.to_str().unwrap(); let section_var = unsafe { llvm::LLVMGetNamedGlobal(cx.llmod, c_section_var_name.as_ptr()) }; @@ -84,17 +91,10 @@ pub(crate) fn get_or_insert_gdb_debug_scripts_section_global<'ll>( } pub(crate) fn needs_gdb_debug_scripts_section(cx: &CodegenCx<'_, '_>) -> bool { - // To ensure the section `__rustc_debug_gdb_scripts_section__` will not create - // ODR violations at link time, this section will not be emitted for rlibs since - // each rlib could produce a different set of visualizers that would be embedded - // in the `.debug_gdb_scripts` section. For that reason, we make sure that the - // section is only emitted for leaf crates. + // We collect pretty printers transitively for all crates, so we make sure + // that the section is only emitted for leaf crates. let embed_visualizers = cx.tcx.crate_types().iter().any(|&crate_type| match crate_type { - CrateType::Executable - | CrateType::Dylib - | CrateType::Cdylib - | CrateType::Staticlib - | CrateType::Sdylib => { + CrateType::Executable | CrateType::Cdylib | CrateType::Staticlib | CrateType::Sdylib => { // These are crate types for which we will embed pretty printers since they // are treated as leaf crates. true @@ -105,9 +105,11 @@ pub(crate) fn needs_gdb_debug_scripts_section(cx: &CodegenCx<'_, '_>) -> bool { // want to slow down the common case. false } - CrateType::Rlib => { - // As per the above description, embedding pretty printers for rlibs could - // lead to ODR violations so we skip this crate type as well. + CrateType::Rlib | CrateType::Dylib => { + // Don't embed pretty printers for these crate types; the compiler + // can see the `#[debug_visualizer]` attributes when using the + // library, and emitting `.debug_gdb_scripts` regardless would + // break `#![omit_gdb_pretty_printer_section]`. false } }); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index 6cbf2dbf7d3fd..c911435967c3e 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -30,7 +30,7 @@ use tracing::debug; use self::metadata::{UNKNOWN_COLUMN_NUMBER, UNKNOWN_LINE_NUMBER, file_metadata, type_di_node}; use self::namespace::mangled_name_of_instance; -use self::utils::{DIB, create_DIArray, is_node_local_to_unit}; +use self::utils::{DIB, create_DIArray, debug_context, is_node_local_to_unit}; use crate::builder::Builder; use crate::common::{AsCCharPtr, CodegenCx}; use crate::llvm; @@ -131,20 +131,28 @@ impl<'ll, 'tcx> CodegenUnitDebugContext<'ll, 'tcx> { } /// Creates any deferred debug metadata nodes -pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) { - if let Some(dbg_cx) = &cx.dbg_cx { - debug!("finalize"); - - if gdb::needs_gdb_debug_scripts_section(cx) { - // Add a .debug_gdb_scripts section to this compile-unit. This will - // cause GDB to try and load the gdb_load_rust_pretty_printers.py file, - // which activates the Rust pretty printers for binary this section is - // contained in. - gdb::get_or_insert_gdb_debug_scripts_section_global(cx); - } +pub(crate) fn finalize(cx: &mut CodegenCx<'_, '_>) { + if cx.dbg_cx.is_none() { + return; + } + + debug!("finalize"); - dbg_cx.finalize(cx.sess()); + if gdb::needs_gdb_debug_scripts_section(cx) { + // Add a .debug_gdb_scripts section to this compile-unit. This will + // cause GDB to try and load the gdb_load_rust_pretty_printers.py file, + // which activates the Rust pretty printers for binary this section is + // contained in. + let section_var = gdb::get_or_insert_gdb_debug_scripts_section_global(cx); + + // Make sure that the linker doesn't optimize the global away. Adding + // it to `llvm.used` has the advantage that it works even in no_std + // binaries, where we don't have a main shim and thus don't emit a + // volatile load to preserve the global. + cx.add_used_global(section_var); } + + debug_context(cx).finalize(cx.sess()); } impl<'ll> Builder<'_, 'll, '_> { @@ -614,7 +622,7 @@ impl<'ll, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { metadata::extend_scope_to_file(self, scope_metadata, file) } - fn debuginfo_finalize(&self) { + fn debuginfo_finalize(&mut self) { finalize(self) } diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index b4556ced0b3fb..eb21468650c76 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -609,15 +609,7 @@ pub fn collect_debugger_visualizers_transitive( ) -> BTreeSet { tcx.debugger_visualizers(LOCAL_CRATE) .iter() - .chain( - tcx.crates(()) - .iter() - .filter(|&cnum| { - let used_crate_source = tcx.used_crate_source(*cnum); - used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some() - }) - .flat_map(|&cnum| tcx.debugger_visualizers(cnum)), - ) + .chain(tcx.crates(()).iter().flat_map(|&cnum| tcx.debugger_visualizers(cnum))) .filter(|visualizer| visualizer.visualizer_type == visualizer_type) .cloned() .collect::>() diff --git a/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs b/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs index b9d4950e0ad36..30a3bd5abe492 100644 --- a/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs +++ b/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs @@ -50,7 +50,7 @@ pub trait DebugInfoCodegenMethods<'tcx>: BackendTypes { scope_metadata: Self::DIScope, file: &SourceFile, ) -> Self::DIScope; - fn debuginfo_finalize(&self); + fn debuginfo_finalize(&mut self); // FIXME(eddyb) find a common convention for all of the debuginfo-related // names (choose between `dbg`, `debug`, `debuginfo`, `debug_info` etc.). diff --git a/tests/codegen-llvm/gdb_debug_script_load.rs b/tests/codegen-llvm/gdb_debug_script_load.rs index 3e92eba10b121..90f2be41cf2ac 100644 --- a/tests/codegen-llvm/gdb_debug_script_load.rs +++ b/tests/codegen-llvm/gdb_debug_script_load.rs @@ -9,6 +9,8 @@ #![feature(lang_items)] #![no_std] +// CHECK: @llvm.used = {{.+}} @__rustc_debug_gdb_scripts_section + #[panic_handler] fn panic_handler(_: &core::panic::PanicInfo) -> ! { loop {} @@ -22,7 +24,7 @@ extern "C" fn rust_eh_personality() { // Needs rustc to generate `main` as that's where the magic load is inserted. // IOW, we cannot write this test with `#![no_main]`. // CHECK-LABEL: @main -// CHECK: load volatile i8, {{.+}} @__rustc_debug_gdb_scripts_section__ +// CHECK: load volatile i8, {{.+}} @__rustc_debug_gdb_scripts_section #[lang = "start"] fn lang_start( diff --git a/tests/run-make/symbols-all-mangled/rmake.rs b/tests/run-make/symbols-all-mangled/rmake.rs index 2cf579758002a..e30bef9858079 100644 --- a/tests/run-make/symbols-all-mangled/rmake.rs +++ b/tests/run-make/symbols-all-mangled/rmake.rs @@ -35,13 +35,7 @@ fn symbols_check_archive(path: &str) { continue; // All compiler-builtins symbols must remain unmangled } - if name.contains("rust_eh_personality") { - continue; // Unfortunately LLVM doesn't allow us to mangle this symbol - } - - if name.contains(".llvm.") { - // Starting in LLVM 21 we get various implementation-detail functions which - // contain .llvm. that are not a problem. + if symbol_ok_everywhere(name) { continue; } @@ -71,13 +65,7 @@ fn symbols_check(path: &str) { continue; } - if name.contains("rust_eh_personality") { - continue; // Unfortunately LLVM doesn't allow us to mangle this symbol - } - - if name.contains(".llvm.") { - // Starting in LLVM 21 we get various implementation-detail functions which - // contain .llvm. that are not a problem. + if symbol_ok_everywhere(name) { continue; } @@ -88,3 +76,22 @@ fn symbols_check(path: &str) { fn strip_underscore_if_apple(symbol: &str) -> &str { if cfg!(target_vendor = "apple") { symbol.strip_prefix("_").unwrap() } else { symbol } } + +fn symbol_ok_everywhere(name: &str) -> bool { + if name.contains("rust_eh_personality") { + return true; // Unfortunately LLVM doesn't allow us to mangle this symbol + } + + if name.contains(".llvm.") { + // Starting in LLVM 21 we get various implementation-detail functions which + // contain .llvm. that are not a problem. + return true; + } + + if name.starts_with("__rustc_debug_gdb_scripts_section") { + // These symbols are fine; they're made unique by the crate ID. + return true; + } + + return false; +} From 33cb4190a2a0e9cb9745dccd43e4f97d62f49c21 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Mon, 14 Jul 2025 17:31:41 +0300 Subject: [PATCH 28/30] Mark all deprecation lints in name resolution as deny-by-default and report-in-deps --- compiler/rustc_lint_defs/src/builtin.rs | 12 ++- .../attributes/key-value-expansion-scope.rs | 12 +-- .../key-value-expansion-scope.stderr | 88 +++++++++++++++++-- tests/ui/extern/issue-80074.rs | 2 +- tests/ui/extern/issue-80074.stderr | 17 +++- .../local-modularized-tricky-fail-2.stderr | 44 ++++++++++ .../ui/proc-macro/derive-helper-shadowing.rs | 2 +- .../proc-macro/derive-helper-shadowing.stderr | 20 ++++- .../helper-attr-blocked-by-import-ambig.rs | 2 +- ...helper-attr-blocked-by-import-ambig.stderr | 20 ++++- tests/ui/proc-macro/issue-75930-derive-cfg.rs | 2 +- .../proc-macro/issue-75930-derive-cfg.stderr | 42 ++++++++- tests/ui/proc-macro/proc-macro-attributes.rs | 8 +- .../proc-macro/proc-macro-attributes.stderr | 68 ++++++++++++-- 14 files changed, 297 insertions(+), 42 deletions(-) diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 3b84c6b611016..e3c9a65cd60f3 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -2156,6 +2156,7 @@ declare_lint! { @future_incompatible = FutureIncompatibleInfo { reason: FutureIncompatibilityReason::FutureReleaseError, reference: "issue #52234 ", + report_in_deps: true, }; crate_level_only } @@ -2887,11 +2888,12 @@ declare_lint! { /// struct S { /* fields */ } /// ``` pub LEGACY_DERIVE_HELPERS, - Warn, + Deny, "detects derive helper attributes that are used before they are introduced", @future_incompatible = FutureIncompatibleInfo { reason: FutureIncompatibilityReason::FutureReleaseError, reference: "issue #79202 ", + report_in_deps: true, }; } @@ -4624,11 +4626,12 @@ declare_lint! { /// /// [future-incompatible]: ../index.md#future-incompatible-lints pub PRIVATE_MACRO_USE, - Warn, + Deny, "detects certain macro bindings that should not be re-exported", @future_incompatible = FutureIncompatibleInfo { reason: FutureIncompatibilityReason::FutureReleaseError, reference: "issue #120192 ", + report_in_deps: true, }; } @@ -4828,7 +4831,7 @@ declare_lint! { /// /// ### Example /// - /// ```rust + /// ```rust,compile_fail /// #![doc = in_root!()] /// /// macro_rules! in_root { () => { "" } } @@ -4853,11 +4856,12 @@ declare_lint! { /// /// [future-incompatible]: ../index.md#future-incompatible-lints pub OUT_OF_SCOPE_MACRO_CALLS, - Warn, + Deny, "detects out of scope calls to `macro_rules` in key-value attributes", @future_incompatible = FutureIncompatibleInfo { reason: FutureIncompatibilityReason::FutureReleaseError, reference: "issue #124535 ", + report_in_deps: true, }; } diff --git a/tests/ui/attributes/key-value-expansion-scope.rs b/tests/ui/attributes/key-value-expansion-scope.rs index 49a59502377f5..6688d698f9eae 100644 --- a/tests/ui/attributes/key-value-expansion-scope.rs +++ b/tests/ui/attributes/key-value-expansion-scope.rs @@ -1,7 +1,7 @@ -#![doc = in_root!()] //~ WARN cannot find macro `in_root` +#![doc = in_root!()] //~ ERROR cannot find macro `in_root` //~| WARN this was previously accepted by the compiler #![doc = in_mod!()] //~ ERROR cannot find macro `in_mod` in this scope -#![doc = in_mod_escape!()] //~ WARN cannot find macro `in_mod_escape` +#![doc = in_mod_escape!()] //~ ERROR cannot find macro `in_mod_escape` //~| WARN this was previously accepted by the compiler #![doc = in_block!()] //~ ERROR cannot find macro `in_block` in this scope @@ -18,10 +18,10 @@ fn before() { macro_rules! in_root { () => { "" } } -#[doc = in_mod!()] //~ WARN cannot find macro `in_mod` +#[doc = in_mod!()] //~ ERROR cannot find macro `in_mod` //~| WARN this was previously accepted by the compiler mod macros_stay { - #![doc = in_mod!()] //~ WARN cannot find macro `in_mod` + #![doc = in_mod!()] //~ ERROR cannot find macro `in_mod` //~| WARN this was previously accepted by the compiler macro_rules! in_mod { () => { "" } } @@ -33,10 +33,10 @@ mod macros_stay { } #[macro_use] -#[doc = in_mod_escape!()] //~ WARN cannot find macro `in_mod_escape` +#[doc = in_mod_escape!()] //~ ERROR cannot find macro `in_mod_escape` //~| WARN this was previously accepted by the compiler mod macros_escape { - #![doc = in_mod_escape!()] //~ WARN cannot find macro `in_mod_escape` + #![doc = in_mod_escape!()] //~ ERROR cannot find macro `in_mod_escape` //~| WARN this was previously accepted by the compiler macro_rules! in_mod_escape { () => { "" } } diff --git a/tests/ui/attributes/key-value-expansion-scope.stderr b/tests/ui/attributes/key-value-expansion-scope.stderr index 91a602e57d9e4..29b48ca4ce683 100644 --- a/tests/ui/attributes/key-value-expansion-scope.stderr +++ b/tests/ui/attributes/key-value-expansion-scope.stderr @@ -126,7 +126,7 @@ LL | #![doc = in_block!()] | = help: have you added the `#[macro_use]` on the module/import? -warning: cannot find macro `in_root` in the current scope when looking from the crate root +error: cannot find macro `in_root` in the current scope when looking from the crate root --> $DIR/key-value-expansion-scope.rs:1:10 | LL | #![doc = in_root!()] @@ -135,9 +135,9 @@ LL | #![doc = in_root!()] = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #124535 = help: import `macro_rules` with `use` to make it callable above its definition - = note: `#[warn(out_of_scope_macro_calls)]` on by default + = note: `#[deny(out_of_scope_macro_calls)]` on by default -warning: cannot find macro `in_mod_escape` in the current scope when looking from the crate root +error: cannot find macro `in_mod_escape` in the current scope when looking from the crate root --> $DIR/key-value-expansion-scope.rs:4:10 | LL | #![doc = in_mod_escape!()] @@ -147,7 +147,7 @@ LL | #![doc = in_mod_escape!()] = note: for more information, see issue #124535 = help: import `macro_rules` with `use` to make it callable above its definition -warning: cannot find macro `in_mod` in the current scope when looking from module `macros_stay` +error: cannot find macro `in_mod` in the current scope when looking from module `macros_stay` --> $DIR/key-value-expansion-scope.rs:21:9 | LL | #[doc = in_mod!()] @@ -157,7 +157,7 @@ LL | #[doc = in_mod!()] = note: for more information, see issue #124535 = help: import `macro_rules` with `use` to make it callable above its definition -warning: cannot find macro `in_mod` in the current scope when looking from module `macros_stay` +error: cannot find macro `in_mod` in the current scope when looking from module `macros_stay` --> $DIR/key-value-expansion-scope.rs:24:14 | LL | #![doc = in_mod!()] @@ -167,7 +167,7 @@ LL | #![doc = in_mod!()] = note: for more information, see issue #124535 = help: import `macro_rules` with `use` to make it callable above its definition -warning: cannot find macro `in_mod_escape` in the current scope when looking from module `macros_escape` +error: cannot find macro `in_mod_escape` in the current scope when looking from module `macros_escape` --> $DIR/key-value-expansion-scope.rs:36:9 | LL | #[doc = in_mod_escape!()] @@ -177,7 +177,7 @@ LL | #[doc = in_mod_escape!()] = note: for more information, see issue #124535 = help: import `macro_rules` with `use` to make it callable above its definition -warning: cannot find macro `in_mod_escape` in the current scope when looking from module `macros_escape` +error: cannot find macro `in_mod_escape` in the current scope when looking from module `macros_escape` --> $DIR/key-value-expansion-scope.rs:39:14 | LL | #![doc = in_mod_escape!()] @@ -187,5 +187,77 @@ LL | #![doc = in_mod_escape!()] = note: for more information, see issue #124535 = help: import `macro_rules` with `use` to make it callable above its definition -error: aborting due to 16 previous errors; 6 warnings emitted +error: aborting due to 22 previous errors + +Future incompatibility report: Future breakage diagnostic: +error: cannot find macro `in_root` in the current scope when looking from the crate root + --> $DIR/key-value-expansion-scope.rs:1:10 + | +LL | #![doc = in_root!()] + | ^^^^^^^ not found from the crate root + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #124535 + = help: import `macro_rules` with `use` to make it callable above its definition + = note: `#[deny(out_of_scope_macro_calls)]` on by default + +Future breakage diagnostic: +error: cannot find macro `in_mod_escape` in the current scope when looking from the crate root + --> $DIR/key-value-expansion-scope.rs:4:10 + | +LL | #![doc = in_mod_escape!()] + | ^^^^^^^^^^^^^ not found from the crate root + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #124535 + = help: import `macro_rules` with `use` to make it callable above its definition + = note: `#[deny(out_of_scope_macro_calls)]` on by default + +Future breakage diagnostic: +error: cannot find macro `in_mod` in the current scope when looking from module `macros_stay` + --> $DIR/key-value-expansion-scope.rs:21:9 + | +LL | #[doc = in_mod!()] + | ^^^^^^ not found from module `macros_stay` + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #124535 + = help: import `macro_rules` with `use` to make it callable above its definition + = note: `#[deny(out_of_scope_macro_calls)]` on by default + +Future breakage diagnostic: +error: cannot find macro `in_mod` in the current scope when looking from module `macros_stay` + --> $DIR/key-value-expansion-scope.rs:24:14 + | +LL | #![doc = in_mod!()] + | ^^^^^^ not found from module `macros_stay` + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #124535 + = help: import `macro_rules` with `use` to make it callable above its definition + = note: `#[deny(out_of_scope_macro_calls)]` on by default + +Future breakage diagnostic: +error: cannot find macro `in_mod_escape` in the current scope when looking from module `macros_escape` + --> $DIR/key-value-expansion-scope.rs:36:9 + | +LL | #[doc = in_mod_escape!()] + | ^^^^^^^^^^^^^ not found from module `macros_escape` + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #124535 + = help: import `macro_rules` with `use` to make it callable above its definition + = note: `#[deny(out_of_scope_macro_calls)]` on by default + +Future breakage diagnostic: +error: cannot find macro `in_mod_escape` in the current scope when looking from module `macros_escape` + --> $DIR/key-value-expansion-scope.rs:39:14 + | +LL | #![doc = in_mod_escape!()] + | ^^^^^^^^^^^^^ not found from module `macros_escape` + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #124535 + = help: import `macro_rules` with `use` to make it callable above its definition + = note: `#[deny(out_of_scope_macro_calls)]` on by default diff --git a/tests/ui/extern/issue-80074.rs b/tests/ui/extern/issue-80074.rs index ba7b55a450f51..942b78916d6a0 100644 --- a/tests/ui/extern/issue-80074.rs +++ b/tests/ui/extern/issue-80074.rs @@ -11,7 +11,7 @@ extern crate issue_80074_2; fn main() { foo!(); - //~^ WARN: macro `foo` is private + //~^ ERROR: macro `foo` is private //~| WARN: it will become a hard error in a future release! bar!(); //~^ ERROR: cannot find macro `bar` in this scope diff --git a/tests/ui/extern/issue-80074.stderr b/tests/ui/extern/issue-80074.stderr index b30b761593e88..510ca1be0a199 100644 --- a/tests/ui/extern/issue-80074.stderr +++ b/tests/ui/extern/issue-80074.stderr @@ -16,7 +16,7 @@ error: cannot find macro `m` in this scope LL | m!(); | ^ -warning: macro `foo` is private +error: macro `foo` is private --> $DIR/issue-80074.rs:13:5 | LL | foo!(); @@ -24,8 +24,19 @@ LL | foo!(); | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #120192 - = note: `#[warn(private_macro_use)]` on by default + = note: `#[deny(private_macro_use)]` on by default -error: aborting due to 3 previous errors; 1 warning emitted +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0469`. +Future incompatibility report: Future breakage diagnostic: +error: macro `foo` is private + --> $DIR/issue-80074.rs:13:5 + | +LL | foo!(); + | ^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #120192 + = note: `#[deny(private_macro_use)]` on by default + diff --git a/tests/ui/imports/local-modularized-tricky-fail-2.stderr b/tests/ui/imports/local-modularized-tricky-fail-2.stderr index 49f5c72947f43..ea4056b3d7504 100644 --- a/tests/ui/imports/local-modularized-tricky-fail-2.stderr +++ b/tests/ui/imports/local-modularized-tricky-fail-2.stderr @@ -41,3 +41,47 @@ LL | define_exported!(); error: aborting due to 2 previous errors +Future incompatibility report: Future breakage diagnostic: +error: macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths + --> $DIR/local-modularized-tricky-fail-2.rs:13:9 + | +LL | use crate::exported; + | ^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #52234 +note: the macro is defined here + --> $DIR/local-modularized-tricky-fail-2.rs:5:5 + | +LL | / macro_rules! exported { +LL | | () => () +LL | | } + | |_____^ +... +LL | define_exported!(); + | ------------------ in this macro invocation + = note: `#[deny(macro_expanded_macro_exports_accessed_by_absolute_paths)]` on by default + = note: this error originates in the macro `define_exported` (in Nightly builds, run with -Z macro-backtrace for more info) + +Future breakage diagnostic: +error: macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths + --> $DIR/local-modularized-tricky-fail-2.rs:19:5 + | +LL | crate::exported!(); + | ^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #52234 +note: the macro is defined here + --> $DIR/local-modularized-tricky-fail-2.rs:5:5 + | +LL | / macro_rules! exported { +LL | | () => () +LL | | } + | |_____^ +... +LL | define_exported!(); + | ------------------ in this macro invocation + = note: `#[deny(macro_expanded_macro_exports_accessed_by_absolute_paths)]` on by default + = note: this error originates in the macro `define_exported` (in Nightly builds, run with -Z macro-backtrace for more info) + diff --git a/tests/ui/proc-macro/derive-helper-shadowing.rs b/tests/ui/proc-macro/derive-helper-shadowing.rs index e774e46405381..ee883be33526c 100644 --- a/tests/ui/proc-macro/derive-helper-shadowing.rs +++ b/tests/ui/proc-macro/derive-helper-shadowing.rs @@ -17,7 +17,7 @@ macro_rules! gen_helper_use { } #[empty_helper] //~ ERROR `empty_helper` is ambiguous - //~| WARN derive helper attribute is used before it is introduced + //~| ERROR derive helper attribute is used before it is introduced //~| WARN this was previously accepted #[derive(Empty)] struct S { diff --git a/tests/ui/proc-macro/derive-helper-shadowing.stderr b/tests/ui/proc-macro/derive-helper-shadowing.stderr index 1206778bb2352..65989375ab5d0 100644 --- a/tests/ui/proc-macro/derive-helper-shadowing.stderr +++ b/tests/ui/proc-macro/derive-helper-shadowing.stderr @@ -58,7 +58,7 @@ LL | use test_macros::empty_attr as empty_helper; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = help: use `crate::empty_helper` to refer to this attribute macro unambiguously -warning: derive helper attribute is used before it is introduced +error: derive helper attribute is used before it is introduced --> $DIR/derive-helper-shadowing.rs:19:3 | LL | #[empty_helper] @@ -69,8 +69,22 @@ LL | #[derive(Empty)] | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79202 - = note: `#[warn(legacy_derive_helpers)]` on by default + = note: `#[deny(legacy_derive_helpers)]` on by default -error: aborting due to 4 previous errors; 1 warning emitted +error: aborting due to 5 previous errors For more information about this error, try `rustc --explain E0659`. +Future incompatibility report: Future breakage diagnostic: +error: derive helper attribute is used before it is introduced + --> $DIR/derive-helper-shadowing.rs:19:3 + | +LL | #[empty_helper] + | ^^^^^^^^^^^^ +... +LL | #[derive(Empty)] + | ----- the attribute is introduced here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #79202 + = note: `#[deny(legacy_derive_helpers)]` on by default + diff --git a/tests/ui/proc-macro/helper-attr-blocked-by-import-ambig.rs b/tests/ui/proc-macro/helper-attr-blocked-by-import-ambig.rs index 1197dd7f3bfd0..97c81e9945d1b 100644 --- a/tests/ui/proc-macro/helper-attr-blocked-by-import-ambig.rs +++ b/tests/ui/proc-macro/helper-attr-blocked-by-import-ambig.rs @@ -5,7 +5,7 @@ extern crate test_macros; use test_macros::empty_attr as empty_helper; #[empty_helper] //~ ERROR `empty_helper` is ambiguous - //~| WARN derive helper attribute is used before it is introduced + //~| ERROR derive helper attribute is used before it is introduced //~| WARN this was previously accepted #[derive(Empty)] struct S; diff --git a/tests/ui/proc-macro/helper-attr-blocked-by-import-ambig.stderr b/tests/ui/proc-macro/helper-attr-blocked-by-import-ambig.stderr index 1c12a2804c6d3..df7951464fb8e 100644 --- a/tests/ui/proc-macro/helper-attr-blocked-by-import-ambig.stderr +++ b/tests/ui/proc-macro/helper-attr-blocked-by-import-ambig.stderr @@ -17,7 +17,7 @@ LL | use test_macros::empty_attr as empty_helper; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = help: use `crate::empty_helper` to refer to this attribute macro unambiguously -warning: derive helper attribute is used before it is introduced +error: derive helper attribute is used before it is introduced --> $DIR/helper-attr-blocked-by-import-ambig.rs:7:3 | LL | #[empty_helper] @@ -28,8 +28,22 @@ LL | #[derive(Empty)] | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79202 - = note: `#[warn(legacy_derive_helpers)]` on by default + = note: `#[deny(legacy_derive_helpers)]` on by default -error: aborting due to 1 previous error; 1 warning emitted +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0659`. +Future incompatibility report: Future breakage diagnostic: +error: derive helper attribute is used before it is introduced + --> $DIR/helper-attr-blocked-by-import-ambig.rs:7:3 + | +LL | #[empty_helper] + | ^^^^^^^^^^^^ +... +LL | #[derive(Empty)] + | ----- the attribute is introduced here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #79202 + = note: `#[deny(legacy_derive_helpers)]` on by default + diff --git a/tests/ui/proc-macro/issue-75930-derive-cfg.rs b/tests/ui/proc-macro/issue-75930-derive-cfg.rs index f0851b31e9cb8..e8df1a66dd949 100644 --- a/tests/ui/proc-macro/issue-75930-derive-cfg.rs +++ b/tests/ui/proc-macro/issue-75930-derive-cfg.rs @@ -6,7 +6,7 @@ // Tests that we cfg-strip all targets before invoking // a derive macro // FIXME: We currently lose spans here (see issue #43081) - +#![warn(legacy_derive_helpers)] #![no_std] // Don't load unnecessary hygiene information from std extern crate std; diff --git a/tests/ui/proc-macro/issue-75930-derive-cfg.stderr b/tests/ui/proc-macro/issue-75930-derive-cfg.stderr index df1e36d739080..906e9c6bf69f4 100644 --- a/tests/ui/proc-macro/issue-75930-derive-cfg.stderr +++ b/tests/ui/proc-macro/issue-75930-derive-cfg.stderr @@ -9,7 +9,11 @@ LL | #[derive(Print)] | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79202 - = note: `#[warn(legacy_derive_helpers)]` on by default +note: the lint level is defined here + --> $DIR/issue-75930-derive-cfg.rs:9:9 + | +LL | #![warn(legacy_derive_helpers)] + | ^^^^^^^^^^^^^^^^^^^^^ warning: derive helper attribute is used before it is introduced --> $DIR/issue-75930-derive-cfg.rs:46:3 @@ -26,3 +30,39 @@ LL | #[derive(Print)] warning: 2 warnings emitted +Future incompatibility report: Future breakage diagnostic: +warning: derive helper attribute is used before it is introduced + --> $DIR/issue-75930-derive-cfg.rs:46:3 + | +LL | #[print_helper(a)] + | ^^^^^^^^^^^^ +... +LL | #[derive(Print)] + | ----- the attribute is introduced here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #79202 +note: the lint level is defined here + --> $DIR/issue-75930-derive-cfg.rs:9:9 + | +LL | #![warn(legacy_derive_helpers)] + | ^^^^^^^^^^^^^^^^^^^^^ + +Future breakage diagnostic: +warning: derive helper attribute is used before it is introduced + --> $DIR/issue-75930-derive-cfg.rs:46:3 + | +LL | #[print_helper(a)] + | ^^^^^^^^^^^^ +... +LL | #[derive(Print)] + | ----- the attribute is introduced here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #79202 +note: the lint level is defined here + --> $DIR/issue-75930-derive-cfg.rs:9:9 + | +LL | #![warn(legacy_derive_helpers)] + | ^^^^^^^^^^^^^^^^^^^^^ + diff --git a/tests/ui/proc-macro/proc-macro-attributes.rs b/tests/ui/proc-macro/proc-macro-attributes.rs index 455fcc56e58b0..f1270b896aaae 100644 --- a/tests/ui/proc-macro/proc-macro-attributes.rs +++ b/tests/ui/proc-macro/proc-macro-attributes.rs @@ -4,17 +4,17 @@ extern crate derive_b; #[B] //~ ERROR `B` is ambiguous - //~| WARN derive helper attribute is used before it is introduced + //~| ERROR derive helper attribute is used before it is introduced //~| WARN this was previously accepted #[C] //~ ERROR cannot find attribute `C` in this scope #[B(D)] //~ ERROR `B` is ambiguous - //~| WARN derive helper attribute is used before it is introduced + //~| ERROR derive helper attribute is used before it is introduced //~| WARN this was previously accepted #[B(E = "foo")] //~ ERROR `B` is ambiguous - //~| WARN derive helper attribute is used before it is introduced + //~| ERROR derive helper attribute is used before it is introduced //~| WARN this was previously accepted #[B(arbitrary tokens)] //~ ERROR `B` is ambiguous - //~| WARN derive helper attribute is used before it is introduced + //~| ERROR derive helper attribute is used before it is introduced //~| WARN this was previously accepted #[derive(B)] struct B; diff --git a/tests/ui/proc-macro/proc-macro-attributes.stderr b/tests/ui/proc-macro/proc-macro-attributes.stderr index 140d879069040..2cc57383eb39c 100644 --- a/tests/ui/proc-macro/proc-macro-attributes.stderr +++ b/tests/ui/proc-macro/proc-macro-attributes.stderr @@ -76,7 +76,7 @@ note: `B` could also refer to the derive macro imported here LL | #[macro_use] | ^^^^^^^^^^^^ -warning: derive helper attribute is used before it is introduced +error: derive helper attribute is used before it is introduced --> $DIR/proc-macro-attributes.rs:6:3 | LL | #[B] @@ -87,9 +87,9 @@ LL | #[derive(B)] | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79202 - = note: `#[warn(legacy_derive_helpers)]` on by default + = note: `#[deny(legacy_derive_helpers)]` on by default -warning: derive helper attribute is used before it is introduced +error: derive helper attribute is used before it is introduced --> $DIR/proc-macro-attributes.rs:10:3 | LL | #[B(D)] @@ -101,7 +101,7 @@ LL | #[derive(B)] = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79202 -warning: derive helper attribute is used before it is introduced +error: derive helper attribute is used before it is introduced --> $DIR/proc-macro-attributes.rs:13:3 | LL | #[B(E = "foo")] @@ -113,7 +113,7 @@ LL | #[derive(B)] = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79202 -warning: derive helper attribute is used before it is introduced +error: derive helper attribute is used before it is introduced --> $DIR/proc-macro-attributes.rs:16:3 | LL | #[B(arbitrary tokens)] @@ -125,6 +125,62 @@ LL | #[derive(B)] = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79202 -error: aborting due to 5 previous errors; 4 warnings emitted +error: aborting due to 9 previous errors For more information about this error, try `rustc --explain E0659`. +Future incompatibility report: Future breakage diagnostic: +error: derive helper attribute is used before it is introduced + --> $DIR/proc-macro-attributes.rs:6:3 + | +LL | #[B] + | ^ +... +LL | #[derive(B)] + | - the attribute is introduced here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #79202 + = note: `#[deny(legacy_derive_helpers)]` on by default + +Future breakage diagnostic: +error: derive helper attribute is used before it is introduced + --> $DIR/proc-macro-attributes.rs:10:3 + | +LL | #[B(D)] + | ^ +... +LL | #[derive(B)] + | - the attribute is introduced here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #79202 + = note: `#[deny(legacy_derive_helpers)]` on by default + +Future breakage diagnostic: +error: derive helper attribute is used before it is introduced + --> $DIR/proc-macro-attributes.rs:13:3 + | +LL | #[B(E = "foo")] + | ^ +... +LL | #[derive(B)] + | - the attribute is introduced here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #79202 + = note: `#[deny(legacy_derive_helpers)]` on by default + +Future breakage diagnostic: +error: derive helper attribute is used before it is introduced + --> $DIR/proc-macro-attributes.rs:16:3 + | +LL | #[B(arbitrary tokens)] + | ^ +... +LL | #[derive(B)] + | - the attribute is introduced here + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #79202 + = note: `#[deny(legacy_derive_helpers)]` on by default + From 3e764d030a2a62066532c940e3509e7e031d71bf Mon Sep 17 00:00:00 2001 From: Shoyu Vanilla Date: Tue, 5 Aug 2025 00:29:13 +0900 Subject: [PATCH 29/30] Add regression tests for seemingly fixed issues --- .../const-closure-issue-125866-error.rs | 24 ++++++++++++++++++ .../const-closure-issue-125866-error.stderr | 11 ++++++++ .../const-closure-issue-125866-pass.rs | 25 +++++++++++++++++++ .../const-fn-trait-bound-issue-104314.rs | 13 ++++++++++ 4 files changed, 73 insertions(+) create mode 100644 tests/ui/traits/const-traits/const-closure-issue-125866-error.rs create mode 100644 tests/ui/traits/const-traits/const-closure-issue-125866-error.stderr create mode 100644 tests/ui/traits/const-traits/const-closure-issue-125866-pass.rs create mode 100644 tests/ui/traits/const-traits/const-fn-trait-bound-issue-104314.rs diff --git a/tests/ui/traits/const-traits/const-closure-issue-125866-error.rs b/tests/ui/traits/const-traits/const-closure-issue-125866-error.rs new file mode 100644 index 0000000000000..7a44920bb729d --- /dev/null +++ b/tests/ui/traits/const-traits/const-closure-issue-125866-error.rs @@ -0,0 +1,24 @@ +#![allow(incomplete_features)] +#![feature(const_closures, const_trait_impl)] + +const fn create_array(mut f: impl FnMut(usize) -> u32 + Copy) -> [u32; N] { + let mut array = [0; N]; + let mut i = 0; + loop { + array[i] = f(i); + //~^ ERROR the trait bound `impl FnMut(usize) -> u32 + Copy: [const] FnMut(usize)` is not satisfied [E0277] + i += 1; + if i == N { + break; + } + } + array +} + +fn main() { + let x = create_array(const |i| 2 * i as u32); + assert_eq!(x, [0, 2, 4, 6, 8]); + + let y = create_array(const |i| 2 * i as u32 + 1); + assert_eq!(y, [1, 3, 5, 7, 9]); +} diff --git a/tests/ui/traits/const-traits/const-closure-issue-125866-error.stderr b/tests/ui/traits/const-traits/const-closure-issue-125866-error.stderr new file mode 100644 index 0000000000000..1eadd1d842691 --- /dev/null +++ b/tests/ui/traits/const-traits/const-closure-issue-125866-error.stderr @@ -0,0 +1,11 @@ +error[E0277]: the trait bound `impl FnMut(usize) -> u32 + Copy: [const] FnMut(usize)` is not satisfied + --> $DIR/const-closure-issue-125866-error.rs:8:22 + | +LL | array[i] = f(i); + | - ^ + | | + | required by a bound introduced by this call + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/const-closure-issue-125866-pass.rs b/tests/ui/traits/const-traits/const-closure-issue-125866-pass.rs new file mode 100644 index 0000000000000..af7375172e674 --- /dev/null +++ b/tests/ui/traits/const-traits/const-closure-issue-125866-pass.rs @@ -0,0 +1,25 @@ +//@ check-pass + +#![allow(incomplete_features)] +#![feature(const_closures, const_trait_impl)] + +const fn create_array(mut f: impl [const] FnMut(usize) -> u32 + Copy) -> [u32; N] { + let mut array = [0; N]; + let mut i = 0; + loop { + array[i] = f(i); + i += 1; + if i == N { + break; + } + } + array +} + +fn main() { + let x = create_array(const |i| 2 * i as u32); + assert_eq!(x, [0, 2, 4, 6, 8]); + + let y = create_array(const |i| 2 * i as u32 + 1); + assert_eq!(y, [1, 3, 5, 7, 9]); +} diff --git a/tests/ui/traits/const-traits/const-fn-trait-bound-issue-104314.rs b/tests/ui/traits/const-traits/const-fn-trait-bound-issue-104314.rs new file mode 100644 index 0000000000000..09c89c9cecde7 --- /dev/null +++ b/tests/ui/traits/const-traits/const-fn-trait-bound-issue-104314.rs @@ -0,0 +1,13 @@ +//@ check-pass + +#![feature(const_trait_impl, const_destruct, const_clone)] + +use std::marker::Destruct; + +const fn f T + [const] Destruct>(_: F) {} + +const fn g() { + f(::clone); +} + +fn main() {} From b4d923cea0509933b1fb859930cb20784251f9be Mon Sep 17 00:00:00 2001 From: Sebastian Poeplau Date: Fri, 1 Aug 2025 13:22:06 +0200 Subject: [PATCH 30/30] Embed GDB pretty printers in rlibs and dylibs Instead of collecting pretty printers transitively when building executables/staticlibs/cdylibs, let the debugger find each crate's pretty printers via its .debug_gdb_scripts section. This covers the case where libraries defining custom pretty printers are loaded dynamically. --- .../rustc_codegen_llvm/src/debuginfo/gdb.rs | 43 +++++-------------- compiler/rustc_codegen_ssa/src/base.rs | 10 ++++- .../src/directives/directive_names.rs | 1 + tests/debuginfo/embedded-visualizer.rs | 2 + 4 files changed, 23 insertions(+), 33 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs index b3e978be5701f..fccd32dec9537 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs @@ -1,13 +1,13 @@ // .debug_gdb_scripts binary section. +use std::collections::BTreeSet; use std::ffi::CString; -use rustc_codegen_ssa::base::collect_debugger_visualizers_transitive; use rustc_codegen_ssa::traits::*; use rustc_hir::def_id::LOCAL_CRATE; use rustc_middle::bug; use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerType; -use rustc_session::config::{CrateType, DebugInfo}; +use rustc_session::config::DebugInfo; use crate::builder::Builder; use crate::common::CodegenCx; @@ -51,10 +51,14 @@ pub(crate) fn get_or_insert_gdb_debug_scripts_section_global<'ll>( // Next, add the pretty printers that were specified via the `#[debugger_visualizer]` // attribute. - let visualizers = collect_debugger_visualizers_transitive( - cx.tcx, - DebuggerVisualizerType::GdbPrettyPrinter, - ); + let visualizers = cx + .tcx + .debugger_visualizers(LOCAL_CRATE) + .iter() + .filter(|visualizer| { + visualizer.visualizer_type == DebuggerVisualizerType::GdbPrettyPrinter + }) + .collect::>(); let crate_name = cx.tcx.crate_name(LOCAL_CRATE); for (index, visualizer) in visualizers.iter().enumerate() { // The initial byte `4` instructs GDB that the following pretty printer @@ -91,30 +95,5 @@ pub(crate) fn get_or_insert_gdb_debug_scripts_section_global<'ll>( } pub(crate) fn needs_gdb_debug_scripts_section(cx: &CodegenCx<'_, '_>) -> bool { - // We collect pretty printers transitively for all crates, so we make sure - // that the section is only emitted for leaf crates. - let embed_visualizers = cx.tcx.crate_types().iter().any(|&crate_type| match crate_type { - CrateType::Executable | CrateType::Cdylib | CrateType::Staticlib | CrateType::Sdylib => { - // These are crate types for which we will embed pretty printers since they - // are treated as leaf crates. - true - } - CrateType::ProcMacro => { - // We could embed pretty printers for proc macro crates too but it does not - // seem like a good default, since this is a rare use case and we don't - // want to slow down the common case. - false - } - CrateType::Rlib | CrateType::Dylib => { - // Don't embed pretty printers for these crate types; the compiler - // can see the `#[debug_visualizer]` attributes when using the - // library, and emitting `.debug_gdb_scripts` regardless would - // break `#![omit_gdb_pretty_printer_section]`. - false - } - }); - - cx.sess().opts.debuginfo != DebugInfo::None - && cx.sess().target.emit_debug_gdb_scripts - && embed_visualizers + cx.sess().opts.debuginfo != DebugInfo::None && cx.sess().target.emit_debug_gdb_scripts } diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index eb21468650c76..b4556ced0b3fb 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -609,7 +609,15 @@ pub fn collect_debugger_visualizers_transitive( ) -> BTreeSet { tcx.debugger_visualizers(LOCAL_CRATE) .iter() - .chain(tcx.crates(()).iter().flat_map(|&cnum| tcx.debugger_visualizers(cnum))) + .chain( + tcx.crates(()) + .iter() + .filter(|&cnum| { + let used_crate_source = tcx.used_crate_source(*cnum); + used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some() + }) + .flat_map(|&cnum| tcx.debugger_visualizers(cnum)), + ) .filter(|visualizer| visualizer.visualizer_type == visualizer_type) .cloned() .collect::>() diff --git a/src/tools/compiletest/src/directives/directive_names.rs b/src/tools/compiletest/src/directives/directive_names.rs index f7955429d8369..099058bf0511a 100644 --- a/src/tools/compiletest/src/directives/directive_names.rs +++ b/src/tools/compiletest/src/directives/directive_names.rs @@ -68,6 +68,7 @@ pub(crate) const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "ignore-gnu", "ignore-haiku", "ignore-horizon", + "ignore-i586-unknown-linux-gnu", "ignore-i686-pc-windows-gnu", "ignore-i686-pc-windows-msvc", "ignore-illumos", diff --git a/tests/debuginfo/embedded-visualizer.rs b/tests/debuginfo/embedded-visualizer.rs index cbd8691394d54..12d87be7c66a0 100644 --- a/tests/debuginfo/embedded-visualizer.rs +++ b/tests/debuginfo/embedded-visualizer.rs @@ -1,6 +1,8 @@ //@ compile-flags:-g //@ ignore-lldb //@ ignore-windows-gnu: #128981 +//@ ignore-musl: linker too old in CI +//@ ignore-i586-unknown-linux-gnu: linker too old in CI // === CDB TESTS ==================================================================================