From a40804312a89bc69b8335912e169a14ab6ccb552 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 17 Mar 2025 12:10:43 +0100 Subject: [PATCH 01/11] add FCW to warn about wasm ABI transition --- compiler/rustc_lint_defs/src/builtin.rs | 46 ++++++++++ compiler/rustc_monomorphize/messages.ftl | 7 ++ compiler/rustc_monomorphize/src/errors.rs | 9 ++ .../src/mono_checks/abi_check.rs | 80 ++++++++++++++--- compiler/rustc_target/src/callconv/wasm.rs | 3 + tests/ui/abi/compatibility.rs | 1 - tests/ui/lint/wasm_c_abi_transition.rs | 41 +++++++++ tests/ui/lint/wasm_c_abi_transition.stderr | 85 +++++++++++++++++++ 8 files changed, 259 insertions(+), 13 deletions(-) create mode 100644 tests/ui/lint/wasm_c_abi_transition.rs create mode 100644 tests/ui/lint/wasm_c_abi_transition.stderr diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 592c934997c01..8a761a0a0969b 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -143,6 +143,7 @@ declare_lint_pass! { UNUSED_VARIABLES, USELESS_DEPRECATED, WARNINGS, + WASM_C_ABI, // tidy-alphabetical-end ] } @@ -5082,6 +5083,8 @@ declare_lint! { /// } /// ``` /// + /// This will produce: + /// /// ```text /// warning: ABI error: this function call uses a avx vector type, which is not enabled in the caller /// --> lint_example.rs:18:12 @@ -5125,3 +5128,46 @@ declare_lint! { reference: "issue #116558 ", }; } + +declare_lint! { + /// The `wasm_c_abi` lint detects usage of the `extern "C"` ABI of wasm that is affected + /// by a planned ABI change that has the goal of aligning Rust with the standard C ABI + /// of this target. + /// + /// ### Example + /// + /// ```rust,ignore (needs wasm32-unknown-unknown) + /// #[repr(C)] + /// struct MyType(i32, i32); + /// + /// extern "C" my_fun(x: MyType) {} + /// ``` + /// + /// This will produce: + /// + /// ```text + /// error: this function function definition is affected by the wasm ABI transition: it passes an argument of non-scalar type `MyType` + /// --> $DIR/wasm_c_abi_transition.rs:17:1 + /// | + /// | pub extern "C" fn my_fun(_x: MyType) {} + /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + /// | + /// = 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 #138762 + /// = help: the "C" ABI Rust uses on wasm32-unknown-unknown will change to align with the standard "C" ABI for this target + /// ``` + /// + /// ### Explanation + /// + /// Rust has historically implemented a non-spec-compliant C ABI on wasm32-unknown-unknown. This + /// has caused incompatibilities with other compilers and Wasm targets. In a future version + /// of Rust, this will be fixed, and therefore code relying on the non-spec-compliant C ABI will + /// stop functioning. + pub WASM_C_ABI, + Warn, + "detects code relying on rustc's non-spec-compliant wasm C ABI", + @future_incompatible = FutureIncompatibleInfo { + reason: FutureIncompatibilityReason::FutureReleaseErrorReportInDeps, + reference: "issue #138762 ", + }; +} diff --git a/compiler/rustc_monomorphize/messages.ftl b/compiler/rustc_monomorphize/messages.ftl index bdeab12ab503b..aae2d79c16109 100644 --- a/compiler/rustc_monomorphize/messages.ftl +++ b/compiler/rustc_monomorphize/messages.ftl @@ -63,4 +63,11 @@ monomorphize_symbol_already_defined = symbol `{$symbol}` is already defined monomorphize_unknown_cgu_collection_mode = unknown codegen-item collection mode '{$mode}', falling back to 'lazy' mode +monomorphize_wasm_c_abi_transition = + this function {$is_call -> + [true] call + *[false] definition + } involves an argument of type `{$ty}` which is affected by the wasm ABI transition + .help = the "C" ABI Rust uses on wasm32-unknown-unknown will change to align with the standard "C" ABI for this target + monomorphize_written_to_path = the full type name has been written to '{$path}' diff --git a/compiler/rustc_monomorphize/src/errors.rs b/compiler/rustc_monomorphize/src/errors.rs index 8dafbbca905f7..dffa372279f9f 100644 --- a/compiler/rustc_monomorphize/src/errors.rs +++ b/compiler/rustc_monomorphize/src/errors.rs @@ -103,3 +103,12 @@ pub(crate) struct AbiRequiredTargetFeature<'a> { /// Whether this is a problem at a call site or at a declaration. pub is_call: bool, } + +#[derive(LintDiagnostic)] +#[diag(monomorphize_wasm_c_abi_transition)] +#[help] +pub(crate) struct WasmCAbiTransition<'a> { + pub ty: Ty<'a>, + /// Whether this is a problem at a call site or at a declaration. + pub is_call: bool, +} diff --git a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs index 06d6c3ab8050e..f17f7261df58c 100644 --- a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs +++ b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs @@ -3,11 +3,13 @@ use rustc_abi::{BackendRepr, RegKind}; use rustc_hir::CRATE_HIR_ID; use rustc_middle::mir::{self, traversal}; -use rustc_middle::ty::{self, Instance, InstanceKind, Ty, TyCtxt}; -use rustc_session::lint::builtin::ABI_UNSUPPORTED_VECTOR_TYPES; +use rustc_middle::ty::layout::LayoutCx; +use rustc_middle::ty::{self, Instance, InstanceKind, Ty, TyCtxt, TypingEnv}; +use rustc_session::lint::builtin::{ABI_UNSUPPORTED_VECTOR_TYPES, WASM_C_ABI}; use rustc_span::def_id::DefId; use rustc_span::{DUMMY_SP, Span, Symbol, sym}; -use rustc_target::callconv::{Conv, FnAbi, PassMode}; +use rustc_target::callconv::{ArgAbi, Conv, FnAbi, PassMode}; +use rustc_target::spec::{HasWasmCAbiOpt, WasmCAbi}; use crate::errors; @@ -26,13 +28,15 @@ fn uses_vector_registers(mode: &PassMode, repr: &BackendRepr) -> bool { /// for a certain function. /// `is_call` indicates whether this is a call-site check or a definition-site check; /// this is only relevant for the wording in the emitted error. -fn do_check_abi<'tcx>( +fn do_check_simd_vector_abi<'tcx>( tcx: TyCtxt<'tcx>, abi: &FnAbi<'tcx, Ty<'tcx>>, def_id: DefId, is_call: bool, span: impl Fn() -> Span, ) { + // We check this on all functions, including those using the "Rust" ABI. + // For the "Rust" ABI it would be a bug if the lint ever triggered, but better safe than sorry. let feature_def = tcx.sess.target.features_for_correct_vector_abi(); let codegen_attrs = tcx.codegen_fn_attrs(def_id); let have_feature = |feat: Symbol| { @@ -88,6 +92,60 @@ fn do_check_abi<'tcx>( } } +fn wasm_abi_safe<'tcx>(tcx: TyCtxt<'tcx>, arg: &ArgAbi<'tcx, Ty<'tcx>>) -> bool { + if matches!(arg.layout.backend_repr, BackendRepr::Scalar(_)) { + return true; + } + + // This matches `unwrap_trivial_aggregate` in the wasm ABI logic. + if arg.layout.is_aggregate() { + let cx = LayoutCx::new(tcx, TypingEnv::fully_monomorphized()); + if let Some(unit) = arg.layout.homogeneous_aggregate(&cx).ok().and_then(|ha| ha.unit()) { + let size = arg.layout.size; + // Ensure there's just a single `unit` element in `arg`. + if unit.size == size { + return true; + } + } + } + + false +} + +/// Warns against usage of `extern "C"` on wasm32-unknown-unknown that is affected by the +/// ABI transition. +fn do_check_wasm_abi<'tcx>( + tcx: TyCtxt<'tcx>, + abi: &FnAbi<'tcx, Ty<'tcx>>, + is_call: bool, + span: impl Fn() -> Span, +) { + // Only proceed for `extern "C" fn` on wasm32-unknown-unknown (same check as what `adjust_for_foreign_abi` uses to call `compute_wasm_abi_info`). + if !(tcx.sess.target.arch == "wasm32" + && tcx.sess.target.os == "unknown" + && tcx.wasm_c_abi_opt() == WasmCAbi::Legacy + && abi.conv == Conv::C) + { + return; + } + // Warn against all types whose ABI will change. That's all arguments except for things passed as scalars. + // Return values are not affected by this change. + for arg_abi in abi.args.iter() { + if wasm_abi_safe(tcx, arg_abi) { + continue; + } + let span = span(); + tcx.emit_node_span_lint( + WASM_C_ABI, + CRATE_HIR_ID, + span, + errors::WasmCAbiTransition { ty: arg_abi.layout.ty, is_call }, + ); + // Let's only warn once per function. + break; + } +} + /// Checks that the ABI of a given instance of a function does not contain vector-passed arguments /// or return values for which the corresponding target feature is not enabled. fn check_instance_abi<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) { @@ -98,13 +156,10 @@ fn check_instance_abi<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) { // function. return; }; - do_check_abi( - tcx, - abi, - instance.def_id(), - /*is_call*/ false, - || tcx.def_span(instance.def_id()), - ) + do_check_simd_vector_abi(tcx, abi, instance.def_id(), /*is_call*/ false, || { + tcx.def_span(instance.def_id()) + }); + do_check_wasm_abi(tcx, abi, /*is_call*/ false, || tcx.def_span(instance.def_id())); } /// Checks that a call expression does not try to pass a vector-passed argument which requires a @@ -141,7 +196,8 @@ fn check_call_site_abi<'tcx>( // ABI failed to compute; this will not get through codegen. return; }; - do_check_abi(tcx, callee_abi, caller.def_id(), /*is_call*/ true, || span); + do_check_simd_vector_abi(tcx, callee_abi, caller.def_id(), /*is_call*/ true, || span); + do_check_wasm_abi(tcx, callee_abi, /*is_call*/ true, || span); } fn check_callees_abi<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>, body: &mir::Body<'tcx>) { diff --git a/compiler/rustc_target/src/callconv/wasm.rs b/compiler/rustc_target/src/callconv/wasm.rs index 364a655113114..881168c98c32e 100644 --- a/compiler/rustc_target/src/callconv/wasm.rs +++ b/compiler/rustc_target/src/callconv/wasm.rs @@ -10,6 +10,9 @@ where if val.layout.is_aggregate() { if let Some(unit) = val.layout.homogeneous_aggregate(cx).ok().and_then(|ha| ha.unit()) { let size = val.layout.size; + // This size check also catches over-aligned scalars as `size` will be rounded up to a + // multiple of the alignment, and the default alignment of all scalar types on wasm + // equals their size. if unit.size == size { val.cast_to(unit); return true; diff --git a/tests/ui/abi/compatibility.rs b/tests/ui/abi/compatibility.rs index 64e65ece85d68..be649029c8630 100644 --- a/tests/ui/abi/compatibility.rs +++ b/tests/ui/abi/compatibility.rs @@ -62,7 +62,6 @@ //@[nvptx64] needs-llvm-components: nvptx #![feature(no_core, rustc_attrs, lang_items)] #![feature(unsized_fn_params, transparent_unions)] -#![no_std] #![no_core] #![allow(unused, improper_ctypes_definitions, internal_features)] diff --git a/tests/ui/lint/wasm_c_abi_transition.rs b/tests/ui/lint/wasm_c_abi_transition.rs new file mode 100644 index 0000000000000..1fe81679e65d0 --- /dev/null +++ b/tests/ui/lint/wasm_c_abi_transition.rs @@ -0,0 +1,41 @@ +//@ compile-flags: --target wasm32-unknown-unknown +//@ needs-llvm-components: webassembly +//@ add-core-stubs +//@ build-fail + +#![feature(no_core)] +#![no_core] +#![crate_type = "lib"] +#![deny(wasm_c_abi)] + +extern crate minicore; +use minicore::*; + +pub extern "C" fn my_fun_trivial(_x: i32, _y: f32) {} + +#[repr(C)] +pub struct MyType(i32, i32); +pub extern "C" fn my_fun(_x: MyType) {} //~ERROR: wasm ABI transition +//~^WARN: previously accepted + +// This one is ABI-safe as it only wraps a single field, +// and the return type can be anything. +#[repr(C)] +pub struct MySafeType(i32); +pub extern "C" fn my_fun_safe(_x: MySafeType) -> MyType { loop {} } + +// This one not ABI-safe due to the alignment. +#[repr(C, align(16))] +pub struct MyAlignedType(i32); +pub extern "C" fn my_fun_aligned(_x: MyAlignedType) {} //~ERROR: wasm ABI transition +//~^WARN: previously accepted + +// Check call-site warning +extern "C" { + fn other_fun(x: MyType); +} + +pub fn call_other_fun(x: MyType) { + unsafe { other_fun(x) } //~ERROR: wasm ABI transition + //~^WARN: previously accepted +} diff --git a/tests/ui/lint/wasm_c_abi_transition.stderr b/tests/ui/lint/wasm_c_abi_transition.stderr new file mode 100644 index 0000000000000..389710d5cb3a2 --- /dev/null +++ b/tests/ui/lint/wasm_c_abi_transition.stderr @@ -0,0 +1,85 @@ +error: this function definition involves an argument of type `MyType` which is affected by the wasm ABI transition + --> $DIR/wasm_c_abi_transition.rs:18:1 + | +LL | pub extern "C" fn my_fun(_x: MyType) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = 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 #138762 + = help: the "C" ABI Rust uses on wasm32-unknown-unknown will change to align with the standard "C" ABI for this target +note: the lint level is defined here + --> $DIR/wasm_c_abi_transition.rs:9:9 + | +LL | #![deny(wasm_c_abi)] + | ^^^^^^^^^^ + +error: this function definition involves an argument of type `MyAlignedType` which is affected by the wasm ABI transition + --> $DIR/wasm_c_abi_transition.rs:30:1 + | +LL | pub extern "C" fn my_fun_aligned(_x: MyAlignedType) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = 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 #138762 + = help: the "C" ABI Rust uses on wasm32-unknown-unknown will change to align with the standard "C" ABI for this target + +error: this function call involves an argument of type `MyType` which is affected by the wasm ABI transition + --> $DIR/wasm_c_abi_transition.rs:39:14 + | +LL | unsafe { other_fun(x) } + | ^^^^^^^^^^^^ + | + = 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 #138762 + = help: the "C" ABI Rust uses on wasm32-unknown-unknown will change to align with the standard "C" ABI for this target + +error: aborting due to 3 previous errors + +Future incompatibility report: Future breakage diagnostic: +error: this function definition involves an argument of type `MyType` which is affected by the wasm ABI transition + --> $DIR/wasm_c_abi_transition.rs:18:1 + | +LL | pub extern "C" fn my_fun(_x: MyType) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = 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 #138762 + = help: the "C" ABI Rust uses on wasm32-unknown-unknown will change to align with the standard "C" ABI for this target +note: the lint level is defined here + --> $DIR/wasm_c_abi_transition.rs:9:9 + | +LL | #![deny(wasm_c_abi)] + | ^^^^^^^^^^ + +Future breakage diagnostic: +error: this function definition involves an argument of type `MyAlignedType` which is affected by the wasm ABI transition + --> $DIR/wasm_c_abi_transition.rs:30:1 + | +LL | pub extern "C" fn my_fun_aligned(_x: MyAlignedType) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = 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 #138762 + = help: the "C" ABI Rust uses on wasm32-unknown-unknown will change to align with the standard "C" ABI for this target +note: the lint level is defined here + --> $DIR/wasm_c_abi_transition.rs:9:9 + | +LL | #![deny(wasm_c_abi)] + | ^^^^^^^^^^ + +Future breakage diagnostic: +error: this function call involves an argument of type `MyType` which is affected by the wasm ABI transition + --> $DIR/wasm_c_abi_transition.rs:39:14 + | +LL | unsafe { other_fun(x) } + | ^^^^^^^^^^^^ + | + = 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 #138762 + = help: the "C" ABI Rust uses on wasm32-unknown-unknown will change to align with the standard "C" ABI for this target +note: the lint level is defined here + --> $DIR/wasm_c_abi_transition.rs:9:9 + | +LL | #![deny(wasm_c_abi)] + | ^^^^^^^^^^ + From 3301e0ea826ca58a199f09ed08b4d0e4d0f76990 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 17 Mar 2025 22:59:56 +0100 Subject: [PATCH 02/11] make -Zwasm-c-abi=legacy suppress the lint --- compiler/rustc_codegen_ssa/src/mir/naked_asm.rs | 4 ++-- compiler/rustc_monomorphize/src/mono_checks/abi_check.rs | 9 +++++---- compiler/rustc_session/src/options.rs | 5 +++-- compiler/rustc_target/src/callconv/mod.rs | 2 +- compiler/rustc_target/src/spec/mod.rs | 5 ++++- 5 files changed, 15 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/mir/naked_asm.rs b/compiler/rustc_codegen_ssa/src/mir/naked_asm.rs index bc9cde1b2a15f..3a6b1f8d4efc9 100644 --- a/compiler/rustc_codegen_ssa/src/mir/naked_asm.rs +++ b/compiler/rustc_codegen_ssa/src/mir/naked_asm.rs @@ -332,7 +332,7 @@ fn wasm_functype<'tcx>(tcx: TyCtxt<'tcx>, fn_abi: &FnAbi<'tcx, Ty<'tcx>>, def_id // please also add `wasm32-unknown-unknown` back in `tests/assembly/wasm32-naked-fn.rs` // basically the commit introducing this comment should be reverted if let PassMode::Pair { .. } = fn_abi.ret.mode { - let _ = WasmCAbi::Legacy; + let _ = WasmCAbi::Legacy { with_lint: true }; span_bug!( tcx.def_span(def_id), "cannot return a pair (the wasm32-unknown-unknown ABI is broken, see https://github.com/rust-lang/rust/issues/115666" @@ -384,7 +384,7 @@ fn wasm_type<'tcx>( BackendRepr::SimdVector { .. } => "v128", BackendRepr::Memory { .. } => { // FIXME: remove this branch once the wasm32-unknown-unknown ABI is fixed - let _ = WasmCAbi::Legacy; + let _ = WasmCAbi::Legacy { with_lint: true }; span_bug!( tcx.def_span(def_id), "cannot use memory args (the wasm32-unknown-unknown ABI is broken, see https://github.com/rust-lang/rust/issues/115666" diff --git a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs index f17f7261df58c..40740c3fdf652 100644 --- a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs +++ b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs @@ -92,6 +92,7 @@ fn do_check_simd_vector_abi<'tcx>( } } +/// Determines whether the given argument is passed the same way on the old and new wasm ABIs. fn wasm_abi_safe<'tcx>(tcx: TyCtxt<'tcx>, arg: &ArgAbi<'tcx, Ty<'tcx>>) -> bool { if matches!(arg.layout.backend_repr, BackendRepr::Scalar(_)) { return true; @@ -120,16 +121,16 @@ fn do_check_wasm_abi<'tcx>( is_call: bool, span: impl Fn() -> Span, ) { - // Only proceed for `extern "C" fn` on wasm32-unknown-unknown (same check as what `adjust_for_foreign_abi` uses to call `compute_wasm_abi_info`). + // Only proceed for `extern "C" fn` on wasm32-unknown-unknown (same check as what `adjust_for_foreign_abi` uses to call `compute_wasm_abi_info`), + // and only proceed if `wasm_c_abi_opt` indicates we should emit the lint. if !(tcx.sess.target.arch == "wasm32" && tcx.sess.target.os == "unknown" - && tcx.wasm_c_abi_opt() == WasmCAbi::Legacy + && tcx.wasm_c_abi_opt() == WasmCAbi::Legacy { with_lint: true } && abi.conv == Conv::C) { return; } - // Warn against all types whose ABI will change. That's all arguments except for things passed as scalars. - // Return values are not affected by this change. + // Warn against all types whose ABI will change. Return values are not affected by this change. for arg_abi in abi.args.iter() { if wasm_abi_safe(tcx, arg_abi) { continue; diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 804b46a9bec41..5988d97c3f297 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1886,7 +1886,8 @@ pub mod parse { pub(crate) fn parse_wasm_c_abi(slot: &mut WasmCAbi, v: Option<&str>) -> bool { match v { Some("spec") => *slot = WasmCAbi::Spec, - Some("legacy") => *slot = WasmCAbi::Legacy, + // Explicitly setting the `-Z` flag suppresses the lint. + Some("legacy") => *slot = WasmCAbi::Legacy { with_lint: false }, _ => return false, } true @@ -2599,7 +2600,7 @@ written to standard error output)"), Requires `-Clto[=[fat,yes]]`"), wasi_exec_model: Option = (None, parse_wasi_exec_model, [TRACKED], "whether to build a wasi command or reactor"), - wasm_c_abi: WasmCAbi = (WasmCAbi::Legacy, parse_wasm_c_abi, [TRACKED], + wasm_c_abi: WasmCAbi = (WasmCAbi::Legacy { with_lint: true }, parse_wasm_c_abi, [TRACKED], "use spec-compliant C ABI for `wasm32-unknown-unknown` (default: legacy)"), write_long_types_to_disk: bool = (true, parse_bool, [UNTRACKED], "whether long type names should be written to files instead of being printed in errors"), diff --git a/compiler/rustc_target/src/callconv/mod.rs b/compiler/rustc_target/src/callconv/mod.rs index 6d0ee3c7ee58a..a52b2b76bc1ee 100644 --- a/compiler/rustc_target/src/callconv/mod.rs +++ b/compiler/rustc_target/src/callconv/mod.rs @@ -705,7 +705,7 @@ impl<'a, Ty> FnAbi<'a, Ty> { "xtensa" => xtensa::compute_abi_info(cx, self), "riscv32" | "riscv64" => riscv::compute_abi_info(cx, self), "wasm32" => { - if spec.os == "unknown" && cx.wasm_c_abi_opt() == WasmCAbi::Legacy { + if spec.os == "unknown" && matches!(cx.wasm_c_abi_opt(), WasmCAbi::Legacy { .. }) { wasm::compute_wasm_abi_info(self) } else { wasm::compute_c_abi_info(cx, self) diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 1887134c5757d..1a823f47d9d92 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -2234,7 +2234,10 @@ pub enum WasmCAbi { /// Spec-compliant C ABI. Spec, /// Legacy ABI. Which is non-spec-compliant. - Legacy, + Legacy { + /// Indicates whether the `wasm_c_abi` lint should be emitted. + with_lint: bool, + }, } pub trait HasWasmCAbiOpt { From 7b9d5b8758589db0cda82be95e43f41be48e9311 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 21 Mar 2025 21:02:06 +0100 Subject: [PATCH 03/11] remove remnants of const_box feature --- library/alloc/src/boxed.rs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index e77caad65401b..4644e37f809c1 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -1149,9 +1149,8 @@ impl Box { /// /// [memory layout]: self#memory-layout #[unstable(feature = "allocator_api", issue = "32838")] - #[rustc_const_unstable(feature = "const_box", issue = "92521")] #[inline] - pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self { + pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self { Box(unsafe { Unique::new_unchecked(raw) }, alloc) } @@ -1203,9 +1202,8 @@ impl Box { /// [memory layout]: self#memory-layout #[unstable(feature = "allocator_api", issue = "32838")] // #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")] - #[rustc_const_unstable(feature = "const_box", issue = "92521")] #[inline] - pub const unsafe fn from_non_null_in(raw: NonNull, alloc: A) -> Self { + pub unsafe fn from_non_null_in(raw: NonNull, alloc: A) -> Self { // SAFETY: guaranteed by the caller. unsafe { Box::from_raw_in(raw.as_ptr(), alloc) } } @@ -1550,9 +1548,8 @@ impl Box { /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This /// is so that there is no conflict with a method on the inner type. #[unstable(feature = "allocator_api", issue = "32838")] - #[rustc_const_unstable(feature = "const_box", issue = "92521")] #[inline] - pub const fn allocator(b: &Self) -> &A { + pub fn allocator(b: &Self) -> &A { &b.1 } @@ -1639,8 +1636,7 @@ impl Box { /// let bar = Pin::from(foo); /// ``` #[stable(feature = "box_into_pin", since = "1.63.0")] - #[rustc_const_unstable(feature = "const_box", issue = "92521")] - pub const fn into_pin(boxed: Self) -> Pin + pub fn into_pin(boxed: Self) -> Pin where A: 'static, { From 83145a674444c15e61f1b4fb7043e8cdc4a62ea3 Mon Sep 17 00:00:00 2001 From: dianne Date: Fri, 21 Mar 2025 19:52:53 -0700 Subject: [PATCH 04/11] match lowering cleanup: `non_scalar_compare` is only for `&str` Since array and slice constants are now lowered to array and slice patterns, `non_scalar_compare` was only called for string comparisons. This specializes it to strings, renames it, and removes the unused array-unsizing logic. This also updates some outdated doc comments. --- compiler/rustc_middle/src/thir.rs | 6 +- .../src/builder/matches/mod.rs | 4 +- .../src/builder/matches/test.rs | 108 +++--------------- 3 files changed, 24 insertions(+), 94 deletions(-) diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index bbcd509c55869..6783bbf8bf42f 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -800,9 +800,9 @@ pub enum PatKind<'tcx> { }, /// One of the following: - /// * `&str`/`&[u8]` (represented as a valtree), which will be handled as a string/slice pattern - /// and thus exhaustiveness checking will detect if you use the same string/slice twice in - /// different patterns. + /// * `&str` (represented as a valtree), which will be handled as a string pattern and thus + /// exhaustiveness checking will detect if you use the same string twice in different + /// patterns. /// * integer, bool, char or float (represented as a valtree), which will be handled by /// exhaustiveness to cover exactly its own value, similar to `&str`, but these values are /// much simpler. diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index ea341b604e0be..710538ef4b867 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -1326,8 +1326,8 @@ enum TestKind<'tcx> { Eq { value: Const<'tcx>, // Integer types are handled by `SwitchInt`, and constants with ADT - // types are converted back into patterns, so this can only be `&str`, - // `&[T]`, `f32` or `f64`. + // types and `&[T]` types are converted back into patterns, so this can + // only be `&str`, `f32` or `f64`. ty: Ty<'tcx>, }, diff --git a/compiler/rustc_mir_build/src/builder/matches/test.rs b/compiler/rustc_mir_build/src/builder/matches/test.rs index e5d61bc9e556a..7ef9e48326f63 100644 --- a/compiler/rustc_mir_build/src/builder/matches/test.rs +++ b/compiler/rustc_mir_build/src/builder/matches/test.rs @@ -11,7 +11,6 @@ use std::sync::Arc; use rustc_data_structures::fx::FxIndexMap; use rustc_hir::{LangItem, RangeEnd}; use rustc_middle::mir::*; -use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, GenericArg, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; @@ -178,21 +177,30 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { _ => {} } + assert_eq!(expect_ty, ty); if !ty.is_scalar() { // Use `PartialEq::eq` instead of `BinOp::Eq` // (the binop can only handle primitives) - self.non_scalar_compare( + // Make sure that we do *not* call any user-defined code here. + // The only type that can end up here is string literals, which have their + // comparison defined in `core`. + // (Interestingly this means that exhaustiveness analysis relies, for soundness, + // on the `PartialEq` impl for `str` to b correct!) + match *ty.kind() { + ty::Ref(_, deref_ty, _) if deref_ty == self.tcx.types.str_ => {} + _ => { + span_bug!(source_info.span, "invalid type for non-scalar compare: {ty}") + } + }; + self.string_compare( block, success_block, fail_block, source_info, expect, - expect_ty, Operand::Copy(place), - ty, ); } else { - assert_eq!(expect_ty, ty); self.compare( block, success_block, @@ -370,97 +378,19 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); } - /// Compare two values using `::eq`. - /// If the values are already references, just call it directly, otherwise - /// take a reference to the values first and then call it. - fn non_scalar_compare( + /// Compare two values of type `&str` using `::eq`. + fn string_compare( &mut self, block: BasicBlock, success_block: BasicBlock, fail_block: BasicBlock, source_info: SourceInfo, - mut expect: Operand<'tcx>, - expect_ty: Ty<'tcx>, - mut val: Operand<'tcx>, - mut ty: Ty<'tcx>, + expect: Operand<'tcx>, + val: Operand<'tcx>, ) { - // If we're using `b"..."` as a pattern, we need to insert an - // unsizing coercion, as the byte string has the type `&[u8; N]`. - // - // We want to do this even when the scrutinee is a reference to an - // array, so we can call `<[u8]>::eq` rather than having to find an - // `<[u8; N]>::eq`. - let unsize = |ty: Ty<'tcx>| match ty.kind() { - ty::Ref(region, rty, _) => match rty.kind() { - ty::Array(inner_ty, n) => Some((region, inner_ty, n)), - _ => None, - }, - _ => None, - }; - let opt_ref_ty = unsize(ty); - let opt_ref_test_ty = unsize(expect_ty); - match (opt_ref_ty, opt_ref_test_ty) { - // nothing to do, neither is an array - (None, None) => {} - (Some((region, elem_ty, _)), _) | (None, Some((region, elem_ty, _))) => { - let tcx = self.tcx; - // make both a slice - ty = Ty::new_imm_ref(tcx, *region, Ty::new_slice(tcx, *elem_ty)); - if opt_ref_ty.is_some() { - let temp = self.temp(ty, source_info.span); - self.cfg.push_assign( - block, - source_info, - temp, - Rvalue::Cast( - CastKind::PointerCoercion( - PointerCoercion::Unsize, - CoercionSource::Implicit, - ), - val, - ty, - ), - ); - val = Operand::Copy(temp); - } - if opt_ref_test_ty.is_some() { - let slice = self.temp(ty, source_info.span); - self.cfg.push_assign( - block, - source_info, - slice, - Rvalue::Cast( - CastKind::PointerCoercion( - PointerCoercion::Unsize, - CoercionSource::Implicit, - ), - expect, - ty, - ), - ); - expect = Operand::Move(slice); - } - } - } - - // Figure out the type on which we are calling `PartialEq`. This involves an extra wrapping - // reference: we can only compare two `&T`, and then compare_ty will be `T`. - // Make sure that we do *not* call any user-defined code here. - // The only types that can end up here are string and byte literals, - // which have their comparison defined in `core`. - // (Interestingly this means that exhaustiveness analysis relies, for soundness, - // on the `PartialEq` impls for `str` and `[u8]` to b correct!) - let compare_ty = match *ty.kind() { - ty::Ref(_, deref_ty, _) - if deref_ty == self.tcx.types.str_ || deref_ty != self.tcx.types.u8 => - { - deref_ty - } - _ => span_bug!(source_info.span, "invalid type for non-scalar compare: {}", ty), - }; - + let str_ty = self.tcx.types.str_; let eq_def_id = self.tcx.require_lang_item(LangItem::PartialEq, Some(source_info.span)); - let method = trait_method(self.tcx, eq_def_id, sym::eq, [compare_ty, compare_ty]); + let method = trait_method(self.tcx, eq_def_id, sym::eq, [str_ty, str_ty]); let bool_ty = self.tcx.types.bool; let eq_result = self.temp(bool_ty, source_info.span); From a75a841fcc800905443ed20018d54768ccb3149f Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 22 Mar 2025 18:42:01 +0100 Subject: [PATCH 05/11] allow wasm_c_abi in proc_macro bridge --- library/proc_macro/src/bridge/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/library/proc_macro/src/bridge/mod.rs b/library/proc_macro/src/bridge/mod.rs index 03c3e697cfe2b..f0e37f3ca6cae 100644 --- a/library/proc_macro/src/bridge/mod.rs +++ b/library/proc_macro/src/bridge/mod.rs @@ -7,6 +7,10 @@ //! Rust ABIs (e.g., stage0/bin/rustc vs stage1/bin/rustc during bootstrap). #![deny(unsafe_code)] +// We rely on both sides of the bridge to be built with the same rustc, +// so that the wasm ABI transition will not affect us. +#![cfg_attr(bootstrap, allow(unknown_lints))] +#![allow(wasm_c_abi)] use std::hash::Hash; use std::ops::{Bound, Range}; From 7210df1a9ac3cec2e925012bcc9190c13b5a2402 Mon Sep 17 00:00:00 2001 From: Urgau Date: Sun, 23 Mar 2025 18:45:34 +0100 Subject: [PATCH 06/11] Rework `--print` options documentation --- src/doc/rustc/src/SUMMARY.md | 1 + src/doc/rustc/src/command-line-arguments.md | 53 +---- .../command-line-arguments/print-options.md | 212 ++++++++++++++++++ 3 files changed, 214 insertions(+), 52 deletions(-) create mode 100644 src/doc/rustc/src/command-line-arguments/print-options.md diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md index 542ee9fffce3a..e258b0a76ffd9 100644 --- a/src/doc/rustc/src/SUMMARY.md +++ b/src/doc/rustc/src/SUMMARY.md @@ -2,6 +2,7 @@ - [What is rustc?](what-is-rustc.md) - [Command-line Arguments](command-line-arguments.md) + - [Print Options](command-line-arguments/print-options.md) - [Codegen Options](codegen-options/index.md) - [Jobserver](jobserver.md) - [Lints](lints/index.md) diff --git a/src/doc/rustc/src/command-line-arguments.md b/src/doc/rustc/src/command-line-arguments.md index 9dd2e7de1b330..b704cee705b05 100644 --- a/src/doc/rustc/src/command-line-arguments.md +++ b/src/doc/rustc/src/command-line-arguments.md @@ -247,58 +247,7 @@ types to stdout at the same time will result in an error. ## `--print`: print compiler information -This flag prints out various information about the compiler. This flag may be -specified multiple times, and the information is printed in the order the -flags are specified. Specifying a `--print` flag will usually disable the -[`--emit`](#option-emit) step and will only print the requested information. -The valid types of print values are: - -- `crate-name` — The name of the crate. -- `file-names` — The names of the files created by the `link` emit kind. -- `sysroot` — Path to the sysroot. -- `target-libdir` — Path to the target libdir. -- `host-tuple` — The target-tuple string of the host compiler (e.g. `x86_64-unknown-linux-gnu`) -- `cfg` — List of cfg values. See [conditional compilation] for more - information about cfg values. -- `target-list` — List of known targets. The target may be selected with the - `--target` flag. -- `target-cpus` — List of available CPU values for the current target. The - target CPU may be selected with the [`-C target-cpu=val` - flag](codegen-options/index.md#target-cpu). -- `target-features` — List of available target features for the current - target. Target features may be enabled with the [`-C target-feature=val` - flag](codegen-options/index.md#target-feature). This flag is unsafe. See - [known issues](targets/known-issues.md) for more details. -- `relocation-models` — List of relocation models. Relocation models may be - selected with the [`-C relocation-model=val` - flag](codegen-options/index.md#relocation-model). -- `code-models` — List of code models. Code models may be selected with the - [`-C code-model=val` flag](codegen-options/index.md#code-model). -- `tls-models` — List of Thread Local Storage models supported. The model may - be selected with the `-Z tls-model=val` flag. -- `native-static-libs` — This may be used when creating a `staticlib` crate - type. If this is the only flag, it will perform a full compilation and - include a diagnostic note that indicates the linker flags to use when - linking the resulting static library. The note starts with the text - `native-static-libs:` to make it easier to fetch the output. -- `link-args` — This flag does not disable the `--emit` step. When linking, - this flag causes `rustc` to print the full linker invocation in a - human-readable form. This can be useful when debugging linker options. The - exact format of this debugging output is not a stable guarantee, other than - that it will include the linker executable and the text of each command-line - argument passed to the linker. -- `deployment-target` — The currently selected [deployment target] (or minimum OS version) - for the selected Apple platform target. This value can be used or passed along to other - components alongside a Rust build that need this information, such as C compilers. - This returns rustc's minimum supported deployment target if no `*_DEPLOYMENT_TARGET` variable - is present in the environment, or otherwise returns the variable's parsed value. - -A filepath may optionally be specified for each requested information kind, in -the format `--print KIND=PATH`, just like for `--emit`. When a path is -specified, information will be written there instead of to stdout. - -[conditional compilation]: ../reference/conditional-compilation.html -[deployment target]: https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/cross_development/Configuring/configuring.html +This flag will allow you to set [print options](command-line-arguments/print-options.md). ## `-g`: include debug information diff --git a/src/doc/rustc/src/command-line-arguments/print-options.md b/src/doc/rustc/src/command-line-arguments/print-options.md new file mode 100644 index 0000000000000..1f33e91e5d1b6 --- /dev/null +++ b/src/doc/rustc/src/command-line-arguments/print-options.md @@ -0,0 +1,212 @@ +# Print Options + +All of these options are passed to `rustc` via the `--print` flag. + +Those options prints out various information about the compiler. Multiple options can be +specified, and the information is printed in the order the options are specified. + +Specifying an option will usually disable the [`--emit`](../command-line-arguments.md#option-emit) +step and will only print the requested information. + +A filepath may optionally be specified for each requested information kind, in the format +`--print KIND=PATH`, just like for `--emit`. When a path is specified, information will be +written there instead of to stdout. + +## `crate-name` + +The name of the crate. + +Generally coming from either from the `#![crate_name = "..."]` attribute, +[`--crate-name` flag](../command-line-arguments.md#option-crate-name) or the filename. + +Example: + +```bash +$ rustc --print crate-name --crate-name my_crate a.rs +my_crate +``` + +## `file-names` + +The names of the files created by the `link` emit kind. + +## `sysroot` + +Abosulte path to the sysroot. + +Example (with rustup and the stable toolchain): + +```bash +$ rustc --print sysroot a.rs +/home/[REDACTED]/.rustup/toolchains/stable-x86_64-unknown-linux-gnu +``` + +## `target-libdir` + +Path to the target libdir. + +Example (with rustup and the stable toolchain): + +```bash +$ rustc --print target-libdir a.rs +/home/[REDACTED]/.rustup/toolchains/beta-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib +``` + +## `host-tuple` + +The target-tuple string of the host compiler. + +Example: + +```bash +$ rustc --print host-tuple a.rs +x86_64-unknown-linux-gnu +``` + +Example with the `--target` flag: + +```bash +$ rustc --print host-tuple --target "armv7-unknown-linux-gnueabihf" a.rs +x86_64-unknown-linux-gnu +``` + +## `cfg` + +List of cfg values. See [conditional compilation] for more information about cfg values. + +Example (for `x86_64-unknown-linux-gnu`): + +```bash +$ rustc --print cfg a.rs +debug_assertions +panic="unwind" +target_abi="" +target_arch="x86_64" +target_endian="little" +target_env="gnu" +target_family="unix" +target_feature="fxsr" +target_feature="sse" +target_feature="sse2" +target_has_atomic="16" +target_has_atomic="32" +target_has_atomic="64" +target_has_atomic="8" +target_has_atomic="ptr" +target_os="linux" +target_pointer_width="64" +target_vendor="unknown" +unix +``` + +## `target-list` + +List of known targets. The target may be selected with the `--target` flag. + +## `target-cpus` + +List of available CPU values for the current target. The target CPU may be selected with +the [`-C target-cpu=val` flag](../codegen-options/index.md#target-cpu). + +## `target-features` + +List of available target features for the *current target*. + +Target features may be enabled with the **unsafe** +[`-C target-feature=val` flag](../codegen-options/index.md#target-feature). + +See [known issues](../targets/known-issues.md) for more details. + +## `relocation-models` + +List of relocation models. Relocation models may be selected with the +[`-C relocation-model=val` flag](../codegen-options/index.md#relocation-model). + +Example: + +```bash +$ rustc --print relocation-models a.rs +Available relocation models: + static + pic + pie + dynamic-no-pic + ropi + rwpi + ropi-rwpi + default +``` + +## `code-models` + +List of code models. Code models may be selected with the +[`-C code-model=val` flag](../codegen-options/index.md#code-model). + +Example: + +```bash +$ rustc --print code-models a.rs +Available code models: + tiny + small + kernel + medium + large +``` + +## `tls-models` + +List of Thread Local Storage models supported. The model may be selected with the +`-Z tls-model=val` flag. + +Example: + +```bash +$ rustc --print tls-models a.rs +Available TLS models: + global-dynamic + local-dynamic + initial-exec + local-exec + emulated +``` + +## `native-static-libs` + +This may be used when creating a `staticlib` crate type. + +If this is the only flag, it will perform a full compilation and include a diagnostic note +that indicates the linker flags to use when linking the resulting static library. + +The note starts with the text `native-static-libs:` to make it easier to fetch the output. + +Example: + +```bash +$ rustc --print native-static-libs --crate-type staticlib a.rs +note: Link against the following native artifacts when linking against this static library. The order and any duplication can be significant on some platforms. + +note: native-static-libs: -lgcc_s -lutil [REDACTED] -lpthread -lm -ldl -lc +``` + +## `link-args` + +This flag does not disable the `--emit` step. This can be useful when debugging linker options. + +When linking, this flag causes `rustc` to print the full linker invocation in a human-readable +form. The exact format of this debugging output is not a stable guarantee, other than that it +will include the linker executable and the text of each command-line argument passed to the +linker. + +## `deployment-target` + +The currently selected [deployment target] (or minimum OS version) for the selected Apple +platform target. + +This value can be used or passed along to other components alongside a Rust build that need +this information, such as C compilers. This returns rustc's minimum supported deployment target +if no `*_DEPLOYMENT_TARGET` variable is present in the environment, or otherwise returns the +variable's parsed value. + +[conditional compilation]: ../../reference/conditional-compilation.html +[deployment target]: https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/cross_development/Configuring/configuring.html From f390dd7911561f4d377a51c7ef2f423d0e484ea0 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Mon, 24 Mar 2025 01:02:07 +0100 Subject: [PATCH 07/11] Add do_not_recommend typo help --- compiler/rustc_resolve/src/macros.rs | 14 +++++++------- tests/ui/diagnostic_namespace/suggest_typos.rs | 5 +++++ tests/ui/diagnostic_namespace/suggest_typos.stderr | 14 +++++++++++++- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index c4304a7a6df6a..34441d313f59f 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -28,7 +28,7 @@ use rustc_session::lint::builtin::{ UNUSED_MACRO_RULES, UNUSED_MACROS, }; use rustc_session::parse::feature_err; -use rustc_span::edit_distance::edit_distance; +use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::edition::Edition; use rustc_span::hygiene::{self, AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind}; use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym}; @@ -652,13 +652,13 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { if res == Res::NonMacroAttr(NonMacroAttrKind::Tool) && let [namespace, attribute, ..] = &*path.segments && namespace.ident.name == sym::diagnostic - && !(attribute.ident.name == sym::on_unimplemented - || attribute.ident.name == sym::do_not_recommend) + && ![sym::on_unimplemented, sym::do_not_recommend].contains(&attribute.ident.name) { - let distance = - edit_distance(attribute.ident.name.as_str(), sym::on_unimplemented.as_str(), 5); - - let typo_name = distance.map(|_| sym::on_unimplemented); + let typo_name = find_best_match_for_name( + &[sym::on_unimplemented, sym::do_not_recommend], + attribute.ident.name, + Some(5), + ); self.tcx.sess.psess.buffer_lint( UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, diff --git a/tests/ui/diagnostic_namespace/suggest_typos.rs b/tests/ui/diagnostic_namespace/suggest_typos.rs index 6fa4f800462fd..8d1dc6f59da97 100644 --- a/tests/ui/diagnostic_namespace/suggest_typos.rs +++ b/tests/ui/diagnostic_namespace/suggest_typos.rs @@ -16,4 +16,9 @@ trait Y{} //~^^HELP an attribute with a similar name exists trait Z{} +#[diagnostic::dont_recommend] +//~^ERROR unknown diagnostic attribute +//~^^HELP an attribute with a similar name exists +impl X for u8 {} + fn main(){} diff --git a/tests/ui/diagnostic_namespace/suggest_typos.stderr b/tests/ui/diagnostic_namespace/suggest_typos.stderr index 86d778c6ec05b..1f19fd4bbcf51 100644 --- a/tests/ui/diagnostic_namespace/suggest_typos.stderr +++ b/tests/ui/diagnostic_namespace/suggest_typos.stderr @@ -37,5 +37,17 @@ help: an attribute with a similar name exists LL | #[diagnostic::on_unimplemented] | ++ -error: aborting due to 3 previous errors +error: unknown diagnostic attribute + --> $DIR/suggest_typos.rs:19:15 + | +LL | #[diagnostic::dont_recommend] + | ^^^^^^^^^^^^^^ + | +help: an attribute with a similar name exists + | +LL - #[diagnostic::dont_recommend] +LL + #[diagnostic::do_not_recommend] + | + +error: aborting due to 4 previous errors From 0cd1d516aee85608a695d0376cdef059cc50e00a Mon Sep 17 00:00:00 2001 From: Ayush Singh Date: Tue, 18 Mar 2025 18:09:22 +0530 Subject: [PATCH 08/11] std: fs: uefi: Implement canonicalize - Should be same as absolute in UEFI since there are no symlinks. - Also each absolute path representation should be unique according to the UEFI specification. Signed-off-by: Ayush Singh --- library/std/src/sys/fs/uefi.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/std/src/sys/fs/uefi.rs b/library/std/src/sys/fs/uefi.rs index 54acd4c27b334..f7c33b7c40f0a 100644 --- a/library/std/src/sys/fs/uefi.rs +++ b/library/std/src/sys/fs/uefi.rs @@ -315,8 +315,8 @@ pub fn lstat(_p: &Path) -> io::Result { unsupported() } -pub fn canonicalize(_p: &Path) -> io::Result { - unsupported() +pub fn canonicalize(p: &Path) -> io::Result { + crate::path::absolute(p) } pub fn copy(_from: &Path, _to: &Path) -> io::Result { From fc0cf52e28cdbc5de45b650797365c91d0c8de76 Mon Sep 17 00:00:00 2001 From: Ayush Singh Date: Tue, 18 Mar 2025 18:11:18 +0530 Subject: [PATCH 09/11] std: fs: uefi: Make lstat call stat - UEFI does not have symlinks. So lstat and stat should behave the same. Signed-off-by: Ayush Singh --- library/std/src/sys/fs/uefi.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/std/src/sys/fs/uefi.rs b/library/std/src/sys/fs/uefi.rs index f7c33b7c40f0a..e1d61aaa309ea 100644 --- a/library/std/src/sys/fs/uefi.rs +++ b/library/std/src/sys/fs/uefi.rs @@ -311,8 +311,8 @@ pub fn stat(_p: &Path) -> io::Result { unsupported() } -pub fn lstat(_p: &Path) -> io::Result { - unsupported() +pub fn lstat(p: &Path) -> io::Result { + stat(p) } pub fn canonicalize(p: &Path) -> io::Result { From 021d23b64ee58b6d4d7f8803729182ad02a567c2 Mon Sep 17 00:00:00 2001 From: Ayush Singh Date: Tue, 18 Mar 2025 18:26:00 +0530 Subject: [PATCH 10/11] std: fs: uefi: Implement OpenOptions UEFI does not have specific modes for create_new, truncate and append. So those need to to be simulated after opening the file. Signed-off-by: Ayush Singh --- library/std/src/sys/fs/uefi.rs | 66 +++++++++++++++++++++++++++++----- 1 file changed, 58 insertions(+), 8 deletions(-) diff --git a/library/std/src/sys/fs/uefi.rs b/library/std/src/sys/fs/uefi.rs index e1d61aaa309ea..d6ae86bd3d26e 100644 --- a/library/std/src/sys/fs/uefi.rs +++ b/library/std/src/sys/fs/uefi.rs @@ -1,3 +1,5 @@ +use r_efi::protocols::file; + use crate::ffi::OsString; use crate::fmt; use crate::hash::Hash; @@ -22,7 +24,12 @@ pub struct ReadDir(!); pub struct DirEntry(!); #[derive(Clone, Debug)] -pub struct OpenOptions {} +pub struct OpenOptions { + mode: u64, + append: bool, + truncate: bool, + create_new: bool, +} #[derive(Copy, Clone, Debug, Default)] pub struct FileTimes {} @@ -141,15 +148,58 @@ impl DirEntry { impl OpenOptions { pub fn new() -> OpenOptions { - OpenOptions {} + OpenOptions { mode: 0, append: false, create_new: false, truncate: false } + } + + pub fn read(&mut self, read: bool) { + if read { + self.mode |= file::MODE_READ; + } else { + self.mode &= !file::MODE_READ; + } + } + + pub fn write(&mut self, write: bool) { + if write { + // Valid Combinations: Read, Read/Write, Read/Write/Create + self.read(true); + self.mode |= file::MODE_WRITE; + } else { + self.mode &= !file::MODE_WRITE; + } + } + + pub fn append(&mut self, append: bool) { + // Docs state that `.write(true).append(true)` has the same effect as `.append(true)` + if append { + self.write(true); + } + self.append = append; + } + + pub fn truncate(&mut self, truncate: bool) { + self.truncate = truncate; + } + + pub fn create(&mut self, create: bool) { + if create { + self.mode |= file::MODE_CREATE; + } else { + self.mode &= !file::MODE_CREATE; + } + } + + pub fn create_new(&mut self, create_new: bool) { + self.create_new = create_new; } - pub fn read(&mut self, _read: bool) {} - pub fn write(&mut self, _write: bool) {} - pub fn append(&mut self, _append: bool) {} - pub fn truncate(&mut self, _truncate: bool) {} - pub fn create(&mut self, _create: bool) {} - pub fn create_new(&mut self, _create_new: bool) {} + #[expect(dead_code)] + const fn is_mode_valid(&self) -> bool { + // Valid Combinations: Read, Read/Write, Read/Write/Create + self.mode == file::MODE_READ + || self.mode == (file::MODE_READ | file::MODE_WRITE) + || self.mode == (file::MODE_READ | file::MODE_WRITE | file::MODE_CREATE) + } } impl File { From 2d3115f61f40b43855bbf252cfb1f4d480c1ccc9 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 24 Mar 2025 09:39:02 +0000 Subject: [PATCH 11/11] `with_scope` is only ever used for ast modules --- compiler/rustc_resolve/src/late.rs | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 6056a69ee71f6..e04d0083548b1 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -1544,20 +1544,17 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { ret } - fn with_scope(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { - if let Some(module) = self.r.get_module(self.r.local_def_id(id).to_def_id()) { - // Move down in the graph. - let orig_module = replace(&mut self.parent_scope.module, module); - self.with_rib(ValueNS, RibKind::Module(module), |this| { - this.with_rib(TypeNS, RibKind::Module(module), |this| { - let ret = f(this); - this.parent_scope.module = orig_module; - ret - }) + fn with_mod_rib(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { + let module = self.r.expect_module(self.r.local_def_id(id).to_def_id()); + // Move down in the graph. + let orig_module = replace(&mut self.parent_scope.module, module); + self.with_rib(ValueNS, RibKind::Module(module), |this| { + this.with_rib(TypeNS, RibKind::Module(module), |this| { + let ret = f(this); + this.parent_scope.module = orig_module; + ret }) - } else { - f(self) - } + }) } fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) { @@ -2738,7 +2735,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { } ItemKind::Mod(..) => { - self.with_scope(item.id, |this| { + self.with_mod_rib(item.id, |this| { if mod_inner_docs { this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id)); }