From 60ee6fbaa464d4d65313a7919c07113ef6068140 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 31 Oct 2024 11:39:45 +0100 Subject: [PATCH 001/266] Update tests. --- example/mini_core.rs | 2 +- example/mini_core_hello_world.rs | 4 ++-- example/mod_bench.rs | 2 +- example/std_example.rs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/example/mini_core.rs b/example/mini_core.rs index cdd151613df84..685e03c07c189 100644 --- a/example/mini_core.rs +++ b/example/mini_core.rs @@ -681,7 +681,7 @@ impl Index for [T] { } } -extern { +extern "C" { type VaListImpl; } diff --git a/example/mini_core_hello_world.rs b/example/mini_core_hello_world.rs index dcfa34cb729d8..1d51e0a1856ba 100644 --- a/example/mini_core_hello_world.rs +++ b/example/mini_core_hello_world.rs @@ -258,13 +258,13 @@ fn main() { assert_eq!(((|()| 42u8) as fn(()) -> u8)(()), 42); - extern { + extern "C" { #[linkage = "weak"] static ABC: *const u8; } { - extern { + extern "C" { #[linkage = "weak"] static ABC: *const u8; } diff --git a/example/mod_bench.rs b/example/mod_bench.rs index cae911c1073d5..e8a9cade74745 100644 --- a/example/mod_bench.rs +++ b/example/mod_bench.rs @@ -3,7 +3,7 @@ #![allow(internal_features)] #[link(name = "c")] -extern {} +extern "C" {} #[panic_handler] fn panic_handler(_: &core::panic::PanicInfo<'_>) -> ! { diff --git a/example/std_example.rs b/example/std_example.rs index 9e43b4635f0d3..5fa1e0afb0603 100644 --- a/example/std_example.rs +++ b/example/std_example.rs @@ -7,7 +7,7 @@ use std::arch::x86_64::*; use std::io::Write; use std::ops::Coroutine; -extern { +extern "C" { pub fn printf(format: *const i8, ...) -> i32; } From 0f89f3ffd438d145a0896c6c86de3bf46d7e14df Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Sun, 15 Dec 2024 11:03:37 +0000 Subject: [PATCH 002/266] Use a C-safe return type for `__rust_[ui]128_*` overflowing intrinsics Combined with [1], this will change the overflowing multiplication operations to return an `extern "C"`-safe type. Link: https://github.com/rust-lang/compiler-builtins/pull/735 [1] --- src/int.rs | 123 +++++++++++++++++++++---------------------- src/intrinsic/mod.rs | 6 ++- 2 files changed, 64 insertions(+), 65 deletions(-) diff --git a/src/int.rs b/src/int.rs index 7b9d1feb8d710..fe6a65bed03b0 100644 --- a/src/int.rs +++ b/src/int.rs @@ -322,36 +322,26 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { }, } } else { - match new_kind { - Int(I128) | Uint(U128) => { - let func_name = match oop { - OverflowOp::Add => match new_kind { - Int(I128) => "__rust_i128_addo", - Uint(U128) => "__rust_u128_addo", - _ => unreachable!(), - }, - OverflowOp::Sub => match new_kind { - Int(I128) => "__rust_i128_subo", - Uint(U128) => "__rust_u128_subo", - _ => unreachable!(), - }, - OverflowOp::Mul => match new_kind { - Int(I128) => "__rust_i128_mulo", // TODO(antoyo): use __muloti4d instead? - Uint(U128) => "__rust_u128_mulo", - _ => unreachable!(), - }, - }; - return self.operation_with_overflow(func_name, lhs, rhs); - } - _ => match oop { - OverflowOp::Mul => match new_kind { - Int(I32) => "__mulosi4", - Int(I64) => "__mulodi4", - _ => unreachable!(), - }, - _ => unimplemented!("overflow operation for {:?}", new_kind), + let (func_name, width) = match oop { + OverflowOp::Add => match new_kind { + Int(I128) => ("__rust_i128_addo", 128), + Uint(U128) => ("__rust_u128_addo", 128), + _ => unreachable!(), }, - } + OverflowOp::Sub => match new_kind { + Int(I128) => ("__rust_i128_subo", 128), + Uint(U128) => ("__rust_u128_subo", 128), + _ => unreachable!(), + }, + OverflowOp::Mul => match new_kind { + Int(I32) => ("__mulosi4", 32), + Int(I64) => ("__mulodi4", 64), + Int(I128) => ("__rust_i128_mulo", 128), // TODO(antoyo): use __muloti4d instead? + Uint(U128) => ("__rust_u128_mulo", 128), + _ => unreachable!(), + }, + }; + return self.operation_with_overflow(func_name, lhs, rhs, width); }; let intrinsic = self.context.get_builtin_function(name); @@ -364,80 +354,87 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { (res.dereference(self.location).to_rvalue(), overflow) } + /// Non-`__builtin_*` overflow operations with a `fn(T, T, &mut i32) -> T` signature. pub fn operation_with_overflow( &self, func_name: &str, lhs: RValue<'gcc>, rhs: RValue<'gcc>, + width: u64, ) -> (RValue<'gcc>, RValue<'gcc>) { let a_type = lhs.get_type(); let b_type = rhs.get_type(); debug_assert!(a_type.dyncast_array().is_some()); debug_assert!(b_type.dyncast_array().is_some()); + let overflow_type = self.i32_type; + let overflow_param_type = overflow_type.make_pointer(); + let res_type = a_type; + + let overflow_value = + self.current_func().new_local(self.location, overflow_type, "overflow"); + let overflow_addr = overflow_value.get_address(self.location); + let param_a = self.context.new_parameter(self.location, a_type, "a"); let param_b = self.context.new_parameter(self.location, b_type, "b"); - let result_field = self.context.new_field(self.location, a_type, "result"); - let overflow_field = self.context.new_field(self.location, self.bool_type, "overflow"); - - let ret_ty = Ty::new_tup(self.tcx, &[self.tcx.types.i128, self.tcx.types.bool]); + let param_overflow = + self.context.new_parameter(self.location, overflow_param_type, "overflow"); + + let a_elem_type = a_type.dyncast_array().expect("non-array a value"); + debug_assert!(a_elem_type.is_integral()); + let res_ty = match width { + 32 => self.tcx.types.i32, + 64 => self.tcx.types.i64, + 128 => self.tcx.types.i128, + _ => unreachable!("unexpected integer size"), + }; let layout = self .tcx - .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ret_ty)) + .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(res_ty)) .unwrap(); let arg_abi = ArgAbi { layout, mode: PassMode::Direct(ArgAttributes::new()) }; let mut fn_abi = FnAbi { - args: vec![arg_abi.clone(), arg_abi.clone()].into_boxed_slice(), + args: vec![arg_abi.clone(), arg_abi.clone(), arg_abi.clone()].into_boxed_slice(), ret: arg_abi, c_variadic: false, - fixed_count: 2, + fixed_count: 3, conv: Conv::C, can_unwind: false, }; fn_abi.adjust_for_foreign_abi(self.cx, spec::abi::Abi::C { unwind: false }).unwrap(); - let indirect = matches!(fn_abi.ret.mode, PassMode::Indirect { .. }); - - let return_type = self - .context - .new_struct_type(self.location, "result_overflow", &[result_field, overflow_field]); - let result = if indirect { - let return_value = - self.current_func().new_local(self.location, return_type.as_type(), "return_value"); - let return_param_type = return_type.as_type().make_pointer(); - let return_param = - self.context.new_parameter(self.location, return_param_type, "return_value"); + let ret_indirect = matches!(fn_abi.ret.mode, PassMode::Indirect { .. }); + + let result = if ret_indirect { + let res_value = self.current_func().new_local(self.location, res_type, "result_value"); + let res_addr = res_value.get_address(self.location); + let res_param_type = res_type.make_pointer(); + let param_res = self.context.new_parameter(self.location, res_param_type, "result"); + let func = self.context.new_function( self.location, FunctionType::Extern, self.type_void(), - &[return_param, param_a, param_b], + &[param_res, param_a, param_b, param_overflow], func_name, false, ); - self.llbb().add_eval( - self.location, - self.context.new_call(self.location, func, &[ - return_value.get_address(self.location), - lhs, - rhs, - ]), - ); - return_value.to_rvalue() + let _void = + self.context.new_call(self.location, func, &[res_addr, lhs, rhs, overflow_addr]); + res_value.to_rvalue() } else { let func = self.context.new_function( self.location, FunctionType::Extern, - return_type.as_type(), - &[param_a, param_b], + res_type, + &[param_a, param_b, param_overflow], func_name, false, ); - self.context.new_call(self.location, func, &[lhs, rhs]) + self.context.new_call(self.location, func, &[lhs, rhs, overflow_addr]) }; - let overflow = result.access_field(self.location, overflow_field); - let int_result = result.access_field(self.location, result_field); - (int_result, overflow) + + (result, self.context.new_cast(self.location, overflow_value, self.bool_type).to_rvalue()) } pub fn gcc_icmp( diff --git a/src/intrinsic/mod.rs b/src/intrinsic/mod.rs index 42d189d1b7d38..48606f5f91c0f 100644 --- a/src/intrinsic/mod.rs +++ b/src/intrinsic/mod.rs @@ -1001,7 +1001,8 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { 128 => "__rust_i128_addo", _ => unreachable!(), }; - let (int_result, overflow) = self.operation_with_overflow(func_name, lhs, rhs); + let (int_result, overflow) = + self.operation_with_overflow(func_name, lhs, rhs, width); self.llbb().add_assignment(self.location, res, int_result); overflow }; @@ -1071,7 +1072,8 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { 128 => "__rust_i128_subo", _ => unreachable!(), }; - let (int_result, overflow) = self.operation_with_overflow(func_name, lhs, rhs); + let (int_result, overflow) = + self.operation_with_overflow(func_name, lhs, rhs, width); self.llbb().add_assignment(self.location, res, int_result); overflow }; From 4600047767f36d12dff51e2b844ed67f81d7adda Mon Sep 17 00:00:00 2001 From: Kyle Huey Date: Fri, 17 Jan 2025 09:44:09 -0800 Subject: [PATCH 003/266] When LLVM's location discriminator value limit is exceeded, emit locations with dummy spans instead of dropping them entirely Revert most of #133194 (except the test and the comment fixes). Then refix not emitting locations at all when the correct location discriminator value exceeds LLVM's capacity. --- src/debuginfo.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/debuginfo.rs b/src/debuginfo.rs index d3aeb7f3bdeb3..4b84b1dbfd396 100644 --- a/src/debuginfo.rs +++ b/src/debuginfo.rs @@ -113,15 +113,15 @@ fn make_mir_scope<'gcc, 'tcx>( let scope_data = &mir.source_scopes[scope]; let parent_scope = if let Some(parent) = scope_data.parent_scope { make_mir_scope(cx, _instance, mir, variables, debug_context, instantiated, parent); - debug_context.scopes[parent].unwrap() + debug_context.scopes[parent] } else { // The root is the function itself. let file = cx.sess().source_map().lookup_source_file(mir.span.lo()); - debug_context.scopes[scope] = Some(DebugScope { + debug_context.scopes[scope] = DebugScope { file_start_pos: file.start_pos, file_end_pos: file.end_position(), - ..debug_context.scopes[scope].unwrap() - }); + ..debug_context.scopes[scope] + }; instantiated.insert(scope); return; }; @@ -130,7 +130,7 @@ fn make_mir_scope<'gcc, 'tcx>( if !vars.contains(scope) && scope_data.inlined.is_none() { // Do not create a DIScope if there are no variables defined in this // MIR `SourceScope`, and it's not `inlined`, to avoid debuginfo bloat. - debug_context.scopes[scope] = Some(parent_scope); + debug_context.scopes[scope] = parent_scope; instantiated.insert(scope); return; } @@ -157,12 +157,12 @@ fn make_mir_scope<'gcc, 'tcx>( // TODO(tempdragon): dbg_scope: Add support for scope extension here. inlined_at.or(p_inlined_at); - debug_context.scopes[scope] = Some(DebugScope { + debug_context.scopes[scope] = DebugScope { dbg_scope, inlined_at, file_start_pos: loc.file.start_pos, file_end_pos: loc.file.end_position(), - }); + }; instantiated.insert(scope); } @@ -232,12 +232,12 @@ impl<'gcc, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { } // Initialize fn debug context (including scopes). - let empty_scope = Some(DebugScope { + let empty_scope = DebugScope { dbg_scope: self.dbg_scope_fn(instance, fn_abi, Some(llfn)), inlined_at: None, file_start_pos: BytePos(0), file_end_pos: BytePos(0), - }); + }; let mut fn_debug_context = FunctionDebugContext { scopes: IndexVec::from_elem(empty_scope, mir.source_scopes.as_slice()), inlined_function_scopes: Default::default(), From 49e047f5aa09d8179dce0d36df8a8263b144de81 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Wed, 8 Jan 2025 15:00:25 +0000 Subject: [PATCH 004/266] Treat undef bytes as equal to any other byte --- src/common.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/common.rs b/src/common.rs index f43743fc2a41b..bd5d6ba387cff 100644 --- a/src/common.rs +++ b/src/common.rs @@ -64,6 +64,11 @@ impl<'gcc, 'tcx> ConstCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { if type_is_pointer(typ) { self.context.new_null(typ) } else { self.const_int(typ, 0) } } + fn is_undef(&self, _val: RValue<'gcc>) -> bool { + // FIXME: actually check for undef + false + } + fn const_undef(&self, typ: Type<'gcc>) -> RValue<'gcc> { let local = self.current_func.borrow().expect("func").new_local(None, typ, "undefined"); if typ.is_struct().is_some() { From 301d2478e04264d1336572a810c33108ec0a278f Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 14 Dec 2024 09:13:12 +0100 Subject: [PATCH 005/266] remove support for the #[start] attribute --- build_system/src/test.rs | 26 ----------------------- example/alloc_example.rs | 7 ++++--- example/mini_core_hello_world.rs | 2 +- example/mod_bench.rs | 36 -------------------------------- src/context.rs | 1 - tests/run/abort1.rs | 7 ++++--- tests/run/abort2.rs | 7 ++++--- tests/run/array.rs | 7 ++++--- tests/run/assign.rs | 7 ++++--- tests/run/closure.rs | 7 ++++--- tests/run/condition.rs | 7 ++++--- tests/run/empty_main.rs | 7 ++++--- tests/run/exit.rs | 7 ++++--- tests/run/exit_code.rs | 7 ++++--- tests/run/fun_ptr.rs | 7 ++++--- tests/run/mut_ref.rs | 7 ++++--- tests/run/operations.rs | 7 ++++--- tests/run/ptr_cast.rs | 7 ++++--- tests/run/return-tuple.rs | 7 ++++--- tests/run/slice.rs | 7 ++++--- tests/run/static.rs | 7 ++++--- tests/run/structs.rs | 7 ++++--- tests/run/tuple.rs | 7 ++++--- 23 files changed, 77 insertions(+), 121 deletions(-) delete mode 100644 example/mod_bench.rs diff --git a/build_system/src/test.rs b/build_system/src/test.rs index 7cc7336612c79..0e790a4befc9b 100644 --- a/build_system/src/test.rs +++ b/build_system/src/test.rs @@ -426,19 +426,6 @@ fn std_tests(env: &Env, args: &TestArg) -> Result<(), String> { run_command_with_env(&command, None, Some(env))?; maybe_run_command_in_vm(&[&cargo_target_dir.join("track-caller-attribute")], env, args)?; - // FIXME: create a function "display_if_not_quiet" or something along the line. - println!("[AOT] mod_bench"); - let mut command = args.config_info.rustc_command_vec(); - command.extend_from_slice(&[ - &"example/mod_bench.rs", - &"--crate-type", - &"bin", - &"--target", - &args.config_info.target_triple, - ]); - run_command_with_env(&command, None, Some(env))?; - // FIXME: the compiled binary is not run. - Ok(()) } @@ -696,19 +683,6 @@ fn test_libcore(env: &Env, args: &TestArg) -> Result<(), String> { Ok(()) } -// echo "[BENCH COMPILE] mod_bench" -// -// COMPILE_MOD_BENCH_INLINE="$RUSTC example/mod_bench.rs --crate-type bin -Zmir-opt-level=3 -O --crate-name mod_bench_inline" -// COMPILE_MOD_BENCH_LLVM_0="rustc example/mod_bench.rs --crate-type bin -Copt-level=0 -o $cargo_target_dir/mod_bench_llvm_0 -Cpanic=abort" -// COMPILE_MOD_BENCH_LLVM_1="rustc example/mod_bench.rs --crate-type bin -Copt-level=1 -o $cargo_target_dir/mod_bench_llvm_1 -Cpanic=abort" -// COMPILE_MOD_BENCH_LLVM_2="rustc example/mod_bench.rs --crate-type bin -Copt-level=2 -o $cargo_target_dir/mod_bench_llvm_2 -Cpanic=abort" -// COMPILE_MOD_BENCH_LLVM_3="rustc example/mod_bench.rs --crate-type bin -Copt-level=3 -o $cargo_target_dir/mod_bench_llvm_3 -Cpanic=abort" -// -// Use 100 runs, because a single compilations doesn't take more than ~150ms, so it isn't very slow -// hyperfine --runs ${COMPILE_RUNS:-100} "$COMPILE_MOD_BENCH_INLINE" "$COMPILE_MOD_BENCH_LLVM_0" "$COMPILE_MOD_BENCH_LLVM_1" "$COMPILE_MOD_BENCH_LLVM_2" "$COMPILE_MOD_BENCH_LLVM_3" -// echo "[BENCH RUN] mod_bench" -// hyperfine --runs ${RUN_RUNS:-10} $cargo_target_dir/mod_bench{,_inline} $cargo_target_dir/mod_bench_llvm_* - fn extended_rand_tests(env: &Env, args: &TestArg) -> Result<(), String> { if !args.is_using_gcc_master_branch() { println!("Not using GCC master branch. Skipping `extended_rand_tests`."); diff --git a/example/alloc_example.rs b/example/alloc_example.rs index 6ed8b9157f21a..9a0b46d5b221a 100644 --- a/example/alloc_example.rs +++ b/example/alloc_example.rs @@ -1,5 +1,6 @@ -#![feature(start, core_intrinsics, alloc_error_handler, lang_items)] +#![feature(core_intrinsics, alloc_error_handler, lang_items)] #![no_std] +#![no_main] #![allow(internal_features)] extern crate alloc; @@ -37,8 +38,8 @@ unsafe extern "C" fn _Unwind_Resume() { core::intrinsics::unreachable(); } -#[start] -fn main(_argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(_argc: core::ffi::c_int, _argv: *const *const u8) -> core::ffi::c_int { let world: Box<&str> = Box::new("Hello World!\0"); unsafe { puts(*world as *const str as *const u8); diff --git a/example/mini_core_hello_world.rs b/example/mini_core_hello_world.rs index 1d51e0a1856ba..4cbe66c5e4c69 100644 --- a/example/mini_core_hello_world.rs +++ b/example/mini_core_hello_world.rs @@ -1,7 +1,7 @@ // Adapted from https://github.com/sunfishcode/mir2cranelift/blob/master/rust-examples/nocore-hello-world.rs #![feature( - no_core, unboxed_closures, start, lang_items, never_type, linkage, + no_core, unboxed_closures, lang_items, never_type, linkage, extern_types, thread_local )] #![no_core] diff --git a/example/mod_bench.rs b/example/mod_bench.rs deleted file mode 100644 index e8a9cade74745..0000000000000 --- a/example/mod_bench.rs +++ /dev/null @@ -1,36 +0,0 @@ -#![feature(start, core_intrinsics, lang_items)] -#![no_std] -#![allow(internal_features)] - -#[link(name = "c")] -extern "C" {} - -#[panic_handler] -fn panic_handler(_: &core::panic::PanicInfo<'_>) -> ! { - core::intrinsics::abort(); -} - -#[lang="eh_personality"] -fn eh_personality(){} - -// Required for rustc_codegen_llvm -#[no_mangle] -unsafe extern "C" fn _Unwind_Resume() { - core::intrinsics::unreachable(); -} - -#[start] -fn main(_argc: isize, _argv: *const *const u8) -> isize { - for i in 2..100_000_000 { - black_box((i + 1) % i); - } - - 0 -} - -#[inline(never)] -fn black_box(i: u32) { - if i != 1 { - core::intrinsics::abort(); - } -} diff --git a/src/context.rs b/src/context.rs index c81c53359fd18..30732c74eb3ef 100644 --- a/src/context.rs +++ b/src/context.rs @@ -513,7 +513,6 @@ impl<'gcc, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { } else { // If the symbol already exists, it is an error: for example, the user wrote // #[no_mangle] extern "C" fn main(..) {..} - // instead of #[start] None } } diff --git a/tests/run/abort1.rs b/tests/run/abort1.rs index 696197d73772f..385e41a68817f 100644 --- a/tests/run/abort1.rs +++ b/tests/run/abort1.rs @@ -3,11 +3,12 @@ // Run-time: // status: signal -#![feature(auto_traits, lang_items, no_core, start, intrinsics, rustc_attrs)] +#![feature(auto_traits, lang_items, no_core, intrinsics, rustc_attrs)] #![allow(internal_features)] #![no_std] #![no_core] +#![no_main] /* * Core @@ -49,7 +50,7 @@ fn test_fail() -> ! { unsafe { intrinsics::abort() }; } -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { test_fail(); } diff --git a/tests/run/abort2.rs b/tests/run/abort2.rs index 714cd6c0f3817..6c66a930e0741 100644 --- a/tests/run/abort2.rs +++ b/tests/run/abort2.rs @@ -3,11 +3,12 @@ // Run-time: // status: signal -#![feature(auto_traits, lang_items, no_core, start, intrinsics, rustc_attrs)] +#![feature(auto_traits, lang_items, no_core, intrinsics, rustc_attrs)] #![allow(internal_features)] #![no_std] #![no_core] +#![no_main] /* * Core @@ -50,8 +51,8 @@ fn fail() -> i32 { 0 } -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { fail(); 0 } diff --git a/tests/run/array.rs b/tests/run/array.rs index c3c08c29c6dba..e18a4ced6bc46 100644 --- a/tests/run/array.rs +++ b/tests/run/array.rs @@ -7,10 +7,11 @@ // 5 // 10 -#![feature(no_core, start)] +#![feature(no_core)] #![no_std] #![no_core] +#![no_main] extern crate mini_core; @@ -28,8 +29,8 @@ fn make_array() -> [u8; 3] { [42, 10, 5] } -#[start] -fn main(argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { let array = [42, 7, 5]; let array2 = make_array(); unsafe { diff --git a/tests/run/assign.rs b/tests/run/assign.rs index 2a47f0c2966e5..4d414c577a657 100644 --- a/tests/run/assign.rs +++ b/tests/run/assign.rs @@ -6,10 +6,11 @@ // 10 #![allow(internal_features, unused_attributes)] -#![feature(auto_traits, lang_items, no_core, start, intrinsics, rustc_attrs, track_caller)] +#![feature(auto_traits, lang_items, no_core, intrinsics, rustc_attrs, track_caller)] #![no_std] #![no_core] +#![no_main] /* * Core @@ -142,8 +143,8 @@ fn inc(num: isize) -> isize { } -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { argc = inc(argc); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc); diff --git a/tests/run/closure.rs b/tests/run/closure.rs index 46c47bc54ed01..c7a236f74f9e6 100644 --- a/tests/run/closure.rs +++ b/tests/run/closure.rs @@ -8,10 +8,11 @@ // Int argument: 2 // Both args: 11 -#![feature(no_core, start)] +#![feature(no_core)] #![no_std] #![no_core] +#![no_main] extern crate mini_core; @@ -22,8 +23,8 @@ mod libc { } } -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { let string = "Arg: %d\n\0"; let mut closure = || { unsafe { diff --git a/tests/run/condition.rs b/tests/run/condition.rs index 039ef94eaa717..b02359702ed2e 100644 --- a/tests/run/condition.rs +++ b/tests/run/condition.rs @@ -5,10 +5,11 @@ // stdout: true // 1 -#![feature(no_core, start)] +#![feature(no_core)] #![no_std] #![no_core] +#![no_main] extern crate mini_core; @@ -19,8 +20,8 @@ mod libc { } } -#[start] -fn main(argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { unsafe { if argc == 1 { libc::printf(b"true\n\0" as *const u8 as *const i8); diff --git a/tests/run/empty_main.rs b/tests/run/empty_main.rs index e66a859ad698e..042e44080c53a 100644 --- a/tests/run/empty_main.rs +++ b/tests/run/empty_main.rs @@ -3,11 +3,12 @@ // Run-time: // status: 0 -#![feature(auto_traits, lang_items, no_core, start)] +#![feature(auto_traits, lang_items, no_core)] #![allow(internal_features)] #![no_std] #![no_core] +#![no_main] /* * Core @@ -34,7 +35,7 @@ pub(crate) unsafe auto trait Freeze {} * Code */ -#[start] -fn main(_argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { 0 } diff --git a/tests/run/exit.rs b/tests/run/exit.rs index bf1cbeef30205..9a7c91c0adb20 100644 --- a/tests/run/exit.rs +++ b/tests/run/exit.rs @@ -3,11 +3,12 @@ // Run-time: // status: 2 -#![feature(auto_traits, lang_items, no_core, start, intrinsics)] +#![feature(auto_traits, lang_items, no_core, intrinsics)] #![allow(internal_features)] #![no_std] #![no_core] +#![no_main] mod libc { #[link(name = "c")] @@ -41,8 +42,8 @@ pub(crate) unsafe auto trait Freeze {} * Code */ -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { unsafe { libc::exit(2); } diff --git a/tests/run/exit_code.rs b/tests/run/exit_code.rs index be7a233efdaaf..c50d2b0d7107c 100644 --- a/tests/run/exit_code.rs +++ b/tests/run/exit_code.rs @@ -3,11 +3,12 @@ // Run-time: // status: 1 -#![feature(auto_traits, lang_items, no_core, start)] +#![feature(auto_traits, lang_items, no_core)] #![allow(internal_features)] #![no_std] #![no_core] +#![no_main] /* * Core @@ -34,7 +35,7 @@ pub(crate) unsafe auto trait Freeze {} * Code */ -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { 1 } diff --git a/tests/run/fun_ptr.rs b/tests/run/fun_ptr.rs index ed1bf72bb2754..98b351e504495 100644 --- a/tests/run/fun_ptr.rs +++ b/tests/run/fun_ptr.rs @@ -4,10 +4,11 @@ // status: 0 // stdout: 1 -#![feature(no_core, start)] +#![feature(no_core)] #![no_std] #![no_core] +#![no_main] extern crate mini_core; @@ -26,8 +27,8 @@ fn call_func(func: fn(i16) -> i8, param: i16) -> i8 { func(param) } -#[start] -fn main(argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { unsafe { let result = call_func(i16_as_i8, argc as i16) as isize; libc::printf(b"%ld\n\0" as *const u8 as *const i8, result); diff --git a/tests/run/mut_ref.rs b/tests/run/mut_ref.rs index 3ae793382164b..9be64f991ee08 100644 --- a/tests/run/mut_ref.rs +++ b/tests/run/mut_ref.rs @@ -8,10 +8,11 @@ // 11 #![allow(internal_features, unused_attributes)] -#![feature(auto_traits, lang_items, no_core, start, intrinsics, rustc_attrs, track_caller)] +#![feature(auto_traits, lang_items, no_core, intrinsics, rustc_attrs, track_caller)] #![no_std] #![no_core] +#![no_main] /* * Core @@ -148,8 +149,8 @@ fn update_num(num: &mut isize) { *num = *num + 5; } -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { let mut test = test(argc); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field); diff --git a/tests/run/operations.rs b/tests/run/operations.rs index 0e44fc580b8c4..c92d3cc0b8fbf 100644 --- a/tests/run/operations.rs +++ b/tests/run/operations.rs @@ -6,10 +6,11 @@ // 10 #![allow(internal_features, unused_attributes)] -#![feature(auto_traits, lang_items, no_core, start, intrinsics, arbitrary_self_types, rustc_attrs)] +#![feature(auto_traits, lang_items, no_core, intrinsics, arbitrary_self_types, rustc_attrs)] #![no_std] #![no_core] +#![no_main] /* * Core @@ -231,8 +232,8 @@ pub fn panic_const_mul_overflow() -> ! { * Code */ -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, 40 + argc); libc::printf(b"%ld\n\0" as *const u8 as *const i8, 40 - argc); diff --git a/tests/run/ptr_cast.rs b/tests/run/ptr_cast.rs index 2b8812ad51c5e..0ba49e7187fca 100644 --- a/tests/run/ptr_cast.rs +++ b/tests/run/ptr_cast.rs @@ -4,10 +4,11 @@ // status: 0 // stdout: 1 -#![feature(no_core, start)] +#![feature(no_core)] #![no_std] #![no_core] +#![no_main] extern crate mini_core; @@ -24,8 +25,8 @@ fn make_array() -> [u8; 3] { [42, 10, 5] } -#[start] -fn main(argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { unsafe { let ptr = ONE as *mut usize; let value = ptr as usize; diff --git a/tests/run/return-tuple.rs b/tests/run/return-tuple.rs index f2a5a2e4384df..3cc1e274001e7 100644 --- a/tests/run/return-tuple.rs +++ b/tests/run/return-tuple.rs @@ -6,11 +6,12 @@ // 10 // 42 -#![feature(auto_traits, lang_items, no_core, start, intrinsics)] +#![feature(auto_traits, lang_items, no_core, intrinsics)] #![allow(internal_features)] #![no_std] #![no_core] +#![no_main] #[lang = "copy"] pub unsafe trait Copy {} @@ -61,8 +62,8 @@ fn int_cast(a: u16, b: i16) -> (u8, u16, u32, usize, i8, i16, i32, isize, u8, u3 ) } -#[start] -fn main(argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { let (a, b, c, d, e, f, g, h, i, j) = int_cast(10, 42); unsafe { libc::printf(b"%d\n\0" as *const u8 as *const i8, c); diff --git a/tests/run/slice.rs b/tests/run/slice.rs index fba93fc155495..825fcb8a081e7 100644 --- a/tests/run/slice.rs +++ b/tests/run/slice.rs @@ -4,10 +4,11 @@ // status: 0 // stdout: 5 -#![feature(no_core, start)] +#![feature(no_core)] #![no_std] #![no_core] +#![no_main] extern crate mini_core; @@ -26,8 +27,8 @@ fn index_slice(s: &[u32]) -> u32 { } } -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { let array = [42, 7, 5]; unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, index_slice(&array)); diff --git a/tests/run/static.rs b/tests/run/static.rs index a17ea2a48936d..80c8782c4b1a6 100644 --- a/tests/run/static.rs +++ b/tests/run/static.rs @@ -9,11 +9,12 @@ // 12 // 1 -#![feature(auto_traits, lang_items, no_core, start, intrinsics, rustc_attrs)] +#![feature(auto_traits, lang_items, no_core, intrinsics, rustc_attrs)] #![allow(internal_features)] #![no_std] #![no_core] +#![no_main] /* * Core @@ -98,8 +99,8 @@ static mut WITH_REF: WithRef = WithRef { refe: unsafe { &TEST }, }; -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, CONSTANT); libc::printf(b"%ld\n\0" as *const u8 as *const i8, TEST2.field); diff --git a/tests/run/structs.rs b/tests/run/structs.rs index d6455667400c9..59b8f358863f2 100644 --- a/tests/run/structs.rs +++ b/tests/run/structs.rs @@ -5,11 +5,12 @@ // stdout: 1 // 2 -#![feature(auto_traits, lang_items, no_core, start, intrinsics)] +#![feature(auto_traits, lang_items, no_core, intrinsics)] #![allow(internal_features)] #![no_std] #![no_core] +#![no_main] /* * Core @@ -55,8 +56,8 @@ fn one() -> isize { 1 } -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { let test = Test { field: one(), }; diff --git a/tests/run/tuple.rs b/tests/run/tuple.rs index 8a7d85ae867e8..ed60a56a68c4c 100644 --- a/tests/run/tuple.rs +++ b/tests/run/tuple.rs @@ -4,11 +4,12 @@ // status: 0 // stdout: 3 -#![feature(auto_traits, lang_items, no_core, start, intrinsics)] +#![feature(auto_traits, lang_items, no_core, intrinsics)] #![allow(internal_features)] #![no_std] #![no_core] +#![no_main] /* * Core @@ -42,8 +43,8 @@ mod libc { * Code */ -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { let test: (isize, isize, isize) = (3, 1, 4); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.0); From 0692ca3d20787e43a3ff3674c0cc7e7487de6508 Mon Sep 17 00:00:00 2001 From: Manuel Drehwald Date: Fri, 24 Jan 2025 16:05:26 -0500 Subject: [PATCH 006/266] Make CodegenCx and Builder generic Co-authored-by: Oli Scherer --- src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 7329080ce1f71..34aead1a6300a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -442,7 +442,6 @@ impl WriteBackendMethods for GccCodegenBackend { } fn autodiff( _cgcx: &CodegenContext, - _tcx: TyCtxt<'_>, _module: &ModuleCodegen, _diff_fncs: Vec, _config: &ModuleConfig, From d6d7c1581e211b9847ffc488645ec7bc342990f7 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 24 Jan 2025 23:12:17 +0100 Subject: [PATCH 007/266] Merge commit '9f33f846ddc06afd7ffd839ee4f18babac3f3204' --- .github/workflows/ci.yml | 10 +++--- .github/workflows/failures.yml | 6 ++-- .github/workflows/gcc12.yml | 2 +- .github/workflows/m68k.yml | 8 ++--- .github/workflows/release.yml | 13 +++++--- build_system/src/build.rs | 10 ++++-- build_system/src/config.rs | 57 ++++++++++++++++++++++++++-------- build_system/src/info.rs | 4 ++- build_system/src/main.rs | 4 +-- build_system/src/test.rs | 7 +++-- libgccjit.version | 2 +- messages.ftl | 3 -- 12 files changed, 85 insertions(+), 41 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 73ec6b84a155e..f96912e6b7a83 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,14 +13,14 @@ env: jobs: build: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: libgccjit_version: - - { gcc: "gcc-13.deb" } - - { gcc: "gcc-13-without-int128.deb" } + - { gcc: "gcc-15.deb" } + - { gcc: "gcc-15-without-int128.deb" } commands: [ "--std-tests", # FIXME: re-enable asm tests when GCC can emit in the right syntax. @@ -108,13 +108,13 @@ jobs: cargo clippy --all-targets --features master -- -D warnings duplicates: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - run: python tools/check_intrinsics_duplicates.py build_system: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - name: Test build system diff --git a/.github/workflows/failures.yml b/.github/workflows/failures.yml index f33d9fcc58257..d080bbfe91fe6 100644 --- a/.github/workflows/failures.yml +++ b/.github/workflows/failures.yml @@ -13,7 +13,7 @@ env: jobs: build: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 strategy: fail-fast: false @@ -56,12 +56,12 @@ jobs: - name: Download artifact if: matrix.libgccjit_version.gcc != 'libgccjit12.so' - run: curl -LO https://github.com/rust-lang/gcc/releases/latest/download/gcc-13.deb + run: curl -LO https://github.com/rust-lang/gcc/releases/latest/download/gcc-15.deb - name: Setup path to libgccjit if: matrix.libgccjit_version.gcc != 'libgccjit12.so' run: | - sudo dpkg --force-overwrite -i gcc-13.deb + sudo dpkg --force-overwrite -i gcc-15.deb echo 'gcc-path = "/usr/lib"' > config.toml echo "LIBRARY_PATH=/usr/lib" >> $GITHUB_ENV echo "LD_LIBRARY_PATH=/usr/lib" >> $GITHUB_ENV diff --git a/.github/workflows/gcc12.yml b/.github/workflows/gcc12.yml index 4c2ce91e86eef..bb9e020dc6a4c 100644 --- a/.github/workflows/gcc12.yml +++ b/.github/workflows/gcc12.yml @@ -17,7 +17,7 @@ env: jobs: build: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 strategy: fail-fast: false diff --git a/.github/workflows/m68k.yml b/.github/workflows/m68k.yml index 07bb372b3606d..ed1fc02bd9131 100644 --- a/.github/workflows/m68k.yml +++ b/.github/workflows/m68k.yml @@ -17,7 +17,7 @@ env: jobs: build: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 strategy: fail-fast: false @@ -47,17 +47,17 @@ jobs: - name: Install packages run: | sudo apt-get update - sudo apt-get install qemu qemu-user-static + sudo apt-get install qemu-system qemu-user-static - name: Download artifact - run: curl -LO https://github.com/cross-cg-gcc-tools/cross-gcc/releases/latest/download/gcc-m68k-13.deb + run: curl -LO https://github.com/cross-cg-gcc-tools/cross-gcc/releases/latest/download/gcc-m68k-15.deb - name: Download VM artifact run: curl -LO https://github.com/cross-cg-gcc-tools/vms/releases/latest/download/debian-m68k.img - name: Setup path to libgccjit run: | - sudo dpkg -i gcc-m68k-13.deb + sudo dpkg -i gcc-m68k-15.deb echo 'gcc-path = "/usr/lib/"' > config.toml - name: Set env diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 60e0943c87dac..886ce90b4713e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,7 +13,7 @@ env: jobs: build: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 strategy: fail-fast: false @@ -37,11 +37,11 @@ jobs: run: sudo apt-get install ninja-build ripgrep - name: Download artifact - run: curl -LO https://github.com/rust-lang/gcc/releases/latest/download/gcc-13.deb + run: curl -LO https://github.com/rust-lang/gcc/releases/latest/download/gcc-15.deb - name: Setup path to libgccjit run: | - sudo dpkg --force-overwrite -i gcc-13.deb + sudo dpkg --force-overwrite -i gcc-15.deb echo 'gcc-path = "/usr/lib/"' > config.toml - name: Set env @@ -76,4 +76,9 @@ jobs: - name: Run y.sh cargo build run: | EMBED_LTO_BITCODE=1 CHANNEL="release" ./y.sh cargo build --release --manifest-path tests/hello-world/Cargo.toml - # TODO: grep the asm output for "call my_func" and fail if it is found. + call_found=$(objdump -dj .text tests/hello-world/target/release/hello_world | grep -c "call .*mylib.*my_func" ) ||: + if [ $call_found -gt 0 ]; then + echo "ERROR: call my_func found in asm" + echo "Test is done with LTO enabled, hence inlining should occur across crates" + exit 1 + fi diff --git a/build_system/src/build.rs b/build_system/src/build.rs index d0ced211a6169..e98377f15a945 100644 --- a/build_system/src/build.rs +++ b/build_system/src/build.rs @@ -150,6 +150,8 @@ pub fn build_sysroot(env: &HashMap, config: &ConfigInfo) -> Resu "debug" }; + // We have a different environment variable than RUSTFLAGS to make sure those flags are only + // sent to rustc_codegen_gcc and not the LLVM backend. if let Ok(cg_rustflags) = std::env::var("CG_RUSTFLAGS") { rustflags.push(' '); rustflags.push_str(&cg_rustflags); @@ -184,8 +186,12 @@ pub fn build_sysroot(env: &HashMap, config: &ConfigInfo) -> Resu fn build_codegen(args: &mut BuildArg) -> Result<(), String> { let mut env = HashMap::new(); - env.insert("LD_LIBRARY_PATH".to_string(), args.config_info.gcc_path.clone()); - env.insert("LIBRARY_PATH".to_string(), args.config_info.gcc_path.clone()); + let gcc_path = + args.config_info.gcc_path.clone().expect( + "The config module should have emitted an error if the GCC path wasn't provided", + ); + env.insert("LD_LIBRARY_PATH".to_string(), gcc_path.clone()); + env.insert("LIBRARY_PATH".to_string(), gcc_path); if args.config_info.no_default_features { env.insert("RUSTFLAGS".to_string(), "-Csymbol-mangling-version=v0".to_string()); diff --git a/build_system/src/config.rs b/build_system/src/config.rs index 37b4b68950e49..4f9fcc9715140 100644 --- a/build_system/src/config.rs +++ b/build_system/src/config.rs @@ -112,7 +112,7 @@ pub struct ConfigInfo { pub sysroot_panic_abort: bool, pub cg_backend_path: String, pub sysroot_path: String, - pub gcc_path: String, + pub gcc_path: Option, config_file: Option, // This is used in particular in rust compiler bootstrap because it doesn't run at the root // of the `cg_gcc` folder, making it complicated for us to get access to local files we need @@ -173,6 +173,14 @@ impl ConfigInfo { "--release-sysroot" => self.sysroot_release_channel = true, "--release" => self.channel = Channel::Release, "--sysroot-panic-abort" => self.sysroot_panic_abort = true, + "--gcc-path" => match args.next() { + Some(arg) if !arg.is_empty() => { + self.gcc_path = Some(arg.into()); + } + _ => { + return Err("Expected a value after `--gcc-path`, found nothing".to_string()); + } + }, "--cg_gcc-path" => match args.next() { Some(arg) if !arg.is_empty() => { self.cg_gcc_path = Some(arg.into()); @@ -260,8 +268,9 @@ impl ConfigInfo { create_symlink(&libgccjit_so, output_dir.join(&format!("{}.0", libgccjit_so_name)))?; } - self.gcc_path = output_dir.display().to_string(); - println!("Using `{}` as path for libgccjit", self.gcc_path); + let gcc_path = output_dir.display().to_string(); + println!("Using `{}` as path for libgccjit", gcc_path); + self.gcc_path = Some(gcc_path); Ok(()) } @@ -273,6 +282,15 @@ impl ConfigInfo { } pub fn setup_gcc_path(&mut self) -> Result<(), String> { + // If the user used the `--gcc-path` option, no need to look at `config.toml` content + // since we already have everything we need. + if let Some(gcc_path) = &self.gcc_path { + println!( + "`--gcc-path` was provided, ignoring config file. Using `{}` as path for libgccjit", + gcc_path + ); + return Ok(()); + } let config_file = match self.config_file.as_deref() { Some(config_file) => config_file.into(), None => self.compute_path("config.toml"), @@ -283,12 +301,15 @@ impl ConfigInfo { self.download_gccjit_if_needed()?; return Ok(()); } - self.gcc_path = match gcc_path { - Some(path) => path, - None => { - return Err(format!("missing `gcc-path` value from `{}`", config_file.display(),)); - } + let Some(gcc_path) = gcc_path else { + return Err(format!("missing `gcc-path` value from `{}`", config_file.display())); }; + println!( + "GCC path retrieved from `{}`. Using `{}` as path for libgccjit", + config_file.display(), + gcc_path + ); + self.gcc_path = Some(gcc_path); Ok(()) } @@ -299,10 +320,17 @@ impl ConfigInfo { ) -> Result<(), String> { env.insert("CARGO_INCREMENTAL".to_string(), "0".to_string()); - if self.gcc_path.is_empty() && !use_system_gcc { - self.setup_gcc_path()?; - } - env.insert("GCC_PATH".to_string(), self.gcc_path.clone()); + let gcc_path = if !use_system_gcc { + if self.gcc_path.is_none() { + self.setup_gcc_path()?; + } + self.gcc_path.clone().expect( + "The config module should have emitted an error if the GCC path wasn't provided", + ) + } else { + String::new() + }; + env.insert("GCC_PATH".to_string(), gcc_path.clone()); if self.cargo_target_dir.is_empty() { match env.get("CARGO_TARGET_DIR").filter(|dir| !dir.is_empty()) { @@ -381,6 +409,8 @@ impl ConfigInfo { } // This environment variable is useful in case we want to change options of rustc commands. + // We have a different environment variable than RUSTFLAGS to make sure those flags are + // only sent to rustc_codegen_gcc and not the LLVM backend. if let Some(cg_rustflags) = env.get("CG_RUSTFLAGS") { rustflags.extend_from_slice(&split_args(&cg_rustflags)?); } @@ -414,7 +444,7 @@ impl ConfigInfo { "{target}:{sysroot}:{gcc_path}", target = self.cargo_target_dir, sysroot = sysroot.display(), - gcc_path = self.gcc_path, + gcc_path = gcc_path, ); env.insert("LIBRARY_PATH".to_string(), ld_library_path.clone()); env.insert("LD_LIBRARY_PATH".to_string(), ld_library_path.clone()); @@ -459,6 +489,7 @@ impl ConfigInfo { --release-sysroot : Build sysroot in release mode --sysroot-panic-abort : Build the sysroot without unwinding support --config-file : Location of the config file to be used + --gcc-path : Location of the GCC root folder --cg_gcc-path : Location of the rustc_codegen_gcc root folder (used when ran from another directory) --no-default-features : Add `--no-default-features` flag to cargo commands diff --git a/build_system/src/info.rs b/build_system/src/info.rs index ea38791d38c9a..bd891de2eb4c0 100644 --- a/build_system/src/info.rs +++ b/build_system/src/info.rs @@ -14,6 +14,8 @@ pub fn run() -> Result<(), String> { } config.no_download = true; config.setup_gcc_path()?; - println!("{}", config.gcc_path); + if let Some(gcc_path) = config.gcc_path { + println!("{}", gcc_path); + } Ok(()) } diff --git a/build_system/src/main.rs b/build_system/src/main.rs index 3a860e2b1360c..393617183061b 100644 --- a/build_system/src/main.rs +++ b/build_system/src/main.rs @@ -34,11 +34,11 @@ Options: --help : Displays this help message. Commands: - cargo : Executes a cargo command. + cargo : Executes a cargo command. rustc : Compiles the program using the GCC compiler. clean : Cleans the build directory, removing all compiled files and artifacts. prepare : Prepares the environment for building, including fetching dependencies and setting up configurations. - build : Compiles the project. + build : Compiles the project. test : Runs tests for the project. info : Displays information about the build environment and project configuration. clone-gcc : Clones the GCC compiler from a specified source. diff --git a/build_system/src/test.rs b/build_system/src/test.rs index 0e790a4befc9b..6c29c7d1825b9 100644 --- a/build_system/src/test.rs +++ b/build_system/src/test.rs @@ -1229,8 +1229,11 @@ pub fn run() -> Result<(), String> { if !args.use_system_gcc { args.config_info.setup_gcc_path()?; - env.insert("LIBRARY_PATH".to_string(), args.config_info.gcc_path.clone()); - env.insert("LD_LIBRARY_PATH".to_string(), args.config_info.gcc_path.clone()); + let gcc_path = args.config_info.gcc_path.clone().expect( + "The config module should have emitted an error if the GCC path wasn't provided", + ); + env.insert("LIBRARY_PATH".to_string(), gcc_path.clone()); + env.insert("LD_LIBRARY_PATH".to_string(), gcc_path); } build_if_no_backend(&env, &args)?; diff --git a/libgccjit.version b/libgccjit.version index ff58accec1d4c..417fd5b03935d 100644 --- a/libgccjit.version +++ b/libgccjit.version @@ -1 +1 @@ -45648c2edd4ecd862d9f08196d3d6c6ccba79f07 +e607be166673a8de9fc07f6f02c60426e556c5f2 diff --git a/messages.ftl b/messages.ftl index 85fa17a6ba501..882fff8673a19 100644 --- a/messages.ftl +++ b/messages.ftl @@ -5,9 +5,6 @@ codegen_gcc_unknown_ctarget_feature_prefix = codegen_gcc_invalid_minimum_alignment = invalid minimum global alignment: {$err} -codegen_gcc_lto_not_supported = - LTO is not supported. You may get a linker error. - codegen_gcc_forbidden_ctarget_feature = target feature `{$feature}` cannot be toggled with `-Ctarget-feature`: {$reason} From 24ce0a2efa314eff96af73f5b6c5d0e3392abf38 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Sun, 12 Jan 2025 20:18:45 +0000 Subject: [PATCH 008/266] Stabilize `const_black_box` This has been unstably const since [1], but a tracking issue was never created. Per discussion on Zulip [2], there should not be any blockers to making this const-stable. The function does not provide any functionality at compile time but does allow code reuse between const- and non-const functions, so stabilize it here. [1]: https://github.com/rust-lang/rust/pull/92226 [2]: https://rust-lang.zulipchat.com/#narrow/channel/146212-t-compiler.2Fconst-eval/topic/const_black_box --- tests/run/int.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/run/int.rs b/tests/run/int.rs index bfe73c38435a3..58a26801b678c 100644 --- a/tests/run/int.rs +++ b/tests/run/int.rs @@ -3,8 +3,6 @@ // Run-time: // status: 0 -#![feature(const_black_box)] - /* * Code */ From bc6b9bf526b2aafefe5d212cdde85e01b16351ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Mon, 27 Jan 2025 23:27:43 +0100 Subject: [PATCH 009/266] Add CI success job --- .github/workflows/ci.yml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f96912e6b7a83..689a7dee435f4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -121,3 +121,23 @@ jobs: run: | cd build_system cargo test + + + # Summary job for the merge queue. + # ALL THE PREVIOUS JOBS NEED TO BE ADDED TO THE `needs` SECTION OF THIS JOB! + success: + needs: [build, duplicates, build_system] + # We need to ensure this job does *not* get skipped if its dependencies fail, + # because a skipped job is considered a success by GitHub. So we have to + # overwrite `if:`. We use `!cancelled()` to ensure the job does still not get run + # when the workflow is canceled manually. + if: ${{ !cancelled() }} + runs-on: ubuntu-latest + steps: + # Manually check the status of all dependencies. `if: failure()` does not work. + - name: Conclusion + run: | + # Print the dependent jobs to see them in the CI log + jq -C <<< '${{ toJson(needs) }}' + # Check if all jobs that we depend on (in the needs array) were successful. + jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}' From 600999a4fe7af3c7eae9349f6530c5c7b12ce1cd Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 27 Jan 2025 18:30:17 +0100 Subject: [PATCH 010/266] ABI-required target features: warn when they are missing in base CPU (rather than silently enabling them) --- src/gcc_util.rs | 50 +------------------------------------------------ src/lib.rs | 5 +++-- 2 files changed, 4 insertions(+), 51 deletions(-) diff --git a/src/gcc_util.rs b/src/gcc_util.rs index 560aff43d6538..4e8c8aaaf5c8a 100644 --- a/src/gcc_util.rs +++ b/src/gcc_util.rs @@ -1,10 +1,8 @@ -use std::iter::FromIterator; - #[cfg(feature = "master")] use gccjit::Context; use rustc_codegen_ssa::codegen_attrs::check_tied_features; use rustc_codegen_ssa::errors::TargetFeatureDisableOrEnable; -use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::unord::UnordSet; use rustc_session::Session; use rustc_target::target_features::RUSTC_SPECIFIC_FEATURES; @@ -45,12 +43,6 @@ pub(crate) fn global_gcc_features(sess: &Session, diagnostics: bool) -> Vec Vec Date: Fri, 10 Jan 2025 04:36:11 +0000 Subject: [PATCH 011/266] Do not treat vtable supertraits as distinct when bound with different bound vars --- src/common.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/common.rs b/src/common.rs index bd5d6ba387cff..20a3482aaa27f 100644 --- a/src/common.rs +++ b/src/common.rs @@ -234,7 +234,12 @@ impl<'gcc, 'tcx> ConstCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { GlobalAlloc::VTable(ty, dyn_ty) => { let alloc = self .tcx - .global_alloc(self.tcx.vtable_allocation((ty, dyn_ty.principal()))) + .global_alloc(self.tcx.vtable_allocation(( + ty, + dyn_ty.principal().map(|principal| { + self.tcx.instantiate_bound_regions_with_erased(principal) + }), + ))) .unwrap_memory(); let init = const_alloc_to_gcc(self, alloc); self.static_addr_of(init, alloc.inner().align, None) From 12feb0e21fe1cc79ee31951322b3bc587e07befe Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 10 Jan 2025 20:26:10 +0000 Subject: [PATCH 012/266] Use ExistentialTraitRef throughout codegen --- src/context.rs | 6 +++--- src/debuginfo.rs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/context.rs b/src/context.rs index 30732c74eb3ef..570ef938dc44e 100644 --- a/src/context.rs +++ b/src/context.rs @@ -14,7 +14,7 @@ use rustc_middle::ty::layout::{ FnAbiError, FnAbiOf, FnAbiOfHelpers, FnAbiRequest, HasTyCtxt, HasTypingEnv, LayoutError, LayoutOfHelpers, }; -use rustc_middle::ty::{self, Instance, PolyExistentialTraitRef, Ty, TyCtxt}; +use rustc_middle::ty::{self, ExistentialTraitRef, Instance, Ty, TyCtxt}; use rustc_session::Session; use rustc_span::source_map::respan; use rustc_span::{DUMMY_SP, Span}; @@ -90,7 +90,7 @@ pub struct CodegenCx<'gcc, 'tcx> { pub function_instances: RefCell, Function<'gcc>>>, /// Cache generated vtables pub vtables: - RefCell, Option>), RValue<'gcc>>>, + RefCell, Option>), RValue<'gcc>>>, // TODO(antoyo): improve the SSA API to not require those. /// Mapping from function pointer type to indexes of on stack parameters. @@ -401,7 +401,7 @@ impl<'gcc, 'tcx> BackendTypes for CodegenCx<'gcc, 'tcx> { impl<'gcc, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { fn vtables( &self, - ) -> &RefCell, Option>), RValue<'gcc>>> { + ) -> &RefCell, Option>), RValue<'gcc>>> { &self.vtables } diff --git a/src/debuginfo.rs b/src/debuginfo.rs index 4b84b1dbfd396..86d3de225f71e 100644 --- a/src/debuginfo.rs +++ b/src/debuginfo.rs @@ -7,7 +7,7 @@ use rustc_data_structures::sync::Lrc; use rustc_index::bit_set::DenseBitSet; use rustc_index::{Idx, IndexVec}; use rustc_middle::mir::{self, Body, SourceScope}; -use rustc_middle::ty::{Instance, PolyExistentialTraitRef, Ty}; +use rustc_middle::ty::{ExistentialTraitRef, Instance, Ty}; use rustc_session::config::DebugInfo; use rustc_span::{BytePos, Pos, SourceFile, SourceFileAndLine, Span, Symbol}; use rustc_target::abi::Size; @@ -214,7 +214,7 @@ impl<'gcc, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { fn create_vtable_debuginfo( &self, _ty: Ty<'tcx>, - _trait_ref: Option>, + _trait_ref: Option>, _vtable: Self::Value, ) { // TODO(antoyo) From adee0849a2971663984f6d7c1612097d4cbbcbd3 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sat, 1 Feb 2025 10:31:25 -0500 Subject: [PATCH 013/266] Add success job for all CI workflows --- .github/workflows/ci.yml | 1 - .github/workflows/failures.yml | 2 +- .github/workflows/gcc12.yml | 2 +- .github/workflows/m68k.yml | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/stdarch.yml | 2 +- 6 files changed, 5 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 689a7dee435f4..688a9f7d7bf73 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -122,7 +122,6 @@ jobs: cd build_system cargo test - # Summary job for the merge queue. # ALL THE PREVIOUS JOBS NEED TO BE ADDED TO THE `needs` SECTION OF THIS JOB! success: diff --git a/.github/workflows/failures.yml b/.github/workflows/failures.yml index d080bbfe91fe6..b9f6f9d84f460 100644 --- a/.github/workflows/failures.yml +++ b/.github/workflows/failures.yml @@ -12,7 +12,7 @@ env: RUST_BACKTRACE: 1 jobs: - build: + success: runs-on: ubuntu-24.04 strategy: diff --git a/.github/workflows/gcc12.yml b/.github/workflows/gcc12.yml index bb9e020dc6a4c..0308eec51cdf3 100644 --- a/.github/workflows/gcc12.yml +++ b/.github/workflows/gcc12.yml @@ -16,7 +16,7 @@ env: GCC_EXEC_PREFIX: /usr/lib/gcc/ jobs: - build: + success: runs-on: ubuntu-24.04 strategy: diff --git a/.github/workflows/m68k.yml b/.github/workflows/m68k.yml index ed1fc02bd9131..e031ad59f4b51 100644 --- a/.github/workflows/m68k.yml +++ b/.github/workflows/m68k.yml @@ -16,7 +16,7 @@ env: OVERWRITE_TARGET_TRIPLE: m68k-unknown-linux-gnu jobs: - build: + success: runs-on: ubuntu-24.04 strategy: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 886ce90b4713e..4367cbccab115 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,7 +12,7 @@ env: RUST_BACKTRACE: 1 jobs: - build: + success: runs-on: ubuntu-24.04 strategy: diff --git a/.github/workflows/stdarch.yml b/.github/workflows/stdarch.yml index d5ae6144496f1..ea8bec02eef1e 100644 --- a/.github/workflows/stdarch.yml +++ b/.github/workflows/stdarch.yml @@ -12,7 +12,7 @@ env: RUST_BACKTRACE: 1 jobs: - build: + success: runs-on: ubuntu-24.04 strategy: From ff2cd0fb6390d775c753733abefab6b81d45eb64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Sat, 1 Feb 2025 19:13:41 +0100 Subject: [PATCH 014/266] Remove duplicated CI triggers There shouldn't be a need to run all CI jobs on all pushes. --- .github/workflows/ci.yml | 1 - .github/workflows/gcc12.yml | 1 - .github/workflows/m68k.yml | 1 - .github/workflows/release.yml | 1 - .github/workflows/stdarch.yml | 1 - 5 files changed, 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 688a9f7d7bf73..bf974f65c1e16 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,6 @@ name: CI on: - - push - pull_request permissions: diff --git a/.github/workflows/gcc12.yml b/.github/workflows/gcc12.yml index 0308eec51cdf3..0d49336ea208e 100644 --- a/.github/workflows/gcc12.yml +++ b/.github/workflows/gcc12.yml @@ -1,7 +1,6 @@ name: CI libgccjit 12 on: - - push - pull_request permissions: diff --git a/.github/workflows/m68k.yml b/.github/workflows/m68k.yml index e031ad59f4b51..af5f084205e52 100644 --- a/.github/workflows/m68k.yml +++ b/.github/workflows/m68k.yml @@ -3,7 +3,6 @@ name: m68k CI on: - - push - pull_request permissions: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4367cbccab115..4582cf577fe61 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,7 +1,6 @@ name: CI with sysroot compiled in release mode on: - - push - pull_request permissions: diff --git a/.github/workflows/stdarch.yml b/.github/workflows/stdarch.yml index ea8bec02eef1e..a1df0207d54f6 100644 --- a/.github/workflows/stdarch.yml +++ b/.github/workflows/stdarch.yml @@ -1,7 +1,6 @@ name: stdarch tests with sysroot compiled in release mode on: - - push - pull_request permissions: From befc31c588585db6650d228f50727070e2ccd96b Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sat, 1 Feb 2025 12:19:35 -0500 Subject: [PATCH 015/266] Move back to a success job so because the required checks only work without a matrix --- .github/workflows/failures.yml | 21 ++++++++++++++++++++- .github/workflows/gcc12.yml | 21 ++++++++++++++++++++- .github/workflows/m68k.yml | 21 ++++++++++++++++++++- .github/workflows/release.yml | 21 ++++++++++++++++++++- .github/workflows/stdarch.yml | 21 ++++++++++++++++++++- 5 files changed, 100 insertions(+), 5 deletions(-) diff --git a/.github/workflows/failures.yml b/.github/workflows/failures.yml index b9f6f9d84f460..ab3e4002e87f6 100644 --- a/.github/workflows/failures.yml +++ b/.github/workflows/failures.yml @@ -12,7 +12,7 @@ env: RUST_BACKTRACE: 1 jobs: - success: + build: runs-on: ubuntu-24.04 strategy: @@ -108,3 +108,22 @@ jobs: echo "Error: 'the compiler unexpectedly panicked' found in output logs. CI Error!!" exit 1 fi + + # Summary job for the merge queue. + # ALL THE PREVIOUS JOBS NEED TO BE ADDED TO THE `needs` SECTION OF THIS JOB! + success_failures: + needs: [build] + # We need to ensure this job does *not* get skipped if its dependencies fail, + # because a skipped job is considered a success by GitHub. So we have to + # overwrite `if:`. We use `!cancelled()` to ensure the job does still not get run + # when the workflow is canceled manually. + if: ${{ !cancelled() }} + runs-on: ubuntu-latest + steps: + # Manually check the status of all dependencies. `if: failure()` does not work. + - name: Conclusion + run: | + # Print the dependent jobs to see them in the CI log + jq -C <<< '${{ toJson(needs) }}' + # Check if all jobs that we depend on (in the needs array) were successful. + jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}' diff --git a/.github/workflows/gcc12.yml b/.github/workflows/gcc12.yml index 0308eec51cdf3..33d5d1a52df8e 100644 --- a/.github/workflows/gcc12.yml +++ b/.github/workflows/gcc12.yml @@ -16,7 +16,7 @@ env: GCC_EXEC_PREFIX: /usr/lib/gcc/ jobs: - success: + build: runs-on: ubuntu-24.04 strategy: @@ -85,3 +85,22 @@ jobs: #- name: Run tests #run: | #./y.sh test --release --clean --build-sysroot ${{ matrix.commands }} --no-default-features + + # Summary job for the merge queue. + # ALL THE PREVIOUS JOBS NEED TO BE ADDED TO THE `needs` SECTION OF THIS JOB! + success_gcc12: + needs: [build] + # We need to ensure this job does *not* get skipped if its dependencies fail, + # because a skipped job is considered a success by GitHub. So we have to + # overwrite `if:`. We use `!cancelled()` to ensure the job does still not get run + # when the workflow is canceled manually. + if: ${{ !cancelled() }} + runs-on: ubuntu-latest + steps: + # Manually check the status of all dependencies. `if: failure()` does not work. + - name: Conclusion + run: | + # Print the dependent jobs to see them in the CI log + jq -C <<< '${{ toJson(needs) }}' + # Check if all jobs that we depend on (in the needs array) were successful. + jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}' diff --git a/.github/workflows/m68k.yml b/.github/workflows/m68k.yml index e031ad59f4b51..a7090338a7f14 100644 --- a/.github/workflows/m68k.yml +++ b/.github/workflows/m68k.yml @@ -16,7 +16,7 @@ env: OVERWRITE_TARGET_TRIPLE: m68k-unknown-linux-gnu jobs: - success: + build: runs-on: ubuntu-24.04 strategy: @@ -105,3 +105,22 @@ jobs: - name: Run tests run: | ./y.sh test --release --clean --build-sysroot --sysroot-features compiler_builtins/no-f16-f128 ${{ matrix.commands }} + + # Summary job for the merge queue. + # ALL THE PREVIOUS JOBS NEED TO BE ADDED TO THE `needs` SECTION OF THIS JOB! + success_m68k: + needs: [build] + # We need to ensure this job does *not* get skipped if its dependencies fail, + # because a skipped job is considered a success by GitHub. So we have to + # overwrite `if:`. We use `!cancelled()` to ensure the job does still not get run + # when the workflow is canceled manually. + if: ${{ !cancelled() }} + runs-on: ubuntu-latest + steps: + # Manually check the status of all dependencies. `if: failure()` does not work. + - name: Conclusion + run: | + # Print the dependent jobs to see them in the CI log + jq -C <<< '${{ toJson(needs) }}' + # Check if all jobs that we depend on (in the needs array) were successful. + jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4367cbccab115..7284b7f7398a3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,7 +12,7 @@ env: RUST_BACKTRACE: 1 jobs: - success: + build: runs-on: ubuntu-24.04 strategy: @@ -82,3 +82,22 @@ jobs: echo "Test is done with LTO enabled, hence inlining should occur across crates" exit 1 fi + + # Summary job for the merge queue. + # ALL THE PREVIOUS JOBS NEED TO BE ADDED TO THE `needs` SECTION OF THIS JOB! + success_release: + needs: [build] + # We need to ensure this job does *not* get skipped if its dependencies fail, + # because a skipped job is considered a success by GitHub. So we have to + # overwrite `if:`. We use `!cancelled()` to ensure the job does still not get run + # when the workflow is canceled manually. + if: ${{ !cancelled() }} + runs-on: ubuntu-latest + steps: + # Manually check the status of all dependencies. `if: failure()` does not work. + - name: Conclusion + run: | + # Print the dependent jobs to see them in the CI log + jq -C <<< '${{ toJson(needs) }}' + # Check if all jobs that we depend on (in the needs array) were successful. + jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}' diff --git a/.github/workflows/stdarch.yml b/.github/workflows/stdarch.yml index ea8bec02eef1e..9438e557ecd9e 100644 --- a/.github/workflows/stdarch.yml +++ b/.github/workflows/stdarch.yml @@ -12,7 +12,7 @@ env: RUST_BACKTRACE: 1 jobs: - success: + build: runs-on: ubuntu-24.04 strategy: @@ -102,3 +102,22 @@ jobs: # TODO: remove --skip test_mm512_stream_ps when stdarch is updated in rustc. # TODO: remove --skip test_tile_ when it's implemented. STDARCH_TEST_EVERYTHING=1 CHANNEL=release CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER="${{ matrix.cargo_runner }}" TARGET=x86_64-unknown-linux-gnu CG_RUSTFLAGS="-Ainternal_features --cfg stdarch_intel_sde" ./y.sh cargo test --manifest-path build/build_sysroot/sysroot_src/library/stdarch/Cargo.toml -- --skip rtm --skip tbm --skip sse4a --skip test_mm512_stream_ps --skip test_tile_ + + # Summary job for the merge queue. + # ALL THE PREVIOUS JOBS NEED TO BE ADDED TO THE `needs` SECTION OF THIS JOB! + success_stdarch: + needs: [build] + # We need to ensure this job does *not* get skipped if its dependencies fail, + # because a skipped job is considered a success by GitHub. So we have to + # overwrite `if:`. We use `!cancelled()` to ensure the job does still not get run + # when the workflow is canceled manually. + if: ${{ !cancelled() }} + runs-on: ubuntu-latest + steps: + # Manually check the status of all dependencies. `if: failure()` does not work. + - name: Conclusion + run: | + # Print the dependent jobs to see them in the CI log + jq -C <<< '${{ toJson(needs) }}' + # Check if all jobs that we depend on (in the needs array) were successful. + jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}' From ad2be68b490180012d7775a2ae3e0fd8e9cabda4 Mon Sep 17 00:00:00 2001 From: Kevin Hamacher Date: Mon, 27 Jan 2025 19:05:14 +0100 Subject: [PATCH 016/266] Make globals always have 2+ chars as suffix As discussed on chat, there currently is the bug where certain suffixes are interpreted by the (m68k) assembler. Example: `move.l #global.w,-44(%fp)` `.w` is interpreted by the assembler as a size hint for `#global`. --- src/context.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/context.rs b/src/context.rs index c81c53359fd18..2a33beef63b99 100644 --- a/src/context.rs +++ b/src/context.rs @@ -606,7 +606,10 @@ impl<'b, 'tcx> CodegenCx<'b, 'tcx> { let mut name = String::with_capacity(prefix.len() + 6); name.push_str(prefix); name.push('.'); - name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY)); + // Offset the index by the base so that always at least two characters + // are generated. This avoids cases where the suffix is interpreted as + // size by the assembler (for m68k: .b, .w, .l). + name.push_str(&(idx as u64 + ALPHANUMERIC_ONLY as u64).to_base(ALPHANUMERIC_ONLY)); name } } From 5d12c54b345d6bf6e7d25b904c1b7fbb0287429e Mon Sep 17 00:00:00 2001 From: Kevin Hamacher Date: Mon, 27 Jan 2025 18:49:49 +0100 Subject: [PATCH 017/266] Add M68000 entry to arch_to_gcc --- src/gcc_util.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/gcc_util.rs b/src/gcc_util.rs index 560aff43d6538..f463ee4061749 100644 --- a/src/gcc_util.rs +++ b/src/gcc_util.rs @@ -242,6 +242,7 @@ pub fn to_gcc_features<'a>(sess: &Session, s: &'a str) -> SmallVec<[&'a str; 2]> fn arch_to_gcc(name: &str) -> &str { match name { + "M68000" => "68000", "M68020" => "68020", _ => name, } From e0d8fb949cafac87d072e7bb873eeb115fe22706 Mon Sep 17 00:00:00 2001 From: Askar Safin Date: Mon, 3 Feb 2025 06:44:41 +0300 Subject: [PATCH 018/266] tree-wide: parallel: Fully removed all `Lrc`, replaced with `Arc` --- src/debuginfo.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/debuginfo.rs b/src/debuginfo.rs index 86d3de225f71e..12cbde0ad0d37 100644 --- a/src/debuginfo.rs +++ b/src/debuginfo.rs @@ -1,9 +1,9 @@ use std::ops::Range; +use std::sync::Arc; use gccjit::{Location, RValue}; use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext, VariableKind}; use rustc_codegen_ssa::traits::{DebugInfoBuilderMethods, DebugInfoCodegenMethods}; -use rustc_data_structures::sync::Lrc; use rustc_index::bit_set::DenseBitSet; use rustc_index::{Idx, IndexVec}; use rustc_middle::mir::{self, Body, SourceScope}; @@ -172,7 +172,7 @@ fn make_mir_scope<'gcc, 'tcx>( // `lookup_char_pos` return the right information instead. pub struct DebugLoc { /// Information about the original source file. - pub file: Lrc, + pub file: Arc, /// The (1-based) line number. pub line: u32, /// The (1-based) column number. From 4c932ff8379e70893d3cdc835c289547ba3bee26 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sat, 25 Jan 2025 23:32:44 +0100 Subject: [PATCH 019/266] Update repositories URL for repositories moved to `rust-lang` organization --- Readme.md | 4 ++-- build_system/src/clone_gcc.rs | 2 +- doc/add-attribute.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Readme.md b/Readme.md index e92c16ece2f10..d0e4dbba6d355 100644 --- a/Readme.md +++ b/Readme.md @@ -23,7 +23,7 @@ A secondary goal is to check if using the gcc backend will provide any run-time ## Building **This requires a patched libgccjit in order to work. -You need to use my [fork of gcc](https://github.com/antoyo/gcc) which already includes these patches.** +You need to use my [fork of gcc](https://github.com/rust-lang/gcc) which already includes these patches.** ```bash $ cp config.example.toml config.toml @@ -40,7 +40,7 @@ to do a few more things. To build it (most of these instructions come from [here](https://gcc.gnu.org/onlinedocs/jit/internals/index.html), so don't hesitate to take a look there if you encounter an issue): ```bash -$ git clone https://github.com/antoyo/gcc +$ git clone https://github.com/rust-lang/gcc $ sudo apt install flex libmpfr-dev libgmp-dev libmpc3 libmpc-dev $ mkdir gcc-build gcc-install $ cd gcc-build diff --git a/build_system/src/clone_gcc.rs b/build_system/src/clone_gcc.rs index e28ee873eb6be..b49dd47f35219 100644 --- a/build_system/src/clone_gcc.rs +++ b/build_system/src/clone_gcc.rs @@ -61,7 +61,7 @@ pub fn run() -> Result<(), String> { return Ok(()); }; - let result = git_clone("https://github.com/antoyo/gcc", Some(&args.out_path), false)?; + let result = git_clone("https://github.com/rust-lang/gcc", Some(&args.out_path), false)?; if result.ran_clone { let gcc_commit = args.config_info.get_gcc_commit()?; println!("Checking out GCC commit `{}`...", gcc_commit); diff --git a/doc/add-attribute.md b/doc/add-attribute.md index ae3bcc5e2ebe2..267c181952556 100644 --- a/doc/add-attribute.md +++ b/doc/add-attribute.md @@ -14,4 +14,4 @@ Finally, you need to update this repository by calling the relevant API you adde To test it, build `gcc`, run `cargo update -p gccjit` and then you can test the generated output for a given Rust crate. -[gccjit.rs]: https://github.com/antoyo/gccjit.rs +[gccjit.rs]: https://github.com/rust-lang/gccjit.rs From beb24b3301e6f9b831f16ddd542930024ffe8239 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 4 Feb 2025 15:15:28 +0100 Subject: [PATCH 020/266] intrinsics: unify rint, roundeven, nearbyint in a single round_ties_even intrinsic --- src/intrinsic/mod.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/intrinsic/mod.rs b/src/intrinsic/mod.rs index 48606f5f91c0f..83d0db0fb54a9 100644 --- a/src/intrinsic/mod.rs +++ b/src/intrinsic/mod.rs @@ -84,14 +84,11 @@ fn get_simple_intrinsic<'gcc, 'tcx>( sym::ceilf64 => "ceil", sym::truncf32 => "truncf", sym::truncf64 => "trunc", - sym::rintf32 => "rintf", - sym::rintf64 => "rint", - sym::nearbyintf32 => "nearbyintf", - sym::nearbyintf64 => "nearbyint", + // We match the LLVM backend and lower this to `rint`. + sym::round_ties_even_f32 => "rintf", + sym::round_ties_even_f64 => "rint", sym::roundf32 => "roundf", sym::roundf64 => "round", - sym::roundevenf32 => "roundevenf", - sym::roundevenf64 => "roundeven", sym::abort => "abort", _ => return None, }; From 819ab9b0656e3efbabdf680856d957ec746bc58a Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Sat, 2 Nov 2024 17:49:42 -0700 Subject: [PATCH 021/266] cg_gcc: Directly use rustc_abi instead of reexports --- src/abi.rs | 6 +++--- src/builder.rs | 2 +- src/consts.rs | 2 +- src/context.rs | 2 +- src/debuginfo.rs | 4 ++-- src/declare.rs | 2 +- src/int.rs | 7 +++---- src/intrinsic/mod.rs | 14 +++++++------- src/intrinsic/simd.rs | 2 +- src/type_.rs | 2 +- src/type_of.rs | 7 ++++--- 11 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/abi.rs b/src/abi.rs index 14fc23593f0e6..d94fc5525288d 100644 --- a/src/abi.rs +++ b/src/abi.rs @@ -8,7 +8,7 @@ use rustc_middle::ty::Ty; use rustc_middle::ty::layout::LayoutOf; #[cfg(feature = "master")] use rustc_session::config; -use rustc_target::abi::call::{ArgAttributes, CastTarget, FnAbi, PassMode, Reg, RegKind}; +use rustc_target::callconv::{ArgAttributes, CastTarget, FnAbi, PassMode, Reg, RegKind}; use crate::builder::Builder; use crate::context::CodegenCx; @@ -132,10 +132,10 @@ impl<'gcc, 'tcx> FnAbiGccExt<'gcc, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { if cx.sess().opts.optimize == config::OptLevel::No { return ty; } - if attrs.regular.contains(rustc_target::abi::call::ArgAttribute::NoAlias) { + if attrs.regular.contains(rustc_target::callconv::ArgAttribute::NoAlias) { ty = ty.make_restrict() } - if attrs.regular.contains(rustc_target::abi::call::ArgAttribute::NonNull) { + if attrs.regular.contains(rustc_target::callconv::ArgAttribute::NonNull) { non_null_args.push(arg_index as i32 + 1); } ty diff --git a/src/builder.rs b/src/builder.rs index 89e5cf1b8c6b6..bba19d0625832 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -29,7 +29,7 @@ use rustc_middle::ty::layout::{ use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_span::Span; use rustc_span::def_id::DefId; -use rustc_target::abi::call::FnAbi; +use rustc_target::callconv::FnAbi; use rustc_target::spec::{HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, Target, WasmCAbi, X86Abi}; use crate::common::{SignType, TypeReflection, type_is_pointer}; diff --git a/src/consts.rs b/src/consts.rs index 1631ecfeecf3f..fb0ca31c54334 100644 --- a/src/consts.rs +++ b/src/consts.rs @@ -1,6 +1,7 @@ #[cfg(feature = "master")] use gccjit::{FnAttribute, VarAttribute, Visibility}; use gccjit::{Function, GlobalKind, LValue, RValue, ToRValue, Type}; +use rustc_abi::{self as abi, Align, HasDataLayout, Primitive, Size, WrappingRange}; use rustc_codegen_ssa::traits::{ BaseTypeCodegenMethods, ConstCodegenMethods, StaticCodegenMethods, }; @@ -14,7 +15,6 @@ use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::{self, Instance}; use rustc_middle::{bug, span_bug}; use rustc_span::def_id::DefId; -use rustc_target::abi::{self, Align, HasDataLayout, Primitive, Size, WrappingRange}; use crate::base; use crate::context::CodegenCx; diff --git a/src/context.rs b/src/context.rs index 570ef938dc44e..1e1f577bb3a15 100644 --- a/src/context.rs +++ b/src/context.rs @@ -3,6 +3,7 @@ use std::cell::{Cell, RefCell}; use gccjit::{ Block, CType, Context, Function, FunctionPtrType, FunctionType, LValue, Location, RValue, Type, }; +use rustc_abi::{HasDataLayout, PointeeInfo, Size, TargetDataLayout, VariantIdx}; use rustc_codegen_ssa::base::wants_msvc_seh; use rustc_codegen_ssa::errors as ssa_errors; use rustc_codegen_ssa::traits::{BackendTypes, BaseTypeCodegenMethods, MiscCodegenMethods}; @@ -18,7 +19,6 @@ use rustc_middle::ty::{self, ExistentialTraitRef, Instance, Ty, TyCtxt}; use rustc_session::Session; use rustc_span::source_map::respan; use rustc_span::{DUMMY_SP, Span}; -use rustc_target::abi::{HasDataLayout, PointeeInfo, Size, TargetDataLayout, VariantIdx}; use rustc_target::spec::{ HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, Target, TlsModel, WasmCAbi, X86Abi, }; diff --git a/src/debuginfo.rs b/src/debuginfo.rs index 86d3de225f71e..3f6fdea9fb8cf 100644 --- a/src/debuginfo.rs +++ b/src/debuginfo.rs @@ -1,6 +1,7 @@ use std::ops::Range; use gccjit::{Location, RValue}; +use rustc_abi::Size; use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext, VariableKind}; use rustc_codegen_ssa::traits::{DebugInfoBuilderMethods, DebugInfoCodegenMethods}; use rustc_data_structures::sync::Lrc; @@ -10,8 +11,7 @@ use rustc_middle::mir::{self, Body, SourceScope}; use rustc_middle::ty::{ExistentialTraitRef, Instance, Ty}; use rustc_session::config::DebugInfo; use rustc_span::{BytePos, Pos, SourceFile, SourceFileAndLine, Span, Symbol}; -use rustc_target::abi::Size; -use rustc_target::abi::call::FnAbi; +use rustc_target::callconv::FnAbi; use crate::builder::Builder; use crate::context::CodegenCx; diff --git a/src/declare.rs b/src/declare.rs index 442488b7fd650..7cdbe3c0c6290 100644 --- a/src/declare.rs +++ b/src/declare.rs @@ -4,7 +4,7 @@ use gccjit::{Function, FunctionType, GlobalKind, LValue, RValue, Type}; use rustc_codegen_ssa::traits::BaseTypeCodegenMethods; use rustc_middle::ty::Ty; use rustc_span::Symbol; -use rustc_target::abi::call::FnAbi; +use rustc_target::callconv::FnAbi; use crate::abi::{FnAbiGcc, FnAbiGccExt}; use crate::context::CodegenCx; diff --git a/src/int.rs b/src/int.rs index fe6a65bed03b0..4a1db8d662a9f 100644 --- a/src/int.rs +++ b/src/int.rs @@ -3,12 +3,11 @@ //! 128-bit integers on 32-bit platforms and thus require to be handled manually. use gccjit::{BinaryOp, ComparisonOp, FunctionType, Location, RValue, ToRValue, Type, UnaryOp}; +use rustc_abi::{Endian, ExternAbi}; use rustc_codegen_ssa::common::{IntPredicate, TypeKind}; use rustc_codegen_ssa::traits::{BackendTypes, BaseTypeCodegenMethods, BuilderMethods, OverflowOp}; use rustc_middle::ty::{self, Ty}; -use rustc_target::abi::Endian; -use rustc_target::abi::call::{ArgAbi, ArgAttributes, Conv, FnAbi, PassMode}; -use rustc_target::spec; +use rustc_target::callconv::{ArgAbi, ArgAttributes, Conv, FnAbi, PassMode}; use crate::builder::{Builder, ToGccComp}; use crate::common::{SignType, TypeReflection}; @@ -401,7 +400,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { conv: Conv::C, can_unwind: false, }; - fn_abi.adjust_for_foreign_abi(self.cx, spec::abi::Abi::C { unwind: false }).unwrap(); + fn_abi.adjust_for_foreign_abi(self.cx, ExternAbi::C { unwind: false }).unwrap(); let ret_indirect = matches!(fn_abi.ret.mode, PassMode::Indirect { .. }); diff --git a/src/intrinsic/mod.rs b/src/intrinsic/mod.rs index 48606f5f91c0f..a1123fafe2f30 100644 --- a/src/intrinsic/mod.rs +++ b/src/intrinsic/mod.rs @@ -7,6 +7,9 @@ use std::iter; #[cfg(feature = "master")] use gccjit::FunctionType; use gccjit::{ComparisonOp, Function, RValue, ToRValue, Type, UnaryOp}; +#[cfg(feature = "master")] +use rustc_abi::ExternAbi; +use rustc_abi::HasDataLayout; use rustc_codegen_ssa::MemFlags; use rustc_codegen_ssa::base::wants_msvc_seh; use rustc_codegen_ssa::common::IntPredicate; @@ -25,11 +28,8 @@ use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt}; use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf}; use rustc_middle::ty::{self, Instance, Ty}; use rustc_span::{Span, Symbol, sym}; -use rustc_target::abi::HasDataLayout; -use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode}; +use rustc_target::callconv::{ArgAbi, FnAbi, PassMode}; use rustc_target::spec::PanicStrategy; -#[cfg(feature = "master")] -use rustc_target::spec::abi::Abi; #[cfg(feature = "master")] use crate::abi::FnAbiGccExt; @@ -1238,7 +1238,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>( tcx.types.unit, false, rustc_hir::Safety::Unsafe, - Abi::Rust, + ExternAbi::Rust, )), ); // `unsafe fn(*mut i8, *mut i8) -> ()` @@ -1249,7 +1249,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>( tcx.types.unit, false, rustc_hir::Safety::Unsafe, - Abi::Rust, + ExternAbi::Rust, )), ); // `unsafe fn(unsafe fn(*mut i8) -> (), *mut i8, unsafe fn(*mut i8, *mut i8) -> ()) -> i32` @@ -1258,7 +1258,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>( tcx.types.i32, false, rustc_hir::Safety::Unsafe, - Abi::Rust, + ExternAbi::Rust, )); let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen); cx.rust_try_fn.set(Some(rust_try)); diff --git a/src/intrinsic/simd.rs b/src/intrinsic/simd.rs index 1be452e5d05de..12a7dab155b47 100644 --- a/src/intrinsic/simd.rs +++ b/src/intrinsic/simd.rs @@ -3,6 +3,7 @@ use std::iter::FromIterator; use gccjit::{BinaryOp, RValue, ToRValue, Type}; #[cfg(feature = "master")] use gccjit::{ComparisonOp, UnaryOp}; +use rustc_abi::{Align, Size}; use rustc_codegen_ssa::base::compare_simd_types; use rustc_codegen_ssa::common::{IntPredicate, TypeKind}; #[cfg(feature = "master")] @@ -17,7 +18,6 @@ use rustc_middle::mir::BinOp; use rustc_middle::ty::layout::HasTyCtxt; use rustc_middle::ty::{self, Ty}; use rustc_span::{Span, Symbol, sym}; -use rustc_target::abi::{Align, Size}; use crate::builder::Builder; #[cfg(not(feature = "master"))] diff --git a/src/type_.rs b/src/type_.rs index 4ea5544721dea..cb08723431a9a 100644 --- a/src/type_.rs +++ b/src/type_.rs @@ -4,13 +4,13 @@ use std::convert::TryInto; #[cfg(feature = "master")] use gccjit::CType; use gccjit::{RValue, Struct, Type}; +use rustc_abi::{AddressSpace, Align, Integer, Size}; use rustc_codegen_ssa::common::TypeKind; use rustc_codegen_ssa::traits::{ BaseTypeCodegenMethods, DerivedTypeCodegenMethods, TypeMembershipCodegenMethods, }; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::{bug, ty}; -use rustc_target::abi::{AddressSpace, Align, Integer, Size}; use crate::common::TypeReflection; use crate::context::CodegenCx; diff --git a/src/type_of.rs b/src/type_of.rs index 0efdf36da485e..8b8b54753e7fd 100644 --- a/src/type_of.rs +++ b/src/type_of.rs @@ -3,7 +3,9 @@ use std::fmt::Write; use gccjit::{Struct, Type}; use rustc_abi as abi; use rustc_abi::Primitive::*; -use rustc_abi::{BackendRepr, FieldsShape, Integer, PointeeInfo, Size, Variants}; +use rustc_abi::{ + BackendRepr, FieldsShape, Integer, PointeeInfo, Reg, Size, TyAbiInterface, Variants, +}; use rustc_codegen_ssa::traits::{ BaseTypeCodegenMethods, DerivedTypeCodegenMethods, LayoutTypeCodegenMethods, }; @@ -11,8 +13,7 @@ use rustc_middle::bug; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self, CoroutineArgsExt, Ty, TypeVisitableExt}; -use rustc_target::abi::TyAbiInterface; -use rustc_target::abi::call::{CastTarget, FnAbi, Reg}; +use rustc_target::callconv::{CastTarget, FnAbi}; use crate::abi::{FnAbiGcc, FnAbiGccExt, GccType}; use crate::context::CodegenCx; From 2214ba9f1a9a3d88098ae34912d5c646b57f59a6 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Wed, 5 Feb 2025 12:16:57 -0500 Subject: [PATCH 022/266] Run the CI on push on the master branch --- .github/workflows/ci.yml | 5 ++++- .github/workflows/failures.yml | 5 ++++- .github/workflows/gcc12.yml | 5 ++++- .github/workflows/m68k.yml | 5 ++++- .github/workflows/release.yml | 5 ++++- .github/workflows/stdarch.yml | 5 ++++- 6 files changed, 24 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf974f65c1e16..ef024258ffc86 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,10 @@ name: CI on: - - pull_request + push: + branches: + - master + pull_request: permissions: contents: read diff --git a/.github/workflows/failures.yml b/.github/workflows/failures.yml index ab3e4002e87f6..bc42eb1468ea2 100644 --- a/.github/workflows/failures.yml +++ b/.github/workflows/failures.yml @@ -2,7 +2,10 @@ name: Failures on: - - pull_request + push: + branches: + - master + pull_request: permissions: contents: read diff --git a/.github/workflows/gcc12.yml b/.github/workflows/gcc12.yml index d6b7e5a2a13a5..da9a1506855c3 100644 --- a/.github/workflows/gcc12.yml +++ b/.github/workflows/gcc12.yml @@ -1,7 +1,10 @@ name: CI libgccjit 12 on: - - pull_request + push: + branches: + - master + pull_request: permissions: contents: read diff --git a/.github/workflows/m68k.yml b/.github/workflows/m68k.yml index 90fa5acc3fb03..21731f7087e2c 100644 --- a/.github/workflows/m68k.yml +++ b/.github/workflows/m68k.yml @@ -3,7 +3,10 @@ name: m68k CI on: - - pull_request + push: + branches: + - master + pull_request: permissions: contents: read diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2f6e3b4753191..47a40286554e4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,7 +1,10 @@ name: CI with sysroot compiled in release mode on: - - pull_request + push: + branches: + - master + pull_request: permissions: contents: read diff --git a/.github/workflows/stdarch.yml b/.github/workflows/stdarch.yml index 350e099d88701..4b9f48e7b1835 100644 --- a/.github/workflows/stdarch.yml +++ b/.github/workflows/stdarch.yml @@ -1,7 +1,10 @@ name: stdarch tests with sysroot compiled in release mode on: - - pull_request + push: + branches: + - master + pull_request: permissions: contents: read From 09d907627b6f86fae8cc926a353a44bd723ccf59 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Fri, 7 Feb 2025 16:48:39 +0100 Subject: [PATCH 023/266] fix backslashes in path used for `asm_tests` --- build_system/src/test.rs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/build_system/src/test.rs b/build_system/src/test.rs index efd7b2b8df3a1..096b4c4a71549 100644 --- a/build_system/src/test.rs +++ b/build_system/src/test.rs @@ -542,20 +542,21 @@ fn asm_tests(env: &Env, args: &TestArg) -> Result<(), String> { env.insert("COMPILETEST_FORCE_STAGE0".to_string(), "1".to_string()); - let extra = - if args.is_using_gcc_master_branch() { "" } else { " -Csymbol-mangling-version=v0" }; - - let rustc_args = &format!( - r#"-Zpanic-abort-tests \ - -Zcodegen-backend="{pwd}/target/{channel}/librustc_codegen_gcc.{dylib_ext}" \ - --sysroot "{sysroot_dir}" -Cpanic=abort{extra}"#, + let codegen_backend_path = format!( + "{pwd}/target/{channel}/librustc_codegen_gcc.{dylib_ext}", pwd = std::env::current_dir() .map_err(|error| format!("`current_dir` failed: {:?}", error))? .display(), channel = args.config_info.channel.as_str(), dylib_ext = args.config_info.dylib_ext, - sysroot_dir = args.config_info.sysroot_path, - extra = extra, + ); + + let extra = + if args.is_using_gcc_master_branch() { "" } else { " -Csymbol-mangling-version=v0" }; + + let rustc_args = format!( + "-Zpanic-abort-tests -Zcodegen-backend={codegen_backend_path} --sysroot {} -Cpanic=abort{extra}", + args.config_info.sysroot_path ); run_command_with_env( From 21b60aad987f5e61658901675cd64a5736ee5eef Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 7 Feb 2025 14:47:21 +0000 Subject: [PATCH 024/266] Remove Linkage::Private This is the same as Linkage::Internal except that it doesn't emit any symbol. Some backends may not support it and it isn't all that useful anyway. --- src/base.rs | 2 -- src/mono_item.rs | 5 +---- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/src/base.rs b/src/base.rs index c9701fb9885c1..f2fc098004470 100644 --- a/src/base.rs +++ b/src/base.rs @@ -51,7 +51,6 @@ pub fn global_linkage_to_gcc(linkage: Linkage) -> GlobalKind { Linkage::WeakODR => unimplemented!(), Linkage::Appending => unimplemented!(), Linkage::Internal => GlobalKind::Internal, - Linkage::Private => GlobalKind::Internal, Linkage::ExternalWeak => GlobalKind::Imported, // TODO(antoyo): should be weak linkage. Linkage::Common => unimplemented!(), } @@ -68,7 +67,6 @@ pub fn linkage_to_gcc(linkage: Linkage) -> FunctionType { Linkage::WeakODR => unimplemented!(), Linkage::Appending => unimplemented!(), Linkage::Internal => FunctionType::Internal, - Linkage::Private => FunctionType::Internal, Linkage::ExternalWeak => unimplemented!(), Linkage::Common => unimplemented!(), } diff --git a/src/mono_item.rs b/src/mono_item.rs index 239902df7f048..a2df7b2596fcf 100644 --- a/src/mono_item.rs +++ b/src/mono_item.rs @@ -61,10 +61,7 @@ impl<'gcc, 'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { // compiler-rt, then we want to implicitly compile everything with hidden // visibility as we're going to link this object all over the place but // don't want the symbols to get exported. - if linkage != Linkage::Internal - && linkage != Linkage::Private - && self.tcx.is_compiler_builtins(LOCAL_CRATE) - { + if linkage != Linkage::Internal && self.tcx.is_compiler_builtins(LOCAL_CRATE) { #[cfg(feature = "master")] decl.add_attribute(FnAttribute::Visibility(gccjit::Visibility::Hidden)); } else { From a90648d25533cd67d978d611dcddeb6f4b6caa39 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 7 Feb 2025 14:52:07 +0000 Subject: [PATCH 025/266] Remove Linkage::Appending It can only be used for certain LLVM internal variables like llvm.global_ctors which users are not allowed to define. --- src/base.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/base.rs b/src/base.rs index f2fc098004470..962f4b161d788 100644 --- a/src/base.rs +++ b/src/base.rs @@ -49,7 +49,6 @@ pub fn global_linkage_to_gcc(linkage: Linkage) -> GlobalKind { Linkage::LinkOnceODR => unimplemented!(), Linkage::WeakAny => unimplemented!(), Linkage::WeakODR => unimplemented!(), - Linkage::Appending => unimplemented!(), Linkage::Internal => GlobalKind::Internal, Linkage::ExternalWeak => GlobalKind::Imported, // TODO(antoyo): should be weak linkage. Linkage::Common => unimplemented!(), @@ -65,7 +64,6 @@ pub fn linkage_to_gcc(linkage: Linkage) -> FunctionType { Linkage::LinkOnceODR => unimplemented!(), Linkage::WeakAny => FunctionType::Exported, // FIXME(antoyo): should be similar to linkonce. Linkage::WeakODR => unimplemented!(), - Linkage::Appending => unimplemented!(), Linkage::Internal => FunctionType::Internal, Linkage::ExternalWeak => unimplemented!(), Linkage::Common => unimplemented!(), From 83f7576a770d394c79c8ef28e1687e3ad0f747d9 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Tue, 4 Feb 2025 22:56:30 -0800 Subject: [PATCH 026/266] compiler: remove reexports from rustc_target::callconv --- src/abi.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/abi.rs b/src/abi.rs index d94fc5525288d..717baebcd8cd6 100644 --- a/src/abi.rs +++ b/src/abi.rs @@ -1,6 +1,7 @@ #[cfg(feature = "master")] use gccjit::FnAttribute; use gccjit::{ToLValue, ToRValue, Type}; +use rustc_abi::{Reg, RegKind}; use rustc_codegen_ssa::traits::{AbiBuilderMethods, BaseTypeCodegenMethods}; use rustc_data_structures::fx::FxHashSet; use rustc_middle::bug; @@ -8,7 +9,7 @@ use rustc_middle::ty::Ty; use rustc_middle::ty::layout::LayoutOf; #[cfg(feature = "master")] use rustc_session::config; -use rustc_target::callconv::{ArgAttributes, CastTarget, FnAbi, PassMode, Reg, RegKind}; +use rustc_target::callconv::{ArgAttributes, CastTarget, FnAbi, PassMode}; use crate::builder::Builder; use crate::context::CodegenCx; From 180f350fc67eed3142fdc7b2e7e6955e4922642e Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 8 Feb 2025 22:12:13 +0000 Subject: [PATCH 027/266] Rustfmt --- src/builder.rs | 21 +- src/intrinsic/llvm.rs | 22 +- src/intrinsic/simd.rs | 466 +++++++++++++++++++++--------------------- 3 files changed, 259 insertions(+), 250 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index bba19d0625832..1c3d6cc899a63 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -155,14 +155,11 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { // NOTE: not sure why, but we have the wrong type here. let int_type = compare_exchange.get_param(2).to_rvalue().get_type(); let src = self.context.new_bitcast(self.location, src, int_type); - self.context.new_call(self.location, compare_exchange, &[ - dst, - expected, - src, - weak, - order, - failure_order, - ]) + self.context.new_call( + self.location, + compare_exchange, + &[dst, expected, src, weak, order, failure_order], + ) } pub fn assign(&self, lvalue: LValue<'gcc>, value: RValue<'gcc>) { @@ -1076,9 +1073,11 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { let align = dest.val.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size); cg_elem.val.store(self, PlaceRef::new_sized_aligned(current_val, cg_elem.layout, align)); - let next = self.inbounds_gep(self.backend_type(cg_elem.layout), current.to_rvalue(), &[ - self.const_usize(1), - ]); + let next = self.inbounds_gep( + self.backend_type(cg_elem.layout), + current.to_rvalue(), + &[self.const_usize(1)], + ); self.llbb().add_assignment(self.location, current, next); self.br(header_bb); diff --git a/src/intrinsic/llvm.rs b/src/intrinsic/llvm.rs index 231307def291f..2d731f88d7d36 100644 --- a/src/intrinsic/llvm.rs +++ b/src/intrinsic/llvm.rs @@ -687,11 +687,12 @@ pub fn adjust_intrinsic_return_value<'a, 'gcc, 'tcx>( let field2 = builder.context.new_field(None, args[1].get_type(), "carryResult"); let struct_type = builder.context.new_struct_type(None, "addcarryResult", &[field1, field2]); - return_value = - builder.context.new_struct_constructor(None, struct_type.as_type(), None, &[ - return_value, - last_arg.dereference(None).to_rvalue(), - ]); + return_value = builder.context.new_struct_constructor( + None, + struct_type.as_type(), + None, + &[return_value, last_arg.dereference(None).to_rvalue()], + ); } } "__builtin_ia32_stmxcsr" => { @@ -716,11 +717,12 @@ pub fn adjust_intrinsic_return_value<'a, 'gcc, 'tcx>( let field2 = builder.context.new_field(None, return_value.get_type(), "success"); let struct_type = builder.context.new_struct_type(None, "rdrand_result", &[field1, field2]); - return_value = - builder.context.new_struct_constructor(None, struct_type.as_type(), None, &[ - random_number, - success_variable.to_rvalue(), - ]); + return_value = builder.context.new_struct_constructor( + None, + struct_type.as_type(), + None, + &[random_number, success_variable.to_rvalue()], + ); } "fma" => { let f16_type = builder.context.new_c_type(CType::Float16); diff --git a/src/intrinsic/simd.rs b/src/intrinsic/simd.rs index 12a7dab155b47..84cd5b002fbb6 100644 --- a/src/intrinsic/simd.rs +++ b/src/intrinsic/simd.rs @@ -62,11 +62,10 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( let arg_tys = sig.inputs(); if name == sym::simd_select_bitmask { - require_simd!(arg_tys[1], InvalidMonomorphization::SimdArgument { - span, - name, - ty: arg_tys[1] - }); + require_simd!( + arg_tys[1], + InvalidMonomorphization::SimdArgument { span, name, ty: arg_tys[1] } + ); let (len, _) = arg_tys[1].simd_size_and_type(bx.tcx()); let expected_int_bits = (len.max(8) - 1).next_power_of_two(); @@ -140,14 +139,17 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx()); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); require!( bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer, InvalidMonomorphization::ReturnIntegerType { span, name, ret_ty, out_ty } @@ -269,23 +271,17 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( let lo_nibble = bx.context.new_rvalue_from_vector(None, long_byte_vector_type, &lo_nibble_elements); - let mask = bx.context.new_rvalue_from_vector(None, long_byte_vector_type, &vec![ - bx.context - .new_rvalue_from_int( - bx.u8_type, 0x0f - ); - byte_vector_type_size - as _ - ]); - - let four_vec = bx.context.new_rvalue_from_vector(None, long_byte_vector_type, &vec![ - bx.context - .new_rvalue_from_int( - bx.u8_type, 4 - ); - byte_vector_type_size - as _ - ]); + let mask = bx.context.new_rvalue_from_vector( + None, + long_byte_vector_type, + &vec![bx.context.new_rvalue_from_int(bx.u8_type, 0x0f); byte_vector_type_size as _], + ); + + let four_vec = bx.context.new_rvalue_from_vector( + None, + long_byte_vector_type, + &vec![bx.context.new_rvalue_from_int(bx.u8_type, 4); byte_vector_type_size as _], + ); // Step 2: Byte-swap the input. let swapped = simd_bswap(bx, args[0].immediate()); @@ -388,21 +384,14 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx()); - require!(out_len == n, InvalidMonomorphization::ReturnLength { - span, - name, - in_len: n, - ret_ty, - out_len - }); - require!(in_elem == out_ty, InvalidMonomorphization::ReturnElement { - span, - name, - in_elem, - in_ty, - ret_ty, - out_ty - }); + require!( + out_len == n, + InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len } + ); + require!( + in_elem == out_ty, + InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty } + ); let vector = args[2].immediate(); @@ -411,13 +400,16 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( #[cfg(feature = "master")] if name == sym::simd_insert { - require!(in_elem == arg_tys[2], InvalidMonomorphization::InsertedType { - span, - name, - in_elem, - in_ty, - out_ty: arg_tys[2] - }); + require!( + in_elem == arg_tys[2], + InvalidMonomorphization::InsertedType { + span, + name, + in_elem, + in_ty, + out_ty: arg_tys[2] + } + ); let vector = args[0].immediate(); let index = args[1].immediate(); let value = args[2].immediate(); @@ -431,13 +423,10 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( #[cfg(feature = "master")] if name == sym::simd_extract { - require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { - span, - name, - in_elem, - in_ty, - ret_ty - }); + require!( + ret_ty == in_elem, + InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } + ); let vector = args[0].immediate(); return Ok(bx.context.new_vector_access(None, vector, args[1].immediate()).to_rvalue()); } @@ -445,18 +434,15 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( if name == sym::simd_select { let m_elem_ty = in_elem; let m_len = in_len; - require_simd!(arg_tys[1], InvalidMonomorphization::SimdArgument { - span, - name, - ty: arg_tys[1] - }); + require_simd!( + arg_tys[1], + InvalidMonomorphization::SimdArgument { span, name, ty: arg_tys[1] } + ); let (v_len, _) = arg_tys[1].simd_size_and_type(bx.tcx()); - require!(m_len == v_len, InvalidMonomorphization::MismatchedLengths { - span, - name, - m_len, - v_len - }); + require!( + m_len == v_len, + InvalidMonomorphization::MismatchedLengths { span, name, m_len, v_len } + ); match *m_elem_ty.kind() { ty::Int(_) => {} _ => return_error!(InvalidMonomorphization::MaskType { span, name, ty: m_elem_ty }), @@ -468,25 +454,27 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx()); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); match *in_elem.kind() { ty::RawPtr(p_ty, _) => { let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| { bx.tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), ty) }); - require!(metadata.is_unit(), InvalidMonomorphization::CastWidePointer { - span, - name, - ty: in_elem - }); + require!( + metadata.is_unit(), + InvalidMonomorphization::CastWidePointer { span, name, ty: in_elem } + ); } _ => { return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem }) @@ -497,11 +485,10 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| { bx.tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), ty) }); - require!(metadata.is_unit(), InvalidMonomorphization::CastWidePointer { - span, - name, - ty: out_elem - }); + require!( + metadata.is_unit(), + InvalidMonomorphization::CastWidePointer { span, name, ty: out_elem } + ); } _ => { return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem }) @@ -524,14 +511,17 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx()); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); match *in_elem.kind() { ty::RawPtr(_, _) => {} @@ -560,14 +550,17 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx()); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); match *in_elem.kind() { ty::Uint(ty::UintTy::Usize) => {} @@ -596,14 +589,17 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( if name == sym::simd_cast || name == sym::simd_as { require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx()); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); // casting cares about nominal type, not just structural type if in_elem == out_elem { return Ok(args[0].immediate()); @@ -629,14 +625,17 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( match (in_style, out_style) { (Style::Unsupported, Style::Unsupported) => { - require!(false, InvalidMonomorphization::UnsupportedCast { - span, - name, - in_ty, - in_elem, - ret_ty, - out_elem - }); + require!( + false, + InvalidMonomorphization::UnsupportedCast { + span, + name, + in_ty, + in_elem, + ret_ty, + out_elem + } + ); } _ => return Ok(bx.context.convert_vector(None, args[0].immediate(), llret_ty)), } @@ -914,45 +913,47 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( // All types must be simd vector types require_simd!(in_ty, InvalidMonomorphization::SimdFirst { span, name, ty: in_ty }); - require_simd!(arg_tys[1], InvalidMonomorphization::SimdSecond { - span, - name, - ty: arg_tys[1] - }); - require_simd!(arg_tys[2], InvalidMonomorphization::SimdThird { - span, - name, - ty: arg_tys[2] - }); + require_simd!( + arg_tys[1], + InvalidMonomorphization::SimdSecond { span, name, ty: arg_tys[1] } + ); + require_simd!( + arg_tys[2], + InvalidMonomorphization::SimdThird { span, name, ty: arg_tys[2] } + ); require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); // Of the same length: let (out_len, _) = arg_tys[1].simd_size_and_type(bx.tcx()); let (out_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx()); - require!(in_len == out_len, InvalidMonomorphization::SecondArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[1], - out_len - }); - require!(in_len == out_len2, InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[2], - out_len: out_len2 - }); + require!( + in_len == out_len, + InvalidMonomorphization::SecondArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[1], + out_len + } + ); + require!( + in_len == out_len2, + InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[2], + out_len: out_len2 + } + ); // The return type must match the first argument type - require!(ret_ty == in_ty, InvalidMonomorphization::ExpectedReturnType { - span, - name, - in_ty, - ret_ty - }); + require!( + ret_ty == in_ty, + InvalidMonomorphization::ExpectedReturnType { span, name, in_ty, ret_ty } + ); // This counts how many pointers fn ptr_count(t: Ty<'_>) -> usize { @@ -979,15 +980,18 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( (ptr_count(element_ty1), non_ptr(element_ty1)) } _ => { - require!(false, InvalidMonomorphization::ExpectedElementType { - span, - name, - expected_element: element_ty1, - second_arg: arg_tys[1], - in_elem, - in_ty, - mutability: ExpectedPointerMutability::Not, - }); + require!( + false, + InvalidMonomorphization::ExpectedElementType { + span, + name, + expected_element: element_ty1, + second_arg: arg_tys[1], + in_elem, + in_ty, + mutability: ExpectedPointerMutability::Not, + } + ); unreachable!(); } }; @@ -1000,12 +1004,15 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( match *element_ty2.kind() { ty::Int(_) => (), _ => { - require!(false, InvalidMonomorphization::ThirdArgElementType { - span, - name, - expected_element: element_ty2, - third_arg: arg_tys[2] - }); + require!( + false, + InvalidMonomorphization::ThirdArgElementType { + span, + name, + expected_element: element_ty2, + third_arg: arg_tys[2] + } + ); } } @@ -1029,36 +1036,40 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( // All types must be simd vector types require_simd!(in_ty, InvalidMonomorphization::SimdFirst { span, name, ty: in_ty }); - require_simd!(arg_tys[1], InvalidMonomorphization::SimdSecond { - span, - name, - ty: arg_tys[1] - }); - require_simd!(arg_tys[2], InvalidMonomorphization::SimdThird { - span, - name, - ty: arg_tys[2] - }); + require_simd!( + arg_tys[1], + InvalidMonomorphization::SimdSecond { span, name, ty: arg_tys[1] } + ); + require_simd!( + arg_tys[2], + InvalidMonomorphization::SimdThird { span, name, ty: arg_tys[2] } + ); // Of the same length: let (element_len1, _) = arg_tys[1].simd_size_and_type(bx.tcx()); let (element_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx()); - require!(in_len == element_len1, InvalidMonomorphization::SecondArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[1], - out_len: element_len1 - }); - require!(in_len == element_len2, InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[2], - out_len: element_len2 - }); + require!( + in_len == element_len1, + InvalidMonomorphization::SecondArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[1], + out_len: element_len1 + } + ); + require!( + in_len == element_len2, + InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[2], + out_len: element_len2 + } + ); // This counts how many pointers fn ptr_count(t: Ty<'_>) -> usize { @@ -1086,15 +1097,18 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( (ptr_count(element_ty1), non_ptr(element_ty1)) } _ => { - require!(false, InvalidMonomorphization::ExpectedElementType { - span, - name, - expected_element: element_ty1, - second_arg: arg_tys[1], - in_elem, - in_ty, - mutability: ExpectedPointerMutability::Mut, - }); + require!( + false, + InvalidMonomorphization::ExpectedElementType { + span, + name, + expected_element: element_ty1, + second_arg: arg_tys[1], + in_elem, + in_ty, + mutability: ExpectedPointerMutability::Mut, + } + ); unreachable!(); } }; @@ -1106,12 +1120,15 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( match *element_ty2.kind() { ty::Int(_) => (), _ => { - require!(false, InvalidMonomorphization::ThirdArgElementType { - span, - name, - expected_element: element_ty2, - third_arg: arg_tys[2] - }); + require!( + false, + InvalidMonomorphization::ThirdArgElementType { + span, + name, + expected_element: element_ty2, + third_arg: arg_tys[2] + } + ); } } @@ -1278,13 +1295,10 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( ($name:ident : $vec_op:expr, $float_reduce:ident, $ordered:expr, $op:ident, $identity:expr) => { if name == sym::$name { - require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { - span, - name, - in_elem, - in_ty, - ret_ty - }); + require!( + ret_ty == in_elem, + InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } + ); return match *in_elem.kind() { ty::Int(_) | ty::Uint(_) => { let r = bx.vector_reduce_op(args[0].immediate(), $vec_op); @@ -1350,13 +1364,10 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( macro_rules! minmax_red { ($name:ident: $int_red:ident, $float_red:ident) => { if name == sym::$name { - require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { - span, - name, - in_elem, - in_ty, - ret_ty - }); + require!( + ret_ty == in_elem, + InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } + ); return match *in_elem.kind() { ty::Int(_) | ty::Uint(_) => Ok(bx.$int_red(args[0].immediate())), ty::Float(_) => Ok(bx.$float_red(args[0].immediate())), @@ -1380,13 +1391,10 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( ($name:ident : $op:expr, $boolean:expr) => { if name == sym::$name { let input = if !$boolean { - require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { - span, - name, - in_elem, - in_ty, - ret_ty - }); + require!( + ret_ty == in_elem, + InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } + ); args[0].immediate() } else { match *in_elem.kind() { From cb499a29a8d26cf58e4b26ea70fd49c9486e7528 Mon Sep 17 00:00:00 2001 From: c8ef Date: Tue, 11 Feb 2025 03:17:38 +0800 Subject: [PATCH 028/266] remove some intrinsics (#625) --- src/builder.rs | 10 +--------- src/intrinsic/llvm.rs | 42 +----------------------------------------- 2 files changed, 2 insertions(+), 50 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index 89e5cf1b8c6b6..8268819c5faed 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -371,16 +371,8 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let previous_arg_count = args.len(); let orig_args = args; let args = { - let function_address_names = self.function_address_names.borrow(); - let original_function_name = function_address_names.get(&func_ptr); func_ptr = llvm::adjust_function(self.context, &func_name, func_ptr, args); - llvm::adjust_intrinsic_arguments( - self, - gcc_func, - args.into(), - &func_name, - original_function_name, - ) + llvm::adjust_intrinsic_arguments(self, gcc_func, args.into(), &func_name) }; let args_adjusted = args.len() != previous_arg_count; let args = self.check_ptr_call("call", func_ptr, &args); diff --git a/src/intrinsic/llvm.rs b/src/intrinsic/llvm.rs index 231307def291f..afa434ce74e39 100644 --- a/src/intrinsic/llvm.rs +++ b/src/intrinsic/llvm.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use gccjit::{CType, Context, Function, FunctionPtrType, RValue, ToRValue, UnaryOp}; +use gccjit::{CType, Context, Function, FunctionPtrType, RValue, ToRValue}; use rustc_codegen_ssa::traits::BuilderMethods; use crate::builder::Builder; @@ -43,7 +43,6 @@ pub fn adjust_intrinsic_arguments<'a, 'b, 'gcc, 'tcx>( gcc_func: FunctionPtrType<'gcc>, mut args: Cow<'b, [RValue<'gcc>]>, func_name: &str, - original_function_name: Option<&String>, ) -> Cow<'b, [RValue<'gcc>]> { // TODO: this might not be a good way to workaround the missing tile builtins. if func_name == "__builtin_trap" { @@ -541,33 +540,6 @@ pub fn adjust_intrinsic_arguments<'a, 'b, 'gcc, 'tcx>( let c = builder.context.new_rvalue_from_vector(None, arg3_type, &[new_args[2]; 2]); args = vec![a, b, c, new_args[3]].into(); } - "__builtin_ia32_vfmaddsubpd256" - | "__builtin_ia32_vfmaddsubps" - | "__builtin_ia32_vfmaddsubps256" - | "__builtin_ia32_vfmaddsubpd" => { - if let Some(original_function_name) = original_function_name { - match &**original_function_name { - "llvm.x86.fma.vfmsubadd.pd.256" - | "llvm.x86.fma.vfmsubadd.ps" - | "llvm.x86.fma.vfmsubadd.ps.256" - | "llvm.x86.fma.vfmsubadd.pd" => { - // NOTE: since both llvm.x86.fma.vfmsubadd.ps and llvm.x86.fma.vfmaddsub.ps maps to - // __builtin_ia32_vfmaddsubps, only add minus if this comes from a - // subadd LLVM intrinsic, e.g. _mm256_fmsubadd_pd. - let mut new_args = args.to_vec(); - let arg3 = &mut new_args[2]; - *arg3 = builder.context.new_unary_op( - None, - UnaryOp::Minus, - arg3.get_type(), - *arg3, - ); - args = new_args.into(); - } - _ => (), - } - } - } "__builtin_ia32_ldmxcsr" => { // The builtin __builtin_ia32_ldmxcsr takes an integer value while llvm.x86.sse.ldmxcsr takes a pointer, // so dereference the pointer. @@ -913,16 +885,6 @@ pub fn intrinsic<'gcc, 'tcx>(name: &str, cx: &CodegenCx<'gcc, 'tcx>) -> Function "llvm.ctlz.v4i64" => "__builtin_ia32_vplzcntq_256_mask", "llvm.ctlz.v2i64" => "__builtin_ia32_vplzcntq_128_mask", "llvm.ctpop.v32i16" => "__builtin_ia32_vpopcountw_v32hi", - "llvm.x86.fma.vfmsub.sd" => "__builtin_ia32_vfmsubsd3", - "llvm.x86.fma.vfmsub.ss" => "__builtin_ia32_vfmsubss3", - "llvm.x86.fma.vfmsubadd.pd" => "__builtin_ia32_vfmaddsubpd", - "llvm.x86.fma.vfmsubadd.pd.256" => "__builtin_ia32_vfmaddsubpd256", - "llvm.x86.fma.vfmsubadd.ps" => "__builtin_ia32_vfmaddsubps", - "llvm.x86.fma.vfmsubadd.ps.256" => "__builtin_ia32_vfmaddsubps256", - "llvm.x86.fma.vfnmadd.sd" => "__builtin_ia32_vfnmaddsd3", - "llvm.x86.fma.vfnmadd.ss" => "__builtin_ia32_vfnmaddss3", - "llvm.x86.fma.vfnmsub.sd" => "__builtin_ia32_vfnmsubsd3", - "llvm.x86.fma.vfnmsub.ss" => "__builtin_ia32_vfnmsubss3", "llvm.x86.avx512.conflict.d.512" => "__builtin_ia32_vpconflictsi_512_mask", "llvm.x86.avx512.conflict.d.256" => "__builtin_ia32_vpconflictsi_256_mask", "llvm.x86.avx512.conflict.d.128" => "__builtin_ia32_vpconflictsi_128_mask", @@ -1000,8 +962,6 @@ pub fn intrinsic<'gcc, 'tcx>(name: &str, cx: &CodegenCx<'gcc, 'tcx>) -> Function "llvm.fshr.v32i16" => "__builtin_ia32_vpshrdv_v32hi", "llvm.fshr.v16i16" => "__builtin_ia32_vpshrdv_v16hi", "llvm.fshr.v8i16" => "__builtin_ia32_vpshrdv_v8hi", - "llvm.x86.fma.vfmadd.sd" => "__builtin_ia32_vfmaddsd3", - "llvm.x86.fma.vfmadd.ss" => "__builtin_ia32_vfmaddss3", "llvm.x86.rdrand.64" => "__builtin_ia32_rdrand64_step", // The above doc points to unknown builtins for the following, so override them: From 65da92e77c60a7144145b02719272b2c99419705 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Mon, 10 Feb 2025 11:19:02 -0800 Subject: [PATCH 029/266] cg_gcc: stop caring about compiling for unknown targets --- src/int.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/int.rs b/src/int.rs index 4a1db8d662a9f..f3552d9b12fcb 100644 --- a/src/int.rs +++ b/src/int.rs @@ -400,7 +400,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { conv: Conv::C, can_unwind: false, }; - fn_abi.adjust_for_foreign_abi(self.cx, ExternAbi::C { unwind: false }).unwrap(); + fn_abi.adjust_for_foreign_abi(self.cx, ExternAbi::C { unwind: false }); let ret_indirect = matches!(fn_abi.ret.mode, PassMode::Indirect { .. }); From d7f2227e63c9f496837530f338fc864532907704 Mon Sep 17 00:00:00 2001 From: Askar Safin Date: Tue, 11 Feb 2025 09:47:13 +0300 Subject: [PATCH 030/266] compiler/rustc_codegen_gcc/src/back/lto.rs: delete "unsafe impl Sync/Send" --- src/back/lto.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/back/lto.rs b/src/back/lto.rs index e419bd1809900..cb4caec8c326c 100644 --- a/src/back/lto.rs +++ b/src/back/lto.rs @@ -710,10 +710,6 @@ pub struct ThinBuffer { context: Arc, } -// TODO: check if this makes sense to make ThinBuffer Send and Sync. -unsafe impl Send for ThinBuffer {} -unsafe impl Sync for ThinBuffer {} - impl ThinBuffer { pub(crate) fn new(context: &Arc) -> Self { Self { context: Arc::clone(context) } From c817210c70bed03133395890a09908ae06e44c94 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Wed, 12 Feb 2025 15:22:13 +0100 Subject: [PATCH 031/266] handle NaN in unordered comparisons --- src/builder.rs | 45 +++++++++++++++++++++++++++++++++++++- tests/failing-ui-tests.txt | 1 - tests/run/float.rs | 32 +++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 tests/run/float.rs diff --git a/src/builder.rs b/src/builder.rs index 8268819c5faed..fc2f6862c1612 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -1284,7 +1284,50 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { } fn fcmp(&mut self, op: RealPredicate, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> { - self.context.new_comparison(self.location, op.to_gcc_comparison(), lhs, rhs) + // LLVM has a concept of "unordered compares", where eg ULT returns true if either the two + // arguments are unordered (i.e. either is NaN), or the lhs is less than the rhs. GCC does + // not natively have this concept, so in some cases we must manually handle NaNs + let must_handle_nan = match op { + RealPredicate::RealPredicateFalse => unreachable!(), + RealPredicate::RealOEQ => false, + RealPredicate::RealOGT => false, + RealPredicate::RealOGE => false, + RealPredicate::RealOLT => false, + RealPredicate::RealOLE => false, + RealPredicate::RealONE => false, + RealPredicate::RealORD => unreachable!(), + RealPredicate::RealUNO => unreachable!(), + RealPredicate::RealUEQ => false, + RealPredicate::RealUGT => true, + RealPredicate::RealUGE => true, + RealPredicate::RealULT => true, + RealPredicate::RealULE => true, + RealPredicate::RealUNE => false, + RealPredicate::RealPredicateTrue => unreachable!(), + }; + + let cmp = self.context.new_comparison(self.location, op.to_gcc_comparison(), lhs, rhs); + + if must_handle_nan { + let is_nan = self.context.new_binary_op( + self.location, + BinaryOp::LogicalOr, + self.cx.bool_type, + // compare a value to itself to check whether it is NaN + self.context.new_comparison(self.location, ComparisonOp::NotEquals, lhs, lhs), + self.context.new_comparison(self.location, ComparisonOp::NotEquals, rhs, rhs), + ); + + self.context.new_binary_op( + self.location, + BinaryOp::LogicalOr, + self.cx.bool_type, + is_nan, + cmp, + ) + } else { + cmp + } } /* Miscellaneous instructions */ diff --git a/tests/failing-ui-tests.txt b/tests/failing-ui-tests.txt index 082958bfe1f85..579ac3749e95a 100644 --- a/tests/failing-ui-tests.txt +++ b/tests/failing-ui-tests.txt @@ -5,7 +5,6 @@ tests/ui/asm/x86_64/multiple-clobber-abi.rs tests/ui/functions-closures/parallel-codegen-closures.rs tests/ui/linkage-attr/linkage1.rs tests/ui/lto/dylib-works.rs -tests/ui/numbers-arithmetic/saturating-float-casts.rs tests/ui/sepcomp/sepcomp-cci.rs tests/ui/sepcomp/sepcomp-extern.rs tests/ui/sepcomp/sepcomp-fns-backwards.rs diff --git a/tests/run/float.rs b/tests/run/float.rs new file mode 100644 index 0000000000000..e0a57e6fed1a8 --- /dev/null +++ b/tests/run/float.rs @@ -0,0 +1,32 @@ +// Compiler: +// +// Run-time: +// status: 0 + +#![feature(const_black_box)] + +/* + * Code + */ + +fn main() { + use std::hint::black_box; + + macro_rules! check { + ($ty:ty, $expr:expr) => {{ + const EXPECTED: $ty = $expr; + assert_eq!($expr, EXPECTED); + }}; + } + + check!(i32, (black_box(0.0f32) as i32)); + + check!(u64, (black_box(f32::NAN) as u64)); + check!(u128, (black_box(f32::NAN) as u128)); + + check!(i64, (black_box(f64::NAN) as i64)); + check!(u64, (black_box(f64::NAN) as u64)); + + check!(i16, (black_box(f32::MIN) as i16)); + check!(i16, (black_box(f32::MAX) as i16)); +} From 4f59a687f136ac0ce29ad68ea02066e06fb9fc88 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Wed, 12 Feb 2025 19:54:51 -0500 Subject: [PATCH 032/266] Support sysv64 and ms ABIs --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- src/abi.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ src/context.rs | 8 +++++++- src/declare.rs | 25 ++++++++++++++----------- src/lib.rs | 4 ++-- 6 files changed, 74 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 636e75b94a3f2..832603aa79252 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -56,18 +56,18 @@ dependencies = [ [[package]] name = "gccjit" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72fd91f4adbf02b53cfc73c97bc33c5f253009043f30c56a5ec08dd5c8094dc8" +checksum = "2895ddec764de7ac76fe6c056050c4801a80109c066f177a00a9cc8dee02b29b" dependencies = [ "gccjit_sys", ] [[package]] name = "gccjit_sys" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fb7b8f48a75e2cfe78c3d9a980b32771c34ffd12d196021ab3f98c49fbd2f0d" +checksum = "ac133db68db8a6a8b2c51ef4b18d8ea16682d5814c4641272fe37bbbc223d5f3" dependencies = [ "libc", ] diff --git a/Cargo.toml b/Cargo.toml index 63d37358561e6..b50f2a626d57c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,7 +22,7 @@ master = ["gccjit/master"] default = ["master"] [dependencies] -gccjit = "2.4" +gccjit = "2.5" #gccjit = { git = "https://github.com/rust-lang/gccjit.rs" } # Local copy. diff --git a/src/abi.rs b/src/abi.rs index 14fc23593f0e6..35e9b356741e8 100644 --- a/src/abi.rs +++ b/src/abi.rs @@ -9,6 +9,8 @@ use rustc_middle::ty::layout::LayoutOf; #[cfg(feature = "master")] use rustc_session::config; use rustc_target::abi::call::{ArgAttributes, CastTarget, FnAbi, PassMode, Reg, RegKind}; +#[cfg(feature = "master")] +use rustc_target::callconv::Conv; use crate::builder::Builder; use crate::context::CodegenCx; @@ -104,6 +106,8 @@ pub trait FnAbiGccExt<'gcc, 'tcx> { // TODO(antoyo): return a function pointer type instead? fn gcc_type(&self, cx: &CodegenCx<'gcc, 'tcx>) -> FnAbiGcc<'gcc>; fn ptr_to_gcc_type(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Type<'gcc>; + #[cfg(feature = "master")] + fn gcc_cconv(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Option>; } impl<'gcc, 'tcx> FnAbiGccExt<'gcc, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { @@ -226,4 +230,46 @@ impl<'gcc, 'tcx> FnAbiGccExt<'gcc, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { ); pointer_type } + + #[cfg(feature = "master")] + fn gcc_cconv(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Option> { + conv_to_fn_attribute(self.conv, &cx.tcx.sess.target.arch) + } +} + +#[cfg(feature = "master")] +pub fn conv_to_fn_attribute<'gcc>(conv: Conv, _arch: &str) -> Option> { + // TODO: handle the calling conventions returning None. + let attribute = match conv { + Conv::C + | Conv::Rust + | Conv::CCmseNonSecureCall + | Conv::CCmseNonSecureEntry + | Conv::RiscvInterrupt { .. } => return None, + Conv::Cold => return None, + Conv::PreserveMost => return None, + Conv::PreserveAll => return None, + /*Conv::GpuKernel => { + if arch == "amdgpu" { + return None + } else if arch == "nvptx64" { + return None + } else { + panic!("Architecture {arch} does not support GpuKernel calling convention"); + } + }*/ + Conv::AvrInterrupt => return None, + Conv::AvrNonBlockingInterrupt => return None, + Conv::ArmAapcs => return None, + Conv::Msp430Intr => return None, + Conv::PtxKernel => return None, + Conv::X86Fastcall => return None, + Conv::X86Intr => return None, + Conv::X86Stdcall => return None, + Conv::X86ThisCall => return None, + Conv::X86VectorCall => return None, + Conv::X86_64SysV => FnAttribute::SysvAbi, + Conv::X86_64Win64 => FnAttribute::MsAbi, + }; + Some(attribute) } diff --git a/src/context.rs b/src/context.rs index 2a33beef63b99..38d012c8ca6d6 100644 --- a/src/context.rs +++ b/src/context.rs @@ -23,6 +23,8 @@ use rustc_target::spec::{ HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, Target, TlsModel, WasmCAbi, X86Abi, }; +#[cfg(feature = "master")] +use crate::abi::conv_to_fn_attribute; use crate::callee::get_fn; use crate::common::SignType; @@ -509,7 +511,11 @@ impl<'gcc, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { fn declare_c_main(&self, fn_type: Self::Type) -> Option { let entry_name = self.sess().target.entry_name.as_ref(); if !self.functions.borrow().contains_key(entry_name) { - Some(self.declare_entry_fn(entry_name, fn_type, ())) + #[cfg(feature = "master")] + let conv = conv_to_fn_attribute(self.sess().target.entry_abi, &self.sess().target.arch); + #[cfg(not(feature = "master"))] + let conv = None; + Some(self.declare_entry_fn(entry_name, fn_type, conv)) } else { // If the symbol already exists, it is an error: for example, the user wrote // #[no_mangle] extern "C" fn main(..) {..} diff --git a/src/declare.rs b/src/declare.rs index 442488b7fd650..d4a4d7f4b82f6 100644 --- a/src/declare.rs +++ b/src/declare.rs @@ -58,7 +58,7 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { variadic: bool, ) -> Function<'gcc> { self.linkage.set(FunctionType::Extern); - declare_raw_fn(self, name, () /*llvm::CCallConv*/, return_type, params, variadic) + declare_raw_fn(self, name, None, return_type, params, variadic) } pub fn declare_global( @@ -92,7 +92,8 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { &self, name: &str, _fn_type: Type<'gcc>, - callconv: (), /*llvm::CCallConv*/ + #[cfg(feature = "master")] callconv: Option>, + #[cfg(not(feature = "master"))] callconv: Option<()>, ) -> RValue<'gcc> { // TODO(antoyo): use the fn_type parameter. let const_string = self.context.new_type::().make_pointer().make_pointer(); @@ -123,14 +124,11 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { #[cfg(feature = "master")] fn_attributes, } = fn_abi.gcc_type(self); - let func = declare_raw_fn( - self, - name, - (), /*fn_abi.llvm_cconv()*/ - return_type, - &arguments_type, - is_c_variadic, - ); + #[cfg(feature = "master")] + let conv = fn_abi.gcc_cconv(self); + #[cfg(not(feature = "master"))] + let conv = None; + let func = declare_raw_fn(self, name, conv, return_type, &arguments_type, is_c_variadic); self.on_stack_function_params.borrow_mut().insert(func, on_stack_param_indices); #[cfg(feature = "master")] for fn_attr in fn_attributes { @@ -162,7 +160,8 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { fn declare_raw_fn<'gcc>( cx: &CodegenCx<'gcc, '_>, name: &str, - _callconv: (), /*llvm::CallConv*/ + #[cfg(feature = "master")] callconv: Option>, + #[cfg(not(feature = "master"))] _callconv: Option<()>, return_type: Type<'gcc>, param_types: &[Type<'gcc>], variadic: bool, @@ -192,6 +191,10 @@ fn declare_raw_fn<'gcc>( let name = &mangle_name(name); let func = cx.context.new_function(None, cx.linkage.get(), return_type, ¶ms, name, variadic); + #[cfg(feature = "master")] + if let Some(attribute) = callconv { + func.add_attribute(attribute); + } cx.functions.borrow_mut().insert(name.to_string(), func); #[cfg(feature = "master")] diff --git a/src/lib.rs b/src/lib.rs index f6ad0c79de545..68e0bc061add7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -187,10 +187,10 @@ impl CodegenBackend for GccCodegenBackend { crate::DEFAULT_LOCALE_RESOURCE } - fn init(&self, sess: &Session) { + fn init(&self, _sess: &Session) { #[cfg(feature = "master")] { - let target_cpu = target_cpu(sess); + let target_cpu = target_cpu(_sess); // Get the second TargetInfo with the correct CPU features by setting the arch. let context = Context::default(); From feb78f904e9e66e4fed9fe2e7e6363bb79d22be5 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 6 Feb 2025 20:08:29 +0000 Subject: [PATCH 033/266] Implement and use BikeshedGuaranteedNoDrop for union/unsafe field validity --- example/mini_core.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/example/mini_core.rs b/example/mini_core.rs index 5a4ee0a198cef..2ff1d757fd4e0 100644 --- a/example/mini_core.rs +++ b/example/mini_core.rs @@ -54,6 +54,9 @@ impl LegacyReceiver for Box {} #[lang = "copy"] pub trait Copy {} +#[lang = "bikeshed_guaranteed_no_drop"] +pub trait BikeshedGuaranteedNoDrop {} + impl Copy for bool {} impl Copy for u8 {} impl Copy for u16 {} From 3ecc012f6f59419fbdfddd9bac3a4b21d2275078 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Wed, 12 Feb 2025 22:05:29 +0100 Subject: [PATCH 034/266] fix clobbered or lateout registers overlapping with input registers --- libgccjit.version | 2 +- src/asm.rs | 74 ++++++++++++++++++++++++-------------- tests/failing-ui-tests.txt | 1 - tests/run/asm.rs | 31 ++++++++++++++++ 4 files changed, 80 insertions(+), 28 deletions(-) diff --git a/libgccjit.version b/libgccjit.version index 417fd5b03935d..dfdc222c00fcb 100644 --- a/libgccjit.version +++ b/libgccjit.version @@ -1 +1 @@ -e607be166673a8de9fc07f6f02c60426e556c5f2 +d6f5a708104a98199ac0f01a3b6b279a0f7c66d3 diff --git a/src/asm.rs b/src/asm.rs index 415f8affab901..9f4b84d22c08a 100644 --- a/src/asm.rs +++ b/src/asm.rs @@ -36,7 +36,8 @@ use crate::type_of::LayoutGccExt; // // 3. Clobbers. GCC has a separate list of clobbers, and clobbers don't have indexes. // Contrary, Rust expresses clobbers through "out" operands that aren't tied to -// a variable (`_`), and such "clobbers" do have index. +// a variable (`_`), and such "clobbers" do have index. Input operands cannot also +// be clobbered. // // 4. Furthermore, GCC Extended Asm does not support explicit register constraints // (like `out("eax")`) directly, offering so-called "local register variables" @@ -161,6 +162,16 @@ impl<'a, 'gcc, 'tcx> AsmBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { // Also, we don't emit any asm operands immediately; we save them to // the one of the buffers to be emitted later. + let mut input_registers = vec![]; + + for op in rust_operands { + if let InlineAsmOperandRef::In { reg, .. } = *op { + if let ConstraintOrRegister::Register(reg_name) = reg_to_gcc(reg) { + input_registers.push(reg_name); + } + } + } + // 1. Normal variables (and saving operands to buffers). for (rust_idx, op) in rust_operands.iter().enumerate() { match *op { @@ -183,25 +194,39 @@ impl<'a, 'gcc, 'tcx> AsmBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { continue; } (Register(reg_name), None) => { - // `clobber_abi` can add lots of clobbers that are not supported by the target, - // such as AVX-512 registers, so we just ignore unsupported registers - let is_target_supported = - reg.reg_class().supported_types(asm_arch, true).iter().any( - |&(_, feature)| { - if let Some(feature) = feature { - self.tcx - .asm_target_features(instance.def_id()) - .contains(&feature) - } else { - true // Register class is unconditionally supported - } - }, - ); - - if is_target_supported && !clobbers.contains(®_name) { - clobbers.push(reg_name); + if input_registers.contains(®_name) { + // the `clobber_abi` operand is converted into a series of + // `lateout("reg") _` operands. Of course, a user could also + // explicitly define such an output operand. + // + // GCC does not allow input registers to be clobbered, so if this out register + // is also used as an in register, do not add it to the clobbers list. + // it will be treated as a lateout register with `out_place: None` + if !late { + bug!("input registers can only be used as lateout regisers"); + } + ("r", dummy_output_type(self.cx, reg.reg_class())) + } else { + // `clobber_abi` can add lots of clobbers that are not supported by the target, + // such as AVX-512 registers, so we just ignore unsupported registers + let is_target_supported = + reg.reg_class().supported_types(asm_arch, true).iter().any( + |&(_, feature)| { + if let Some(feature) = feature { + self.tcx + .asm_target_features(instance.def_id()) + .contains(&feature) + } else { + true // Register class is unconditionally supported + } + }, + ); + + if is_target_supported && !clobbers.contains(®_name) { + clobbers.push(reg_name); + } + continue; } - continue; } }; @@ -230,13 +255,10 @@ impl<'a, 'gcc, 'tcx> AsmBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { } InlineAsmOperandRef::InOut { reg, late, in_value, out_place } => { - let constraint = - if let ConstraintOrRegister::Constraint(constraint) = reg_to_gcc(reg) { - constraint - } else { - // left for the next pass - continue; - }; + let ConstraintOrRegister::Constraint(constraint) = reg_to_gcc(reg) else { + // left for the next pass + continue; + }; // Rustc frontend guarantees that input and output types are "compatible", // so we can just use input var's type for the output variable. diff --git a/tests/failing-ui-tests.txt b/tests/failing-ui-tests.txt index 579ac3749e95a..0babc748f98b9 100644 --- a/tests/failing-ui-tests.txt +++ b/tests/failing-ui-tests.txt @@ -1,7 +1,6 @@ tests/ui/allocator/no_std-alloc-error-handler-custom.rs tests/ui/allocator/no_std-alloc-error-handler-default.rs tests/ui/asm/may_unwind.rs -tests/ui/asm/x86_64/multiple-clobber-abi.rs tests/ui/functions-closures/parallel-codegen-closures.rs tests/ui/linkage-attr/linkage1.rs tests/ui/lto/dylib-works.rs diff --git a/tests/run/asm.rs b/tests/run/asm.rs index 4e05d026868e7..9ede19a061f39 100644 --- a/tests/run/asm.rs +++ b/tests/run/asm.rs @@ -174,6 +174,37 @@ fn asm() { mem_cpy(array2.as_mut_ptr(), array1.as_ptr(), 3); } assert_eq!(array1, array2); + + // in and clobber registers cannot overlap. This tests that the lateout register without an + // output place (indicated by the `_`) is not added to the list of clobbered registers + let x = 8; + let y: i32; + unsafe { + asm!( + "mov rax, rdi", + in("rdi") x, + lateout("rdi") _, + out("rax") y, + ); + } + assert_eq!((x, y), (8, 8)); + + // sysv64 is the default calling convention on unix systems. The rdi register is + // used to pass arguments in the sysv64 calling convention, so this register will be clobbered + #[cfg(unix)] + { + let x = 16; + let y: i32; + unsafe { + asm!( + "mov rax, rdi", + in("rdi") x, + out("rax") y, + clobber_abi("sysv64"), + ); + } + assert_eq!((x, y), (16, 16)); + } } #[cfg(not(target_arch = "x86_64"))] From fd526a248c05b846507291a6281c06e10c2d05f7 Mon Sep 17 00:00:00 2001 From: clubby789 Date: Mon, 13 Jan 2025 15:52:08 +0000 Subject: [PATCH 035/266] Make `-O` mean `-C opt-level=3` --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index ce88ac390216a..6455bcec6851b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -476,7 +476,7 @@ fn to_gcc_opt_level(optlevel: Option) -> OptimizationLevel { Some(level) => match level { OptLevel::No => OptimizationLevel::None, OptLevel::Less => OptimizationLevel::Limited, - OptLevel::Default => OptimizationLevel::Standard, + OptLevel::More => OptimizationLevel::Standard, OptLevel::Aggressive => OptimizationLevel::Aggressive, OptLevel::Size | OptLevel::SizeMin => OptimizationLevel::Limited, }, From 5e0c773e8000c56fa1c258b57b2b64e453a3f57a Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Wed, 5 Feb 2025 03:43:54 -0800 Subject: [PATCH 036/266] Set both `nuw` and `nsw` in slice size calculation There's an old note in the code to do this, and now that LLVM-C has an API for it, we might as well. --- src/builder.rs | 26 +------------------------- 1 file changed, 1 insertion(+), 25 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index 1c3d6cc899a63..b8e37b604801f 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -665,6 +665,7 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { a + b } + // TODO(antoyo): should we also override the `unchecked_` versions? fn sub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { self.gcc_sub(a, b) } @@ -832,31 +833,6 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { set_rvalue_location(self, self.gcc_not(a)) } - fn unchecked_sadd(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { - set_rvalue_location(self, self.gcc_add(a, b)) - } - - fn unchecked_uadd(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { - set_rvalue_location(self, self.gcc_add(a, b)) - } - - fn unchecked_ssub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { - set_rvalue_location(self, self.gcc_sub(a, b)) - } - - fn unchecked_usub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { - // TODO(antoyo): should generate poison value? - set_rvalue_location(self, self.gcc_sub(a, b)) - } - - fn unchecked_smul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { - set_rvalue_location(self, self.gcc_mul(a, b)) - } - - fn unchecked_umul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { - set_rvalue_location(self, self.gcc_mul(a, b)) - } - fn fadd_fast(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> { // NOTE: it seems like we cannot enable fast-mode for a single operation in GCC. set_rvalue_location(self, lhs + rhs) From 53aa977e4bd4f5d79303061c1a6b6dbeb8cbf51c Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Thu, 13 Feb 2025 19:44:42 +0100 Subject: [PATCH 037/266] refactor and support reg_byte registers --- src/asm.rs | 215 +++++++++++++++++++++++++---------------------- tests/run/asm.rs | 22 +++++ 2 files changed, 136 insertions(+), 101 deletions(-) diff --git a/src/asm.rs b/src/asm.rs index 9f4b84d22c08a..dbdf37ee6c9ef 100644 --- a/src/asm.rs +++ b/src/asm.rs @@ -611,114 +611,127 @@ fn estimate_template_length( } /// Converts a register class to a GCC constraint code. -fn reg_to_gcc(reg: InlineAsmRegOrRegClass) -> ConstraintOrRegister { - let constraint = match reg { - // For vector registers LLVM wants the register name to match the type size. +fn reg_to_gcc(reg_or_reg_class: InlineAsmRegOrRegClass) -> ConstraintOrRegister { + match reg_or_reg_class { InlineAsmRegOrRegClass::Reg(reg) => { - match reg { - InlineAsmReg::X86(_) => { - // TODO(antoyo): add support for vector register. - // - // // For explicit registers, we have to create a register variable: https://stackoverflow.com/a/31774784/389119 - return ConstraintOrRegister::Register(match reg.name() { - // Some of registers' names does not map 1-1 from rust to gcc - "st(0)" => "st", + ConstraintOrRegister::Register(explicit_reg_to_gcc(reg)) + } + InlineAsmRegOrRegClass::RegClass(reg_class) => { + ConstraintOrRegister::Constraint(reg_class_to_gcc(reg_class)) + } + } +} - name => name, - }); +fn explicit_reg_to_gcc(reg: InlineAsmReg) -> &'static str { + // For explicit registers, we have to create a register variable: https://stackoverflow.com/a/31774784/389119 + match reg { + InlineAsmReg::X86(reg) => { + // TODO(antoyo): add support for vector register. + match reg.reg_class() { + X86InlineAsmRegClass::reg_byte => { + // GCC does not support the `b` suffix, so we just strip it + // see https://github.com/rust-lang/rustc_codegen_gcc/issues/485 + reg.name().trim_end_matches('b') } + _ => match reg.name() { + // Some of registers' names does not map 1-1 from rust to gcc + "st(0)" => "st", - _ => unimplemented!(), + name => name, + }, } } - // They can be retrieved from https://gcc.gnu.org/onlinedocs/gcc/Machine-Constraints.html - InlineAsmRegOrRegClass::RegClass(reg) => match reg { - InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => "r", - InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg) => "w", - InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => "x", - InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::preg) => { - unreachable!("clobber-only") - } - InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) => "r", - InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg) - | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16) - | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8) - | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) - | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) - | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) - | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg) - | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg) => "t", - InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg) => "r", - InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_upper) => "d", - InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_pair) => "r", - InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_iw) => "w", - InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_ptr) => "e", - InlineAsmRegClass::Bpf(BpfInlineAsmRegClass::reg) => "r", - InlineAsmRegClass::Bpf(BpfInlineAsmRegClass::wreg) => "w", - InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => "r", - InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::preg) => { - unreachable!("clobber-only") - } - InlineAsmRegClass::LoongArch(LoongArchInlineAsmRegClass::reg) => "r", - InlineAsmRegClass::LoongArch(LoongArchInlineAsmRegClass::freg) => "f", - InlineAsmRegClass::M68k(M68kInlineAsmRegClass::reg) => "r", - InlineAsmRegClass::M68k(M68kInlineAsmRegClass::reg_addr) => "a", - InlineAsmRegClass::M68k(M68kInlineAsmRegClass::reg_data) => "d", - InlineAsmRegClass::CSKY(CSKYInlineAsmRegClass::reg) => "r", - InlineAsmRegClass::CSKY(CSKYInlineAsmRegClass::freg) => "f", - InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg) => "d", // more specific than "r" - InlineAsmRegClass::Mips(MipsInlineAsmRegClass::freg) => "f", - InlineAsmRegClass::Msp430(Msp430InlineAsmRegClass::reg) => "r", - // https://github.com/gcc-mirror/gcc/blob/master/gcc/config/nvptx/nvptx.md -> look for - // "define_constraint". - InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => "h", - InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => "r", - InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => "l", - - InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg) => "r", - InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => "b", - InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::freg) => "f", - InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::vreg) => "v", - InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::cr) - | InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::xer) => { - unreachable!("clobber-only") - } - InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => "r", - InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => "f", - InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::vreg) => { - unreachable!("clobber-only") - } - InlineAsmRegClass::X86(X86InlineAsmRegClass::reg) => "r", - InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => "Q", - InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => "q", - InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg) - | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg) => "x", - InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => "v", - InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => "Yk", - InlineAsmRegClass::X86( - X86InlineAsmRegClass::kreg0 - | X86InlineAsmRegClass::x87_reg - | X86InlineAsmRegClass::mmx_reg - | X86InlineAsmRegClass::tmm_reg, - ) => unreachable!("clobber-only"), - InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => { - bug!("GCC backend does not support SPIR-V") - } - InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => "r", - InlineAsmRegClass::S390x(S390xInlineAsmRegClass::reg) => "r", - InlineAsmRegClass::S390x(S390xInlineAsmRegClass::reg_addr) => "a", - InlineAsmRegClass::S390x(S390xInlineAsmRegClass::freg) => "f", - InlineAsmRegClass::S390x(S390xInlineAsmRegClass::vreg) => "v", - InlineAsmRegClass::S390x(S390xInlineAsmRegClass::areg) => { - unreachable!("clobber-only") - } - InlineAsmRegClass::Sparc(SparcInlineAsmRegClass::reg) => "r", - InlineAsmRegClass::Sparc(SparcInlineAsmRegClass::yreg) => unreachable!("clobber-only"), - InlineAsmRegClass::Err => unreachable!(), - }, - }; - ConstraintOrRegister::Constraint(constraint) + _ => unimplemented!(), + } +} + +/// They can be retrieved from https://gcc.gnu.org/onlinedocs/gcc/Machine-Constraints.html +fn reg_class_to_gcc(reg_class: InlineAsmRegClass) -> &'static str { + match reg_class { + InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => "r", + InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg) => "w", + InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => "x", + InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::preg) => { + unreachable!("clobber-only") + } + InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) => "r", + InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg) + | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16) + | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8) + | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) + | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) + | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) + | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg) + | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg) => "t", + InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg) => "r", + InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_upper) => "d", + InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_pair) => "r", + InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_iw) => "w", + InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_ptr) => "e", + InlineAsmRegClass::Bpf(BpfInlineAsmRegClass::reg) => "r", + InlineAsmRegClass::Bpf(BpfInlineAsmRegClass::wreg) => "w", + InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => "r", + InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::preg) => { + unreachable!("clobber-only") + } + InlineAsmRegClass::LoongArch(LoongArchInlineAsmRegClass::reg) => "r", + InlineAsmRegClass::LoongArch(LoongArchInlineAsmRegClass::freg) => "f", + InlineAsmRegClass::M68k(M68kInlineAsmRegClass::reg) => "r", + InlineAsmRegClass::M68k(M68kInlineAsmRegClass::reg_addr) => "a", + InlineAsmRegClass::M68k(M68kInlineAsmRegClass::reg_data) => "d", + InlineAsmRegClass::CSKY(CSKYInlineAsmRegClass::reg) => "r", + InlineAsmRegClass::CSKY(CSKYInlineAsmRegClass::freg) => "f", + InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg) => "d", // more specific than "r" + InlineAsmRegClass::Mips(MipsInlineAsmRegClass::freg) => "f", + InlineAsmRegClass::Msp430(Msp430InlineAsmRegClass::reg) => "r", + // https://github.com/gcc-mirror/gcc/blob/master/gcc/config/nvptx/nvptx.md -> look for + // "define_constraint". + InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => "h", + InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => "r", + InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => "l", + + InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg) => "r", + InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => "b", + InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::freg) => "f", + InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::vreg) => "v", + InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::cr) + | InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::xer) => { + unreachable!("clobber-only") + } + InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => "r", + InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => "f", + InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::vreg) => { + unreachable!("clobber-only") + } + InlineAsmRegClass::X86(X86InlineAsmRegClass::reg) => "r", + InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => "Q", + InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => "q", + InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg) + | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg) => "x", + InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => "v", + InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => "Yk", + InlineAsmRegClass::X86( + X86InlineAsmRegClass::kreg0 + | X86InlineAsmRegClass::x87_reg + | X86InlineAsmRegClass::mmx_reg + | X86InlineAsmRegClass::tmm_reg, + ) => unreachable!("clobber-only"), + InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => { + bug!("GCC backend does not support SPIR-V") + } + InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => "r", + InlineAsmRegClass::S390x(S390xInlineAsmRegClass::reg) => "r", + InlineAsmRegClass::S390x(S390xInlineAsmRegClass::reg_addr) => "a", + InlineAsmRegClass::S390x(S390xInlineAsmRegClass::freg) => "f", + InlineAsmRegClass::S390x(S390xInlineAsmRegClass::vreg) => "v", + InlineAsmRegClass::S390x(S390xInlineAsmRegClass::areg) => { + unreachable!("clobber-only") + } + InlineAsmRegClass::Sparc(SparcInlineAsmRegClass::reg) => "r", + InlineAsmRegClass::Sparc(SparcInlineAsmRegClass::yreg) => unreachable!("clobber-only"), + InlineAsmRegClass::Err => unreachable!(), + } } /// Type to use for outputs that are discarded. It doesn't really matter what diff --git a/tests/run/asm.rs b/tests/run/asm.rs index 9ede19a061f39..2dbf43be664dc 100644 --- a/tests/run/asm.rs +++ b/tests/run/asm.rs @@ -205,6 +205,28 @@ fn asm() { } assert_eq!((x, y), (16, 16)); } + + // the `b` suffix for registers in the `reg_byte` register class is not supported in GCC + // and needs to be stripped in order to use these registers. + unsafe { + core::arch::asm!( + "", + out("al") _, + out("bl") _, + out("cl") _, + out("dl") _, + out("sil") _, + out("dil") _, + out("r8b") _, + out("r9b") _, + out("r10b") _, + out("r11b") _, + out("r12b") _, + out("r13b") _, + out("r14b") _, + out("r15b") _, + ); + } } #[cfg(not(target_arch = "x86_64"))] From 51911a745de6fab88f7eb75b2b8bea9787c5a153 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Fri, 14 Feb 2025 20:25:43 -0800 Subject: [PATCH 038/266] Emit `trunc nuw` for unchecked shifts and `to_immediate_scalar` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - For shifts this shrinks the IR by no longer needing an `assume` while still providing the UB information - Having this on the `i8`→`i1` truncations will hopefully help with some places that have to load `i8`s or pass those in LLVM structs without range information --- src/builder.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/builder.rs b/src/builder.rs index b8e37b604801f..76846692459d5 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -1694,7 +1694,7 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value { if scalar.is_bool() { - return self.trunc(val, self.cx().type_i1()); + return self.unchecked_utrunc(val, self.cx().type_i1()); } val } From 9ebb68ddda0247df044241daaf4856144c9c0998 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sat, 15 Feb 2025 16:07:18 -0800 Subject: [PATCH 039/266] Rework `OperandRef::extract_field` to stop calling `to_immediate_scalar` on things which are already immediates That means it stops trying to truncate things that are already `i1`s. --- src/builder.rs | 12 ++++++++---- src/intrinsic/mod.rs | 11 ++++++++--- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index 76846692459d5..c8b7616e64509 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -989,10 +989,14 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { OperandValue::Ref(place.val) } else if place.layout.is_gcc_immediate() { let load = self.load(place.layout.gcc_type(self), place.val.llval, place.val.align); - if let abi::BackendRepr::Scalar(ref scalar) = place.layout.backend_repr { - scalar_load_metadata(self, load, scalar); - } - OperandValue::Immediate(self.to_immediate(load, place.layout)) + OperandValue::Immediate( + if let abi::BackendRepr::Scalar(ref scalar) = place.layout.backend_repr { + scalar_load_metadata(self, load, scalar); + self.to_immediate_scalar(load, *scalar) + } else { + load + }, + ) } else if let abi::BackendRepr::ScalarPair(ref a, ref b) = place.layout.backend_repr { let b_offset = a.size(self).align_to(b.align(self).abi); diff --git a/src/intrinsic/mod.rs b/src/intrinsic/mod.rs index a1123fafe2f30..5322b731d8bb5 100644 --- a/src/intrinsic/mod.rs +++ b/src/intrinsic/mod.rs @@ -9,7 +9,7 @@ use gccjit::FunctionType; use gccjit::{ComparisonOp, Function, RValue, ToRValue, Type, UnaryOp}; #[cfg(feature = "master")] use rustc_abi::ExternAbi; -use rustc_abi::HasDataLayout; +use rustc_abi::{BackendRepr, HasDataLayout}; use rustc_codegen_ssa::MemFlags; use rustc_codegen_ssa::base::wants_msvc_seh; use rustc_codegen_ssa::common::IntPredicate; @@ -181,14 +181,19 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc sym::volatile_load | sym::unaligned_volatile_load => { let tp_ty = fn_args.type_at(0); let ptr = args[0].immediate(); + let layout = self.layout_of(tp_ty); let load = if let PassMode::Cast { cast: ref ty, pad_i32: _ } = fn_abi.ret.mode { let gcc_ty = ty.gcc_type(self); self.volatile_load(gcc_ty, ptr) } else { - self.volatile_load(self.layout_of(tp_ty).gcc_type(self), ptr) + self.volatile_load(layout.gcc_type(self), ptr) }; // TODO(antoyo): set alignment. - self.to_immediate(load, self.layout_of(tp_ty)) + if let BackendRepr::Scalar(scalar) = layout.backend_repr { + self.to_immediate_scalar(load, scalar) + } else { + load + } } sym::volatile_store => { let dst = args[0].deref(self.cx()); From be635722bd4264f0fd0de4cccb9ca4f9f74fafd9 Mon Sep 17 00:00:00 2001 From: Zachary S Date: Sat, 25 Jan 2025 20:15:24 -0600 Subject: [PATCH 040/266] Remove `BackendRepr::Uninhabited`, replaced with an `uninhabited: bool` field in `LayoutData`. Also update comments that refered to BackendRepr::Uninhabited. --- src/intrinsic/mod.rs | 2 +- src/type_of.rs | 13 +++++-------- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/intrinsic/mod.rs b/src/intrinsic/mod.rs index 5322b731d8bb5..433868e238a4c 100644 --- a/src/intrinsic/mod.rs +++ b/src/intrinsic/mod.rs @@ -315,7 +315,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc let layout = self.layout_of(tp_ty).layout; let _use_integer_compare = match layout.backend_repr() { Scalar(_) | ScalarPair(_, _) => true, - Uninhabited | Vector { .. } => false, + Vector { .. } => false, Memory { .. } => { // For rusty ABIs, small aggregates are actually passed // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`), diff --git a/src/type_of.rs b/src/type_of.rs index 8b8b54753e7fd..bac4fc51300a2 100644 --- a/src/type_of.rs +++ b/src/type_of.rs @@ -84,7 +84,7 @@ fn uncached_gcc_type<'gcc, 'tcx>( false, ); } - BackendRepr::Uninhabited | BackendRepr::Memory { .. } => {} + BackendRepr::Memory { .. } => {} } let name = match *layout.ty.kind() { @@ -179,19 +179,16 @@ impl<'tcx> LayoutGccExt<'tcx> for TyAndLayout<'tcx> { fn is_gcc_immediate(&self) -> bool { match self.backend_repr { BackendRepr::Scalar(_) | BackendRepr::Vector { .. } => true, - BackendRepr::ScalarPair(..) | BackendRepr::Uninhabited | BackendRepr::Memory { .. } => { - false - } + BackendRepr::ScalarPair(..) | BackendRepr::Memory { .. } => false, } } fn is_gcc_scalar_pair(&self) -> bool { match self.backend_repr { BackendRepr::ScalarPair(..) => true, - BackendRepr::Uninhabited - | BackendRepr::Scalar(_) - | BackendRepr::Vector { .. } - | BackendRepr::Memory { .. } => false, + BackendRepr::Scalar(_) | BackendRepr::Vector { .. } | BackendRepr::Memory { .. } => { + false + } } } From 3fe0b3d4d04dd86cbe22770217f3b42a8856d382 Mon Sep 17 00:00:00 2001 From: Mu001999 Date: Sun, 23 Feb 2025 11:29:35 +0800 Subject: [PATCH 041/266] not lint break with label and unsafe block --- compiler/rustc_parse/src/parser/expr.rs | 14 ++++++++------ tests/ui/lint/break-with-label-and-unsafe-block.rs | 11 +++++++++++ 2 files changed, 19 insertions(+), 6 deletions(-) create mode 100644 tests/ui/lint/break-with-label-and-unsafe-block.rs diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index e0e6c2177da54..21e01ff535a8c 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -1859,13 +1859,15 @@ impl<'a> Parser<'a> { let mut expr = self.parse_expr_opt()?; if let Some(expr) = &mut expr { if label.is_some() - && matches!( - expr.kind, + && match &expr.kind { ExprKind::While(_, _, None) - | ExprKind::ForLoop { label: None, .. } - | ExprKind::Loop(_, None, _) - | ExprKind::Block(_, None) - ) + | ExprKind::ForLoop { label: None, .. } + | ExprKind::Loop(_, None, _) => true, + ExprKind::Block(block, None) => { + matches!(block.rules, BlockCheckMode::Default) + } + _ => false, + } { self.psess.buffer_lint( BREAK_WITH_LABEL_AND_LOOP, diff --git a/tests/ui/lint/break-with-label-and-unsafe-block.rs b/tests/ui/lint/break-with-label-and-unsafe-block.rs new file mode 100644 index 0000000000000..a76a576147556 --- /dev/null +++ b/tests/ui/lint/break-with-label-and-unsafe-block.rs @@ -0,0 +1,11 @@ +//@ check-pass + +#![deny(break_with_label_and_loop)] + +unsafe fn foo() -> i32 { 42 } + +fn main () { + 'label: loop { + break 'label unsafe { foo() } + }; +} From aa038c2d95bb041a170cb1bbea8ef0fd2fd14ca4 Mon Sep 17 00:00:00 2001 From: DianQK Date: Thu, 6 Feb 2025 21:59:36 +0800 Subject: [PATCH 042/266] Add `new_regular` and `new_allocator` to `ModuleCodegen` --- src/back/lto.rs | 9 ++++----- src/base.rs | 11 +++++------ 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/back/lto.rs b/src/back/lto.rs index cb4caec8c326c..e5221c7da3197 100644 --- a/src/back/lto.rs +++ b/src/back/lto.rs @@ -632,17 +632,16 @@ pub unsafe fn optimize_thin_module( Arc::new(SyncContext::new(context)) } }; - let module = ModuleCodegen { - module_llvm: GccContext { + let module = ModuleCodegen::new_regular( + thin_module.name().to_string(), + GccContext { context, should_combine_object_files, // TODO(antoyo): use the correct relocation model here. relocation_model: RelocModel::Pic, temp_dir: None, }, - name: thin_module.name().to_string(), - kind: ModuleKind::Regular, - }; + ); /*{ let target = &*module.module_llvm.tm; let llmod = module.module_llvm.llmod(); diff --git a/src/base.rs b/src/base.rs index 962f4b161d788..9b495174a3fab 100644 --- a/src/base.rs +++ b/src/base.rs @@ -4,10 +4,10 @@ use std::sync::Arc; use std::time::Instant; use gccjit::{CType, Context, FunctionType, GlobalKind}; +use rustc_codegen_ssa::ModuleCodegen; use rustc_codegen_ssa::base::maybe_create_entry_wrapper; use rustc_codegen_ssa::mono_item::MonoItemExt; use rustc_codegen_ssa::traits::DebugInfoCodegenMethods; -use rustc_codegen_ssa::{ModuleCodegen, ModuleKind}; use rustc_middle::dep_graph; use rustc_middle::mir::mono::Linkage; #[cfg(feature = "master")] @@ -237,16 +237,15 @@ pub fn compile_codegen_unit( } } - ModuleCodegen { - name: cgu_name.to_string(), - module_llvm: GccContext { + ModuleCodegen::new_regular( + cgu_name.to_string(), + GccContext { context: Arc::new(SyncContext::new(context)), relocation_model: tcx.sess.relocation_model(), should_combine_object_files: false, temp_dir: None, }, - kind: ModuleKind::Regular, - } + ) } (module, cost) From 9b8701d27ebc49b2ade98d910b411d6f0a57a0ac Mon Sep 17 00:00:00 2001 From: DianQK Date: Thu, 6 Feb 2025 22:00:19 +0800 Subject: [PATCH 043/266] Save pre-link bitcode to `ModuleCodegen` --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 6455bcec6851b..9d91aab72ab3c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -393,7 +393,7 @@ impl WriteBackendMethods for GccCodegenBackend { unsafe fn optimize( _cgcx: &CodegenContext, _dcx: DiagCtxtHandle<'_>, - module: &ModuleCodegen, + module: &mut ModuleCodegen, config: &ModuleConfig, ) -> Result<(), FatalError> { module.module_llvm.context.set_optimization_level(to_gcc_opt_level(config.opt_level)); From 15f0dca5317ac3cac7be8f509761fa6248fad0c0 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 23 Feb 2025 17:34:50 +0100 Subject: [PATCH 044/266] remove support for rustc_intrinsic_must_be_overridden from the compiler --- example/mini_core.rs | 65 +++++++++-------------------------------- tests/run/abort1.rs | 5 +--- tests/run/abort2.rs | 5 +--- tests/run/assign.rs | 5 +--- tests/run/mut_ref.rs | 5 +--- tests/run/operations.rs | 5 +--- tests/run/static.rs | 5 +--- 7 files changed, 19 insertions(+), 76 deletions(-) diff --git a/example/mini_core.rs b/example/mini_core.rs index 2ff1d757fd4e0..3dad35bc4ce47 100644 --- a/example/mini_core.rs +++ b/example/mini_core.rs @@ -591,70 +591,31 @@ pub union MaybeUninit { pub mod intrinsics { #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } + pub fn abort() -> !; #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn size_of() -> usize { - loop {} - } + pub fn size_of() -> usize; #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn size_of_val(_val: *const T) -> usize { - loop {} - } + pub unsafe fn size_of_val(_val: *const T) -> usize; #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn min_align_of() -> usize { - loop {} - } + pub fn min_align_of() -> usize; #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn min_align_of_val(_val: *const T) -> usize { - loop {} - } + pub unsafe fn min_align_of_val(_val: *const T) -> usize; #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn copy(_src: *const T, _dst: *mut T, _count: usize) { - loop {} - } + pub unsafe fn copy(_src: *const T, _dst: *mut T, _count: usize); #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn transmute(_e: T) -> U { - loop {} - } + pub unsafe fn transmute(_e: T) -> U; #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn ctlz_nonzero(_x: T) -> u32 { - loop {} - } + pub unsafe fn ctlz_nonzero(_x: T) -> u32; #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn needs_drop() -> bool { - loop {} - } + pub fn needs_drop() -> bool; #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn bitreverse(_x: T) -> T { - loop {} - } + pub fn bitreverse(_x: T) -> T; #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn bswap(_x: T) -> T { - loop {} - } + pub fn bswap(_x: T) -> T; #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn write_bytes(_dst: *mut T, _val: u8, _count: usize) { - loop {} - } + pub unsafe fn write_bytes(_dst: *mut T, _val: u8, _count: usize); #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn unreachable() -> ! { - loop {} - } + pub unsafe fn unreachable() -> !; } pub mod libc { diff --git a/tests/run/abort1.rs b/tests/run/abort1.rs index 385e41a68817f..fe46d9ae41849 100644 --- a/tests/run/abort1.rs +++ b/tests/run/abort1.rs @@ -36,10 +36,7 @@ mod intrinsics { #[rustc_nounwind] #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } + pub fn abort() -> !; } /* diff --git a/tests/run/abort2.rs b/tests/run/abort2.rs index 6c66a930e0741..4123f4f4beebc 100644 --- a/tests/run/abort2.rs +++ b/tests/run/abort2.rs @@ -36,10 +36,7 @@ mod intrinsics { #[rustc_nounwind] #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } + pub fn abort() -> !; } /* diff --git a/tests/run/assign.rs b/tests/run/assign.rs index 4d414c577a657..286155852d50f 100644 --- a/tests/run/assign.rs +++ b/tests/run/assign.rs @@ -59,10 +59,7 @@ mod libc { mod intrinsics { #[rustc_nounwind] #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } + pub fn abort() -> !; } #[lang = "panic"] diff --git a/tests/run/mut_ref.rs b/tests/run/mut_ref.rs index 9be64f991ee08..b0215860406e5 100644 --- a/tests/run/mut_ref.rs +++ b/tests/run/mut_ref.rs @@ -61,10 +61,7 @@ mod libc { mod intrinsics { #[rustc_nounwind] #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } + pub fn abort() -> !; } #[lang = "panic"] diff --git a/tests/run/operations.rs b/tests/run/operations.rs index c92d3cc0b8fbf..8ba7a4c5ed8ce 100644 --- a/tests/run/operations.rs +++ b/tests/run/operations.rs @@ -67,10 +67,7 @@ mod libc { mod intrinsics { #[rustc_nounwind] #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } + pub fn abort() -> !; } #[lang = "panic"] diff --git a/tests/run/static.rs b/tests/run/static.rs index 80c8782c4b1a6..c3c8121b1e195 100644 --- a/tests/run/static.rs +++ b/tests/run/static.rs @@ -49,10 +49,7 @@ mod intrinsics { #[rustc_nounwind] #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } + pub fn abort() -> !; } mod libc { From e92466e22a6f98f7be019a6709b8f120cc5981a3 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 24 Feb 2025 08:07:11 +0000 Subject: [PATCH 045/266] Remove an unnecessary lifetime --- src/common.rs | 4 ++-- src/consts.rs | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/common.rs b/src/common.rs index 20a3482aaa27f..0ee13498ccade 100644 --- a/src/common.rs +++ b/src/common.rs @@ -59,7 +59,7 @@ pub fn type_is_pointer(typ: Type<'_>) -> bool { typ.get_pointee().is_some() } -impl<'gcc, 'tcx> ConstCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { +impl<'gcc, 'tcx> ConstCodegenMethods for CodegenCx<'gcc, 'tcx> { fn const_null(&self, typ: Type<'gcc>) -> RValue<'gcc> { if type_is_pointer(typ) { self.context.new_null(typ) } else { self.const_int(typ, 0) } } @@ -263,7 +263,7 @@ impl<'gcc, 'tcx> ConstCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { } } - fn const_data_from_alloc(&self, alloc: ConstAllocation<'tcx>) -> Self::Value { + fn const_data_from_alloc(&self, alloc: ConstAllocation<'_>) -> Self::Value { const_alloc_to_gcc(self, alloc) } diff --git a/src/consts.rs b/src/consts.rs index fb0ca31c54334..c514b7a428bc6 100644 --- a/src/consts.rs +++ b/src/consts.rs @@ -302,9 +302,9 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { } } -pub fn const_alloc_to_gcc<'gcc, 'tcx>( - cx: &CodegenCx<'gcc, 'tcx>, - alloc: ConstAllocation<'tcx>, +pub fn const_alloc_to_gcc<'gcc>( + cx: &CodegenCx<'gcc, '_>, + alloc: ConstAllocation<'_>, ) -> RValue<'gcc> { let alloc = alloc.inner(); let mut llvals = Vec::with_capacity(alloc.provenance().ptrs().len() + 1); From 71c189a2effd3ea4e8d4653b938c9d90cdb78845 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 24 Feb 2025 11:31:43 +0000 Subject: [PATCH 046/266] Generalize BaseTypeCodegenMethods --- src/type_.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/type_.rs b/src/type_.rs index cb08723431a9a..4e0a250b5509a 100644 --- a/src/type_.rs +++ b/src/type_.rs @@ -123,7 +123,7 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { } } -impl<'gcc, 'tcx> BaseTypeCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { +impl<'gcc, 'tcx> BaseTypeCodegenMethods for CodegenCx<'gcc, 'tcx> { fn type_i8(&self) -> Type<'gcc> { self.i8_type } From 334eb82117cddee4813e860e54d1aa9db91da461 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 24 Feb 2025 12:23:45 +0000 Subject: [PATCH 047/266] Remove an unused lifetime param --- src/abi.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/abi.rs b/src/abi.rs index 717baebcd8cd6..9fe6baa3d2573 100644 --- a/src/abi.rs +++ b/src/abi.rs @@ -16,7 +16,7 @@ use crate::context::CodegenCx; use crate::intrinsic::ArgAbiExt; use crate::type_of::LayoutGccExt; -impl<'a, 'gcc, 'tcx> AbiBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { +impl AbiBuilderMethods for Builder<'_, '_, '_> { fn get_param(&mut self, index: usize) -> Self::Value { let func = self.current_func(); let param = func.get_param(index as i32); From 78481458d172e0a85dc56a08f315d7fc6c1757cc Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Tue, 25 Feb 2025 09:20:10 +0100 Subject: [PATCH 048/266] remove `simd_fpow` and `simd_fpowi` --- src/intrinsic/simd.rs | 28 ++++++++-------------------- 1 file changed, 8 insertions(+), 20 deletions(-) diff --git a/src/intrinsic/simd.rs b/src/intrinsic/simd.rs index 84cd5b002fbb6..8b454ab2a4241 100644 --- a/src/intrinsic/simd.rs +++ b/src/intrinsic/simd.rs @@ -772,8 +772,6 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( sym::simd_floor => "floor", sym::simd_fma => "fma", sym::simd_relaxed_fma => "fma", // FIXME: this should relax to non-fused multiply-add when necessary - sym::simd_fpowi => "__builtin_powi", - sym::simd_fpow => "pow", sym::simd_fsin => "sin", sym::simd_fsqrt => "sqrt", sym::simd_round => "round", @@ -788,24 +786,16 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( let mut vector_elements = vec![]; for i in 0..in_len { let index = bx.context.new_rvalue_from_long(bx.ulong_type, i as i64); - // we have to treat fpowi specially, since fpowi's second argument is always an i32 let mut arguments = vec![]; - if name == sym::simd_fpowi { - arguments = vec![ - bx.extract_element(args[0].immediate(), index).to_rvalue(), - args[1].immediate(), - ]; - } else { - for arg in args { - let mut element = bx.extract_element(arg.immediate(), index).to_rvalue(); - // FIXME: it would probably be better to not have casts here and use the proper - // instructions. - if let Some(typ) = cast_type { - element = bx.context.new_cast(None, element, typ); - } - arguments.push(element); + for arg in args { + let mut element = bx.extract_element(arg.immediate(), index).to_rvalue(); + // FIXME: it would probably be better to not have casts here and use the proper + // instructions. + if let Some(typ) = cast_type { + element = bx.context.new_cast(None, element, typ); } - }; + arguments.push(element); + } let mut result = bx.context.new_call(None, function, &arguments); if cast_type.is_some() { result = bx.context.new_cast(None, result, elem_ty); @@ -829,8 +819,6 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( | sym::simd_floor | sym::simd_fma | sym::simd_relaxed_fma - | sym::simd_fpow - | sym::simd_fpowi | sym::simd_fsin | sym::simd_fsqrt | sym::simd_round From 7721431d57f7c8eea818d39d7a284459bb15f6e3 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Thu, 27 Feb 2025 09:09:52 -0800 Subject: [PATCH 049/266] Stop using `hash_raw_entry` in `CodegenCx::const_str` That unstable feature completed fcp-close, so the compiler needs to be migrated away to allow its removal. In this case, `cg_llvm` and `cg_gcc` were using raw entries to optimize their `const_str_cache` lookup and insertion. We can change that to separate `get` and (on miss) `insert` calls, so we still have the fast path avoiding string allocation when the cache hits. --- src/common.rs | 13 ++++++------- src/lib.rs | 2 +- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/common.rs b/src/common.rs index 20a3482aaa27f..ce1a200886478 100644 --- a/src/common.rs +++ b/src/common.rs @@ -146,13 +146,12 @@ impl<'gcc, 'tcx> ConstCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { } fn const_str(&self, s: &str) -> (RValue<'gcc>, RValue<'gcc>) { - let str_global = *self - .const_str_cache - .borrow_mut() - .raw_entry_mut() - .from_key(s) - .or_insert_with(|| (s.to_owned(), self.global_string(s))) - .1; + let mut const_str_cache = self.const_str_cache.borrow_mut(); + let str_global = const_str_cache.get(s).copied().unwrap_or_else(|| { + let g = self.global_string(s); + const_str_cache.insert(s.to_owned(), g); + g + }); let len = s.len(); let cs = self.const_ptrcast( str_global.get_address(None), diff --git a/src/lib.rs b/src/lib.rs index 6455bcec6851b..7413868767901 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,7 +16,7 @@ #![allow(internal_features)] #![doc(rust_logo)] #![feature(rustdoc_internals)] -#![feature(rustc_private, decl_macro, never_type, trusted_len, hash_raw_entry, let_chains)] +#![feature(rustc_private, decl_macro, never_type, trusted_len, let_chains)] #![allow(broken_intra_doc_links)] #![recursion_limit = "256"] #![warn(rust_2018_idioms)] From 975dee20ef70423c00a617867fa78e7ae9f63fce Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 28 Feb 2025 16:29:07 +0100 Subject: [PATCH 050/266] =?UTF-8?q?rename=20BackendRepr::Vector=20?= =?UTF-8?q?=E2=86=92=20SimdVector?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/intrinsic/mod.rs | 2 +- src/type_of.rs | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/intrinsic/mod.rs b/src/intrinsic/mod.rs index f8672c0729998..f38622074f18b 100644 --- a/src/intrinsic/mod.rs +++ b/src/intrinsic/mod.rs @@ -312,7 +312,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc let layout = self.layout_of(tp_ty).layout; let _use_integer_compare = match layout.backend_repr() { Scalar(_) | ScalarPair(_, _) => true, - Vector { .. } => false, + SimdVector { .. } => false, Memory { .. } => { // For rusty ABIs, small aggregates are actually passed // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`), diff --git a/src/type_of.rs b/src/type_of.rs index bac4fc51300a2..ae98b3d0b56e2 100644 --- a/src/type_of.rs +++ b/src/type_of.rs @@ -63,7 +63,7 @@ fn uncached_gcc_type<'gcc, 'tcx>( ) -> Type<'gcc> { match layout.backend_repr { BackendRepr::Scalar(_) => bug!("handled elsewhere"), - BackendRepr::Vector { ref element, count } => { + BackendRepr::SimdVector { ref element, count } => { let element = layout.scalar_gcc_type_at(cx, element, Size::ZERO); let element = // NOTE: gcc doesn't allow pointer types in vectors. @@ -178,7 +178,7 @@ pub trait LayoutGccExt<'tcx> { impl<'tcx> LayoutGccExt<'tcx> for TyAndLayout<'tcx> { fn is_gcc_immediate(&self) -> bool { match self.backend_repr { - BackendRepr::Scalar(_) | BackendRepr::Vector { .. } => true, + BackendRepr::Scalar(_) | BackendRepr::SimdVector { .. } => true, BackendRepr::ScalarPair(..) | BackendRepr::Memory { .. } => false, } } @@ -186,9 +186,9 @@ impl<'tcx> LayoutGccExt<'tcx> for TyAndLayout<'tcx> { fn is_gcc_scalar_pair(&self) -> bool { match self.backend_repr { BackendRepr::ScalarPair(..) => true, - BackendRepr::Scalar(_) | BackendRepr::Vector { .. } | BackendRepr::Memory { .. } => { - false - } + BackendRepr::Scalar(_) + | BackendRepr::SimdVector { .. } + | BackendRepr::Memory { .. } => false, } } From c25f12a667cd83fb79e6f7098e3191f9b1ab6416 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 2 Mar 2025 18:41:28 +0000 Subject: [PATCH 051/266] Revert "Auto merge of #135335 - oli-obk:push-zxwssomxxtnq, r=saethlin" This reverts commit a7a6c64a657f68113301c2ffe0745b49a16442d1, reversing changes made to ebbe63891f1fae21734cb97f2f863b08b1d44bf8. --- src/common.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/common.rs b/src/common.rs index 20a3482aaa27f..2052a6aa21597 100644 --- a/src/common.rs +++ b/src/common.rs @@ -64,11 +64,6 @@ impl<'gcc, 'tcx> ConstCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { if type_is_pointer(typ) { self.context.new_null(typ) } else { self.const_int(typ, 0) } } - fn is_undef(&self, _val: RValue<'gcc>) -> bool { - // FIXME: actually check for undef - false - } - fn const_undef(&self, typ: Type<'gcc>) -> RValue<'gcc> { let local = self.current_func.borrow().expect("func").new_local(None, typ, "undefined"); if typ.is_struct().is_some() { From ae07d7d368f3487999e68c5c2aa00a9ba2539905 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 25 Feb 2025 14:13:16 +1100 Subject: [PATCH 052/266] Simplify `implied_target_features`. Currently its argument is an iterator, but in practice it's always a singleton. --- src/gcc_util.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gcc_util.rs b/src/gcc_util.rs index 4e8c8aaaf5c8a..6eae0c24f48ad 100644 --- a/src/gcc_util.rs +++ b/src/gcc_util.rs @@ -48,7 +48,7 @@ pub(crate) fn global_gcc_features(sess: &Session, diagnostics: bool) -> Vec Date: Tue, 25 Feb 2025 15:25:54 +1100 Subject: [PATCH 053/266] Change signature of `target_features_cfg`. Currently it is called twice, once with `allow_unstable` set to true and once with it set to false. This results in some duplicated work. Most notably, for the LLVM backend, `LLVMRustHasFeature` is called twice for every feature, and it's moderately slow. For very short running compilations on platforms with many features (e.g. a `check` build of hello-world on x86) this is a significant fraction of runtime. This commit changes `target_features_cfg` so it is only called once, and it now returns a pair of feature sets. This halves the number of `LLVMRustHasFeature` calls. --- src/lib.rs | 68 +++++++++++++++++++++++++++++------------------------- 1 file changed, 37 insertions(+), 31 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index f090597f95335..d478b2af46c28 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -259,8 +259,8 @@ impl CodegenBackend for GccCodegenBackend { .join(sess) } - fn target_features_cfg(&self, sess: &Session, allow_unstable: bool) -> Vec { - target_features_cfg(sess, allow_unstable, &self.target_info) + fn target_features_cfg(&self, sess: &Session) -> (Vec, Vec) { + target_features_cfg(sess, &self.target_info) } } @@ -486,35 +486,41 @@ fn to_gcc_opt_level(optlevel: Option) -> OptimizationLevel { /// Returns the features that should be set in `cfg(target_feature)`. fn target_features_cfg( sess: &Session, - allow_unstable: bool, target_info: &LockedTargetInfo, -) -> Vec { +) -> (Vec, Vec) { // TODO(antoyo): use global_gcc_features. - sess.target - .rust_target_features() - .iter() - .filter_map(|&(feature, gate, _)| { - if allow_unstable - || (gate.in_cfg() && (sess.is_nightly_build() || gate.requires_nightly().is_none())) - { - Some(feature) - } else { - None - } - }) - .filter(|feature| { - // TODO: we disable Neon for now since we don't support the LLVM intrinsics for it. - if *feature == "neon" { - return false; - } - target_info.cpu_supports(feature) - /* - adx, aes, avx, avx2, avx512bf16, avx512bitalg, avx512bw, avx512cd, avx512dq, avx512er, avx512f, avx512fp16, avx512ifma, - avx512pf, avx512vbmi, avx512vbmi2, avx512vl, avx512vnni, avx512vp2intersect, avx512vpopcntdq, - bmi1, bmi2, cmpxchg16b, ermsb, f16c, fma, fxsr, gfni, lzcnt, movbe, pclmulqdq, popcnt, rdrand, rdseed, rtm, - sha, sse, sse2, sse3, sse4.1, sse4.2, sse4a, ssse3, tbm, vaes, vpclmulqdq, xsave, xsavec, xsaveopt, xsaves - */ - }) - .map(Symbol::intern) - .collect() + let f = |allow_unstable| { + sess.target + .rust_target_features() + .iter() + .filter_map(|&(feature, gate, _)| { + if allow_unstable + || (gate.in_cfg() + && (sess.is_nightly_build() || gate.requires_nightly().is_none())) + { + Some(feature) + } else { + None + } + }) + .filter(|feature| { + // TODO: we disable Neon for now since we don't support the LLVM intrinsics for it. + if *feature == "neon" { + return false; + } + target_info.cpu_supports(feature) + /* + adx, aes, avx, avx2, avx512bf16, avx512bitalg, avx512bw, avx512cd, avx512dq, avx512er, avx512f, avx512fp16, avx512ifma, + avx512pf, avx512vbmi, avx512vbmi2, avx512vl, avx512vnni, avx512vp2intersect, avx512vpopcntdq, + bmi1, bmi2, cmpxchg16b, ermsb, f16c, fma, fxsr, gfni, lzcnt, movbe, pclmulqdq, popcnt, rdrand, rdseed, rtm, + sha, sse, sse2, sse3, sse4.1, sse4.2, sse4a, ssse3, tbm, vaes, vpclmulqdq, xsave, xsavec, xsaveopt, xsaves + */ + }) + .map(Symbol::intern) + .collect() + }; + + let target_features = f(false); + let unstable_target_features = f(true); + (target_features, unstable_target_features) } From 70b588882781ff091a0bff927f8ff74c0d234798 Mon Sep 17 00:00:00 2001 From: Thalia Archibald Date: Tue, 4 Mar 2025 20:28:38 -0800 Subject: [PATCH 054/266] compiler: Use size_of from the prelude instead of imported Use `std::mem::{size_of, size_of_val, align_of, align_of_val}` from the prelude instead of importing or qualifying them. These functions were added to all preludes in Rust 1.80. --- src/builder.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index c8b7616e64509..6573b5b165e61 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -2439,9 +2439,5 @@ fn get_maybe_pointer_size(value: RValue<'_>) -> u32 { #[cfg(not(feature = "master"))] fn get_maybe_pointer_size(value: RValue<'_>) -> u32 { let type_ = value.get_type(); - if type_.get_pointee().is_some() { - std::mem::size_of::<*const ()>() as _ - } else { - type_.get_size() - } + if type_.get_pointee().is_some() { size_of::<*const ()>() as _ } else { type_.get_size() } } From 572da5cd261381451669d7d35c199e2227f9e6db Mon Sep 17 00:00:00 2001 From: Madhav Madhusoodanan Date: Sat, 8 Mar 2025 16:47:58 +0530 Subject: [PATCH 055/266] cleaned up tests by bringing objects under `mini_core` into scope --- example/mini_core.rs | 109 +++++++++--------- tests/run/abort1.rs | 41 +------ tests/run/abort2.rs | 41 +------ tests/run/array.rs | 10 +- tests/run/assign.rs | 127 +-------------------- tests/run/closure.rs | 39 ++----- tests/run/condition.rs | 26 ++--- tests/run/empty_main.rs | 30 +---- tests/run/exit.rs | 37 +------ tests/run/exit_code.rs | 30 +---- tests/run/float.rs | 4 - tests/run/fun_ptr.rs | 9 +- tests/run/int.rs | 4 - tests/run/mut_ref.rs | 131 +--------------------- tests/run/operations.rs | 225 +------------------------------------- tests/run/ptr_cast.rs | 9 +- tests/run/return-tuple.rs | 47 +------- tests/run/slice.rs | 13 +-- tests/run/static.rs | 78 +------------ tests/run/structs.rs | 45 +------- tests/run/tuple.rs | 37 +------ 21 files changed, 124 insertions(+), 968 deletions(-) diff --git a/example/mini_core.rs b/example/mini_core.rs index bd7a4612a92cc..8d749c7a8f17d 100644 --- a/example/mini_core.rs +++ b/example/mini_core.rs @@ -51,6 +51,10 @@ impl LegacyReceiver for &T {} impl LegacyReceiver for &mut T {} impl LegacyReceiver for Box {} +#[lang = "receiver"] +trait Receiver { +} + #[lang = "copy"] pub trait Copy {} @@ -139,6 +143,14 @@ impl Mul for usize { } } +impl Mul for isize { + type Output = Self; + + fn mul(self, rhs: Self) -> Self::Output { + self * rhs + } +} + #[lang = "add"] pub trait Add { type Output; @@ -162,6 +174,14 @@ impl Add for i8 { } } +impl Add for i32 { + type Output = Self; + + fn add(self, rhs: Self) -> Self { + self + rhs + } +} + impl Add for usize { type Output = Self; @@ -193,6 +213,14 @@ impl Sub for usize { } } +impl Sub for isize { + type Output = Self; + + fn sub(self, rhs: Self) -> Self { + self - rhs + } +} + impl Sub for u8 { type Output = Self; @@ -588,70 +616,43 @@ pub union MaybeUninit { pub mod intrinsics { #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } + pub fn abort() -> !; + #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn size_of() -> usize { - loop {} - } + pub fn size_of() -> usize; + #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn size_of_val(_val: *const T) -> usize { - loop {} - } + pub unsafe fn size_of_val(_val: *const T) -> usize; + #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn min_align_of() -> usize { - loop {} - } + pub fn min_align_of() -> usize; + #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn min_align_of_val(_val: *const T) -> usize { - loop {} - } + pub unsafe fn min_align_of_val(_val: *const T) -> usize; + #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn copy(_src: *const T, _dst: *mut T, _count: usize) { - loop {} - } + pub unsafe fn copy(_src: *const T, _dst: *mut T, _count: usize); + #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn transmute(_e: T) -> U { - loop {} - } + pub unsafe fn transmute(_e: T) -> U; + #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn ctlz_nonzero(_x: T) -> u32 { - loop {} - } + pub unsafe fn ctlz_nonzero(_x: T) -> u32; + #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn needs_drop() -> bool { - loop {} - } + pub fn needs_drop() -> bool; + #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn bitreverse(_x: T) -> T { - loop {} - } + pub fn bitreverse(_x: T) -> T; + #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn bswap(_x: T) -> T { - loop {} - } + pub fn bswap(_x: T) -> T; + #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn write_bytes(_dst: *mut T, _val: u8, _count: usize) { - loop {} - } + pub unsafe fn write_bytes(_dst: *mut T, _val: u8, _count: usize); + #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub unsafe fn unreachable() -> ! { - loop {} - } + pub unsafe fn unreachable() -> !; } pub mod libc { @@ -664,6 +665,10 @@ pub mod libc { pub fn memcpy(dst: *mut u8, src: *const u8, size: usize); pub fn memmove(dst: *mut u8, src: *const u8, size: usize); pub fn strncpy(dst: *mut u8, src: *const u8, size: usize); + pub fn fflush(stream: *mut i32) -> i32; + pub fn exit(status: i32); + + pub static stdout: *mut i32; } } diff --git a/tests/run/abort1.rs b/tests/run/abort1.rs index 696197d73772f..6561aaf25f6ed 100644 --- a/tests/run/abort1.rs +++ b/tests/run/abort1.rs @@ -3,47 +3,12 @@ // Run-time: // status: signal -#![feature(auto_traits, lang_items, no_core, start, intrinsics, rustc_attrs)] -#![allow(internal_features)] - +#![feature(no_core, start)] #![no_std] #![no_core] -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "copy"] -trait Copy { -} - -impl Copy for isize {} - -#[lang = "receiver"] -trait Receiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -mod intrinsics { - use super::Sized; - - #[rustc_nounwind] - #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } -} - -/* - * Code - */ +extern crate mini_core; +use mini_core::*; fn test_fail() -> ! { unsafe { intrinsics::abort() }; diff --git a/tests/run/abort2.rs b/tests/run/abort2.rs index 714cd6c0f3817..a9f176577fc79 100644 --- a/tests/run/abort2.rs +++ b/tests/run/abort2.rs @@ -3,47 +3,12 @@ // Run-time: // status: signal -#![feature(auto_traits, lang_items, no_core, start, intrinsics, rustc_attrs)] -#![allow(internal_features)] - +#![feature(no_core, start)] #![no_std] #![no_core] -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "copy"] -trait Copy { -} - -impl Copy for isize {} - -#[lang = "receiver"] -trait Receiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -mod intrinsics { - use super::Sized; - - #[rustc_nounwind] - #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } -} - -/* - * Code - */ +extern crate mini_core; +use mini_core::*; fn fail() -> i32 { unsafe { intrinsics::abort() }; diff --git a/tests/run/array.rs b/tests/run/array.rs index c3c08c29c6dba..b405102baff68 100644 --- a/tests/run/array.rs +++ b/tests/run/array.rs @@ -8,19 +8,11 @@ // 10 #![feature(no_core, start)] - #![no_std] #![no_core] extern crate mini_core; - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn printf(format: *const i8, ...) -> i32; - pub fn puts(s: *const u8) -> i32; - } -} +use mini_core::*; static mut ONE: usize = 1; diff --git a/tests/run/assign.rs b/tests/run/assign.rs index 2a47f0c2966e5..99a61337ada44 100644 --- a/tests/run/assign.rs +++ b/tests/run/assign.rs @@ -5,132 +5,12 @@ // 7 8 // 10 -#![allow(internal_features, unused_attributes)] -#![feature(auto_traits, lang_items, no_core, start, intrinsics, rustc_attrs, track_caller)] - +#![feature(no_core, start)] #![no_std] #![no_core] -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "copy"] -trait Copy { -} - -impl Copy for isize {} -impl Copy for *mut i32 {} -impl Copy for usize {} -impl Copy for u8 {} -impl Copy for i8 {} -impl Copy for i32 {} - -#[lang = "receiver"] -trait Receiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -#[lang = "panic_location"] -struct PanicLocation { - file: &'static str, - line: u32, - column: u32, -} - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn puts(s: *const u8) -> i32; - pub fn fflush(stream: *mut i32) -> i32; - pub fn printf(format: *const i8, ...) -> i32; - - pub static stdout: *mut i32; - } -} - -mod intrinsics { - #[rustc_nounwind] - #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } -} - -#[lang = "panic"] -#[track_caller] -#[no_mangle] -pub fn panic(_msg: &'static str) -> ! { - unsafe { - libc::puts("Panicking\0" as *const str as *const u8); - libc::fflush(libc::stdout); - intrinsics::abort(); - } -} - -#[lang = "add"] -trait Add { - type Output; - - fn add(self, rhs: RHS) -> Self::Output; -} - -impl Add for u8 { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for i8 { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for i32 { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for usize { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for isize { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -#[track_caller] -#[lang = "panic_const_add_overflow"] -pub fn panic_const_add_overflow() -> ! { - panic("attempt to add with overflow"); -} - -/* - * Code - */ +extern crate mini_core; +use mini_core::*; fn inc_ref(num: &mut isize) -> isize { *num = *num + 5; @@ -141,7 +21,6 @@ fn inc(num: isize) -> isize { num + 1 } - #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { argc = inc(argc); diff --git a/tests/run/closure.rs b/tests/run/closure.rs index 46c47bc54ed01..c8f06265c6b9a 100644 --- a/tests/run/closure.rs +++ b/tests/run/closure.rs @@ -9,54 +9,37 @@ // Both args: 11 #![feature(no_core, start)] - #![no_std] #![no_core] extern crate mini_core; - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn printf(format: *const i8, ...) -> i32; - } -} +use mini_core::*; #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { let string = "Arg: %d\n\0"; - let mut closure = || { - unsafe { - libc::printf(string as *const str as *const i8, argc); - } + let mut closure = || unsafe { + libc::printf(string as *const str as *const i8, argc); }; closure(); - let mut closure = || { - unsafe { - libc::printf("Argument: %d\n\0" as *const str as *const i8, argc); - } + let mut closure = || unsafe { + libc::printf("Argument: %d\n\0" as *const str as *const i8, argc); }; closure(); - let mut closure = |string| { - unsafe { - libc::printf(string as *const str as *const i8, argc); - } + let mut closure = |string| unsafe { + libc::printf(string as *const str as *const i8, argc); }; closure("String arg: %d\n\0"); - let mut closure = |arg: isize| { - unsafe { - libc::printf("Int argument: %d\n\0" as *const str as *const i8, arg); - } + let mut closure = |arg: isize| unsafe { + libc::printf("Int argument: %d\n\0" as *const str as *const i8, arg); }; closure(argc + 1); - let mut closure = |string, arg: isize| { - unsafe { - libc::printf(string as *const str as *const i8, arg); - } + let mut closure = |string, arg: isize| unsafe { + libc::printf(string as *const str as *const i8, arg); }; closure("Both args: %d\n\0", argc + 10); diff --git a/tests/run/condition.rs b/tests/run/condition.rs index 039ef94eaa717..d3714587401a8 100644 --- a/tests/run/condition.rs +++ b/tests/run/condition.rs @@ -6,18 +6,11 @@ // 1 #![feature(no_core, start)] - #![no_std] #![no_core] extern crate mini_core; - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn printf(format: *const i8, ...) -> i32; - } -} +use mini_core::*; #[start] fn main(argc: isize, _argv: *const *const u8) -> isize { @@ -26,15 +19,14 @@ fn main(argc: isize, _argv: *const *const u8) -> isize { libc::printf(b"true\n\0" as *const u8 as *const i8); } - let string = - match argc { - 1 => b"1\n\0", - 2 => b"2\n\0", - 3 => b"3\n\0", - 4 => b"4\n\0", - 5 => b"5\n\0", - _ => b"_\n\0", - }; + let string = match argc { + 1 => b"1\n\0", + 2 => b"2\n\0", + 3 => b"3\n\0", + 4 => b"4\n\0", + 5 => b"5\n\0", + _ => b"_\n\0", + }; libc::printf(string as *const u8 as *const i8); } 0 diff --git a/tests/run/empty_main.rs b/tests/run/empty_main.rs index e66a859ad698e..c4a24e9b18546 100644 --- a/tests/run/empty_main.rs +++ b/tests/run/empty_main.rs @@ -3,36 +3,12 @@ // Run-time: // status: 0 -#![feature(auto_traits, lang_items, no_core, start)] -#![allow(internal_features)] - +#![feature(no_core, start)] #![no_std] #![no_core] -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "copy"] -trait Copy { -} - -impl Copy for isize {} - -#[lang = "receiver"] -trait Receiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -/* - * Code - */ +extern crate mini_core; +use mini_core::*; #[start] fn main(_argc: isize, _argv: *const *const u8) -> isize { diff --git a/tests/run/exit.rs b/tests/run/exit.rs index bf1cbeef30205..3d66d8fbdb21a 100644 --- a/tests/run/exit.rs +++ b/tests/run/exit.rs @@ -3,43 +3,12 @@ // Run-time: // status: 2 -#![feature(auto_traits, lang_items, no_core, start, intrinsics)] -#![allow(internal_features)] - +#![feature(no_core, start)] #![no_std] #![no_core] -mod libc { - #[link(name = "c")] - extern "C" { - pub fn exit(status: i32); - } -} - -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "copy"] -trait Copy { -} - -impl Copy for isize {} - -#[lang = "receiver"] -trait Receiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -/* - * Code - */ +extern crate mini_core; +use mini_core::*; #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { diff --git a/tests/run/exit_code.rs b/tests/run/exit_code.rs index be7a233efdaaf..b18d08879f0dd 100644 --- a/tests/run/exit_code.rs +++ b/tests/run/exit_code.rs @@ -3,36 +3,12 @@ // Run-time: // status: 1 -#![feature(auto_traits, lang_items, no_core, start)] -#![allow(internal_features)] - +#![feature(no_core, start)] #![no_std] #![no_core] -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "copy"] -trait Copy { -} - -impl Copy for isize {} - -#[lang = "receiver"] -trait Receiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -/* - * Code - */ +extern crate mini_core; +use mini_core::*; #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { diff --git a/tests/run/float.rs b/tests/run/float.rs index e0a57e6fed1a8..424fa1cf4ad53 100644 --- a/tests/run/float.rs +++ b/tests/run/float.rs @@ -5,10 +5,6 @@ #![feature(const_black_box)] -/* - * Code - */ - fn main() { use std::hint::black_box; diff --git a/tests/run/fun_ptr.rs b/tests/run/fun_ptr.rs index ed1bf72bb2754..45b4ebcd9f05e 100644 --- a/tests/run/fun_ptr.rs +++ b/tests/run/fun_ptr.rs @@ -5,18 +5,11 @@ // stdout: 1 #![feature(no_core, start)] - #![no_std] #![no_core] extern crate mini_core; - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn printf(format: *const i8, ...) -> i32; - } -} +use mini_core::*; fn i16_as_i8(a: i16) -> i8 { a as i8 diff --git a/tests/run/int.rs b/tests/run/int.rs index bfe73c38435a3..47b5dea46f8de 100644 --- a/tests/run/int.rs +++ b/tests/run/int.rs @@ -5,10 +5,6 @@ #![feature(const_black_box)] -/* - * Code - */ - fn main() { use std::hint::black_box; diff --git a/tests/run/mut_ref.rs b/tests/run/mut_ref.rs index 3ae793382164b..5c91bc96ca000 100644 --- a/tests/run/mut_ref.rs +++ b/tests/run/mut_ref.rs @@ -1,4 +1,3 @@ - // Compiler: // // Run-time: @@ -7,141 +6,19 @@ // 6 // 11 -#![allow(internal_features, unused_attributes)] -#![feature(auto_traits, lang_items, no_core, start, intrinsics, rustc_attrs, track_caller)] - +#![feature(no_core, start)] #![no_std] #![no_core] -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "copy"] -trait Copy { -} - -impl Copy for isize {} -impl Copy for *mut i32 {} -impl Copy for usize {} -impl Copy for u8 {} -impl Copy for i8 {} -impl Copy for i32 {} - -#[lang = "receiver"] -trait Receiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -#[lang = "panic_location"] -struct PanicLocation { - file: &'static str, - line: u32, - column: u32, -} - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn puts(s: *const u8) -> i32; - pub fn fflush(stream: *mut i32) -> i32; - pub fn printf(format: *const i8, ...) -> i32; - - pub static stdout: *mut i32; - } -} - -mod intrinsics { - #[rustc_nounwind] - #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } -} - -#[lang = "panic"] -#[track_caller] -#[no_mangle] -pub fn panic(_msg: &'static str) -> ! { - unsafe { - libc::puts("Panicking\0" as *const str as *const u8); - libc::fflush(libc::stdout); - intrinsics::abort(); - } -} - -#[lang = "add"] -trait Add { - type Output; - - fn add(self, rhs: RHS) -> Self::Output; -} - -impl Add for u8 { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for i8 { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for i32 { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for usize { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for isize { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -#[track_caller] -#[lang = "panic_const_add_overflow"] -pub fn panic_const_add_overflow() -> ! { - panic("attempt to add with overflow"); -} - -/* - * Code - */ +extern crate mini_core; +use mini_core::*; struct Test { field: isize, } fn test(num: isize) -> Test { - Test { - field: num + 1, - } + Test { field: num + 1 } } fn update_num(num: &mut isize) { diff --git a/tests/run/operations.rs b/tests/run/operations.rs index 0e44fc580b8c4..a298cf2a68d5c 100644 --- a/tests/run/operations.rs +++ b/tests/run/operations.rs @@ -5,231 +5,12 @@ // 39 // 10 -#![allow(internal_features, unused_attributes)] -#![feature(auto_traits, lang_items, no_core, start, intrinsics, arbitrary_self_types, rustc_attrs)] - +#![feature(no_core, start)] #![no_std] #![no_core] -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "copy"] -trait Copy { -} - -impl Copy for isize {} -impl Copy for *mut i32 {} -impl Copy for usize {} -impl Copy for u8 {} -impl Copy for i8 {} -impl Copy for i16 {} -impl Copy for i32 {} - -#[lang = "deref"] -pub trait Deref { - type Target: ?Sized; - - fn deref(&self) -> &Self::Target; -} - -#[lang = "legacy_receiver"] -trait LegacyReceiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -#[lang = "panic_location"] -struct PanicLocation { - file: &'static str, - line: u32, - column: u32, -} - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn printf(format: *const i8, ...) -> i32; - pub fn puts(s: *const u8) -> i32; - pub fn fflush(stream: *mut i32) -> i32; - - pub static stdout: *mut i32; - } -} - -mod intrinsics { - #[rustc_nounwind] - #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } -} - -#[lang = "panic"] -#[track_caller] -#[no_mangle] -pub fn panic(_msg: &'static str) -> ! { - unsafe { - libc::puts("Panicking\0" as *const str as *const u8); - libc::fflush(libc::stdout); - intrinsics::abort(); - } -} - -#[lang = "add"] -trait Add { - type Output; - - fn add(self, rhs: RHS) -> Self::Output; -} - -impl Add for u8 { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for i8 { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for i32 { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for usize { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for isize { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -#[lang = "sub"] -pub trait Sub { - type Output; - - fn sub(self, rhs: RHS) -> Self::Output; -} - -impl Sub for usize { - type Output = Self; - - fn sub(self, rhs: Self) -> Self { - self - rhs - } -} - -impl Sub for isize { - type Output = Self; - - fn sub(self, rhs: Self) -> Self { - self - rhs - } -} - -impl Sub for u8 { - type Output = Self; - - fn sub(self, rhs: Self) -> Self { - self - rhs - } -} - -impl Sub for i8 { - type Output = Self; - - fn sub(self, rhs: Self) -> Self { - self - rhs - } -} - -impl Sub for i16 { - type Output = Self; - - fn sub(self, rhs: Self) -> Self { - self - rhs - } -} - -#[lang = "mul"] -pub trait Mul { - type Output; - - #[must_use] - fn mul(self, rhs: RHS) -> Self::Output; -} - -impl Mul for u8 { - type Output = Self; - - fn mul(self, rhs: Self) -> Self::Output { - self * rhs - } -} - -impl Mul for usize { - type Output = Self; - - fn mul(self, rhs: Self) -> Self::Output { - self * rhs - } -} - -impl Mul for isize { - type Output = Self; - - fn mul(self, rhs: Self) -> Self::Output { - self * rhs - } -} - -#[track_caller] -#[lang = "panic_const_add_overflow"] -pub fn panic_const_add_overflow() -> ! { - panic("attempt to add with overflow"); -} - -#[track_caller] -#[lang = "panic_const_sub_overflow"] -pub fn panic_const_sub_overflow() -> ! { - panic("attempt to subtract with overflow"); -} - -#[track_caller] -#[lang = "panic_const_mul_overflow"] -pub fn panic_const_mul_overflow() -> ! { - panic("attempt to multiply with overflow"); -} - -/* - * Code - */ +extern crate mini_core; +use mini_core::*; #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { diff --git a/tests/run/ptr_cast.rs b/tests/run/ptr_cast.rs index 2b8812ad51c5e..eb4cf3eafd0ee 100644 --- a/tests/run/ptr_cast.rs +++ b/tests/run/ptr_cast.rs @@ -5,18 +5,11 @@ // stdout: 1 #![feature(no_core, start)] - #![no_std] #![no_core] extern crate mini_core; - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn printf(format: *const i8, ...) -> i32; - } -} +use mini_core::*; static mut ONE: usize = 1; diff --git a/tests/run/return-tuple.rs b/tests/run/return-tuple.rs index f2a5a2e4384df..c3069933e0854 100644 --- a/tests/run/return-tuple.rs +++ b/tests/run/return-tuple.rs @@ -6,53 +6,12 @@ // 10 // 42 -#![feature(auto_traits, lang_items, no_core, start, intrinsics)] -#![allow(internal_features)] - +#![feature(no_core, start)] #![no_std] #![no_core] -#[lang = "copy"] -pub unsafe trait Copy {} - -impl Copy for bool {} -impl Copy for u8 {} -impl Copy for u16 {} -impl Copy for u32 {} -impl Copy for u64 {} -impl Copy for usize {} -impl Copy for i8 {} -impl Copy for i16 {} -impl Copy for i32 {} -impl Copy for isize {} -impl Copy for f32 {} -impl Copy for char {} - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn printf(format: *const i8, ...) -> i32; - } -} - -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "legacy_receiver"] -trait LegacyReceiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -/* - * Code - */ +extern crate mini_core; +use mini_core::*; fn int_cast(a: u16, b: i16) -> (u8, u16, u32, usize, i8, i16, i32, isize, u8, u32) { ( diff --git a/tests/run/slice.rs b/tests/run/slice.rs index fba93fc155495..6f2f8b9a9cec6 100644 --- a/tests/run/slice.rs +++ b/tests/run/slice.rs @@ -5,25 +5,16 @@ // stdout: 5 #![feature(no_core, start)] - #![no_std] #![no_core] extern crate mini_core; - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn printf(format: *const i8, ...) -> i32; - } -} +use mini_core::*; static mut TWO: usize = 2; fn index_slice(s: &[u32]) -> u32 { - unsafe { - s[TWO] - } + unsafe { s[TWO] } } #[start] diff --git a/tests/run/static.rs b/tests/run/static.rs index a17ea2a48936d..5fc167ce4e479 100644 --- a/tests/run/static.rs +++ b/tests/run/static.rs @@ -9,72 +9,12 @@ // 12 // 1 -#![feature(auto_traits, lang_items, no_core, start, intrinsics, rustc_attrs)] -#![allow(internal_features)] - +#![feature(no_core, start)] #![no_std] #![no_core] -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "destruct"] -pub trait Destruct {} - -#[lang = "drop"] -pub trait Drop {} - -#[lang = "copy"] -trait Copy { -} - -impl Copy for isize {} -impl Copy for *mut T {} - -#[lang = "receiver"] -trait Receiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -mod intrinsics { - use super::Sized; - - #[rustc_nounwind] - #[rustc_intrinsic] - #[rustc_intrinsic_must_be_overridden] - pub fn abort() -> ! { - loop {} - } -} - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn printf(format: *const i8, ...) -> i32; - } -} - -#[lang = "structural_peq"] -pub trait StructuralPartialEq {} - -#[lang = "drop_in_place"] -#[allow(unconditional_recursion)] -pub unsafe fn drop_in_place(to_drop: *mut T) { - // Code here does not matter - this is replaced by the - // real drop glue by the compiler. - drop_in_place(to_drop); -} - -/* - * Code - */ +extern crate mini_core; +use mini_core::*; struct Test { field: isize, @@ -86,17 +26,11 @@ struct WithRef { static mut CONSTANT: isize = 10; -static mut TEST: Test = Test { - field: 12, -}; +static mut TEST: Test = Test { field: 12 }; -static mut TEST2: Test = Test { - field: 14, -}; +static mut TEST2: Test = Test { field: 14 }; -static mut WITH_REF: WithRef = WithRef { - refe: unsafe { &TEST }, -}; +static mut WITH_REF: WithRef = WithRef { refe: unsafe { &TEST } }; #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { diff --git a/tests/run/structs.rs b/tests/run/structs.rs index d6455667400c9..641c6c71d1e02 100644 --- a/tests/run/structs.rs +++ b/tests/run/structs.rs @@ -5,43 +5,12 @@ // stdout: 1 // 2 -#![feature(auto_traits, lang_items, no_core, start, intrinsics)] -#![allow(internal_features)] - +#![feature(no_core, start)] #![no_std] #![no_core] -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "copy"] -trait Copy { -} - -impl Copy for isize {} - -#[lang = "receiver"] -trait Receiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn printf(format: *const i8, ...) -> i32; - } -} - -/* - * Code - */ +extern crate mini_core; +use mini_core::*; struct Test { field: isize, @@ -57,12 +26,8 @@ fn one() -> isize { #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { - let test = Test { - field: one(), - }; - let two = Two { - two: 2, - }; + let test = Test { field: one() }; + let two = Two { two: 2 }; unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field); libc::printf(b"%ld\n\0" as *const u8 as *const i8, two.two); diff --git a/tests/run/tuple.rs b/tests/run/tuple.rs index 8a7d85ae867e8..1f2d24eeacc51 100644 --- a/tests/run/tuple.rs +++ b/tests/run/tuple.rs @@ -4,43 +4,12 @@ // status: 0 // stdout: 3 -#![feature(auto_traits, lang_items, no_core, start, intrinsics)] -#![allow(internal_features)] - +#![feature(no_core, start)] #![no_std] #![no_core] -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "copy"] -trait Copy { -} - -impl Copy for isize {} - -#[lang = "receiver"] -trait Receiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn printf(format: *const i8, ...) -> i32; - } -} - -/* - * Code - */ +extern crate mini_core; +use mini_core::*; #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { From 7989568b8edd6531ed062614b71c327677b581ba Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 12 Mar 2025 08:03:54 +0100 Subject: [PATCH 056/266] intrinsics: remove unnecessary leading underscore from argument names --- example/mini_core.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/example/mini_core.rs b/example/mini_core.rs index 3dad35bc4ce47..5544aee9eaf16 100644 --- a/example/mini_core.rs +++ b/example/mini_core.rs @@ -595,25 +595,25 @@ pub mod intrinsics { #[rustc_intrinsic] pub fn size_of() -> usize; #[rustc_intrinsic] - pub unsafe fn size_of_val(_val: *const T) -> usize; + pub unsafe fn size_of_val(val: *const T) -> usize; #[rustc_intrinsic] pub fn min_align_of() -> usize; #[rustc_intrinsic] - pub unsafe fn min_align_of_val(_val: *const T) -> usize; + pub unsafe fn min_align_of_val(val: *const T) -> usize; #[rustc_intrinsic] - pub unsafe fn copy(_src: *const T, _dst: *mut T, _count: usize); + pub unsafe fn copy(src: *const T, dst: *mut T, count: usize); #[rustc_intrinsic] - pub unsafe fn transmute(_e: T) -> U; + pub unsafe fn transmute(e: T) -> U; #[rustc_intrinsic] - pub unsafe fn ctlz_nonzero(_x: T) -> u32; + pub unsafe fn ctlz_nonzero(x: T) -> u32; #[rustc_intrinsic] pub fn needs_drop() -> bool; #[rustc_intrinsic] - pub fn bitreverse(_x: T) -> T; + pub fn bitreverse(x: T) -> T; #[rustc_intrinsic] - pub fn bswap(_x: T) -> T; + pub fn bswap(x: T) -> T; #[rustc_intrinsic] - pub unsafe fn write_bytes(_dst: *mut T, _val: u8, _count: usize); + pub unsafe fn write_bytes(dst: *mut T, val: u8, count: usize); #[rustc_intrinsic] pub unsafe fn unreachable() -> !; } From 8e235258f38e43c4b565c5393d96aa5381d366bf Mon Sep 17 00:00:00 2001 From: Adwin White Date: Mon, 17 Mar 2025 18:17:09 +0800 Subject: [PATCH 057/266] fix(debuginfo): avoid overflow when handling expanding recursive type --- .../src/debuginfo/metadata/type_map.rs | 48 +++++++++++++++++++ .../rustc_codegen_llvm/src/debuginfo/mod.rs | 2 + tests/debuginfo/recursive-enum.rs | 17 ++++++- 3 files changed, 66 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs index af1d503ad6a43..8fd13eee379de 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs @@ -247,6 +247,16 @@ pub(super) fn stub<'ll, 'tcx>( StubInfo { metadata, unique_type_id } } +struct AdtStackPopGuard<'ll, 'tcx, 'a> { + cx: &'a CodegenCx<'ll, 'tcx>, +} + +impl<'ll, 'tcx, 'a> Drop for AdtStackPopGuard<'ll, 'tcx, 'a> { + fn drop(&mut self) { + debug_context(self.cx).adt_stack.borrow_mut().pop(); + } +} + /// This function enables creating debuginfo nodes that can recursively refer to themselves. /// It will first insert the given stub into the type map and only then execute the `members` /// and `generics` closures passed in. These closures have access to the stub so they can @@ -261,6 +271,44 @@ pub(super) fn build_type_with_children<'ll, 'tcx>( ) -> DINodeCreationResult<'ll> { assert_eq!(debug_context(cx).type_map.di_node_for_unique_id(stub_info.unique_type_id), None); + let mut _adt_stack_pop_guard = None; + if let UniqueTypeId::Ty(ty, ..) = stub_info.unique_type_id + && let ty::Adt(adt_def, args) = ty.kind() + { + let def_id = adt_def.did(); + // If any sub type reference the original type definition and the sub type has a type + // parameter that strictly contains the original parameter, the original type is a recursive + // type that can expanding indefinitely. Example, + // ``` + // enum Recursive { + // Recurse(*const Recursive>), + // Item(T), + // } + // ``` + let is_expanding_recursive = + debug_context(cx).adt_stack.borrow().iter().any(|(parent_def_id, parent_args)| { + if def_id == *parent_def_id { + args.iter().zip(parent_args.iter()).any(|(arg, parent_arg)| { + if let (Some(arg), Some(parent_arg)) = (arg.as_type(), parent_arg.as_type()) + { + arg != parent_arg && arg.contains(parent_arg) + } else { + false + } + }) + } else { + false + } + }); + if is_expanding_recursive { + // FIXME: indicate that this is an expanding recursive type in stub metadata? + return DINodeCreationResult::new(stub_info.metadata, false); + } else { + debug_context(cx).adt_stack.borrow_mut().push((def_id, args)); + _adt_stack_pop_guard = Some(AdtStackPopGuard { cx }); + } + } + debug_context(cx).type_map.insert(stub_info.unique_type_id, stub_info.metadata); let members: SmallVec<_> = diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index 10819a53b1df8..bbe69382d0841 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -65,6 +65,7 @@ pub(crate) struct CodegenUnitDebugContext<'ll, 'tcx> { created_files: RefCell, &'ll DIFile>>, type_map: metadata::TypeMap<'ll, 'tcx>, + adt_stack: RefCell)>>, namespace_map: RefCell>, recursion_marker_type: OnceCell<&'ll DIType>, } @@ -79,6 +80,7 @@ impl<'ll, 'tcx> CodegenUnitDebugContext<'ll, 'tcx> { builder, created_files: Default::default(), type_map: Default::default(), + adt_stack: Default::default(), namespace_map: RefCell::new(Default::default()), recursion_marker_type: OnceCell::new(), } diff --git a/tests/debuginfo/recursive-enum.rs b/tests/debuginfo/recursive-enum.rs index c2c3e71b8a4f8..b861e6d617c88 100644 --- a/tests/debuginfo/recursive-enum.rs +++ b/tests/debuginfo/recursive-enum.rs @@ -4,7 +4,7 @@ // gdb-command:run // Test whether compiling a recursive enum definition crashes debug info generation. The test case -// is taken from issue #11083. +// is taken from issue #11083 and #135093. #![allow(unused_variables)] #![feature(omit_gdb_pretty_printer_section)] @@ -18,6 +18,21 @@ struct WindowCallbacks<'a> { pos_callback: Option>, } +enum ExpandingRecursive { + Recurse(Indirect), + Item(T), +} + +struct Indirect { + rec: *const ExpandingRecursive>, +} + + fn main() { let x = WindowCallbacks { pos_callback: None }; + + // EXPANDING RECURSIVE + let expanding_recursive: ExpandingRecursive = ExpandingRecursive::Recurse(Indirect { + rec: &ExpandingRecursive::Item(Option::Some(42)), + }); } From d5c4ed04842235b08119fde271151f7f17b57139 Mon Sep 17 00:00:00 2001 From: Adwin White Date: Mon, 17 Mar 2025 19:43:31 +0800 Subject: [PATCH 058/266] (re)move fixed crash tests --- tests/crashes/100618.rs | 12 -------- tests/crashes/115994.rs | 17 ----------- tests/crashes/121538.rs | 30 ------------------- .../recursive-type-with-gat.rs} | 1 - 4 files changed, 60 deletions(-) delete mode 100644 tests/crashes/100618.rs delete mode 100644 tests/crashes/115994.rs delete mode 100644 tests/crashes/121538.rs rename tests/{crashes/107362.rs => debuginfo/recursive-type-with-gat.rs} (96%) diff --git a/tests/crashes/100618.rs b/tests/crashes/100618.rs deleted file mode 100644 index 911c4098badc0..0000000000000 --- a/tests/crashes/100618.rs +++ /dev/null @@ -1,12 +0,0 @@ -//@ known-bug: #100618 -//@ compile-flags: -Cdebuginfo=2 - -//@ only-x86_64 -enum Foo { - Value(T), - Recursive(&'static Foo>), -} - -fn main() { - let _x = Foo::Value(()); -} diff --git a/tests/crashes/115994.rs b/tests/crashes/115994.rs deleted file mode 100644 index 23d1507136f7c..0000000000000 --- a/tests/crashes/115994.rs +++ /dev/null @@ -1,17 +0,0 @@ -//@ known-bug: #115994 -//@ compile-flags: -Cdebuginfo=2 --crate-type lib - -// To prevent "overflow while adding drop-check rules". -use std::mem::ManuallyDrop; - -pub enum Foo { - Leaf(U), - - Branch(BoxedFoo>), -} - -pub type BoxedFoo = ManuallyDrop>>; - -pub fn test() -> Foo { - todo!() -} diff --git a/tests/crashes/121538.rs b/tests/crashes/121538.rs deleted file mode 100644 index f18bad84b5724..0000000000000 --- a/tests/crashes/121538.rs +++ /dev/null @@ -1,30 +0,0 @@ -//@ known-bug: #121538 -//@ compile-flags: -Cdebuginfo=2 - -use std::marker::PhantomData; - -struct Digit { - elem: T -} - -struct Node { m: PhantomData<&'static T> } - -enum FingerTree { - Single(T), - - Deep( - Digit, - Node>>, - ) -} - -enum Wrapper { - Simple, - Other(FingerTree), -} - -fn main() { - let w = - Some(Wrapper::Simple::); - -} diff --git a/tests/crashes/107362.rs b/tests/debuginfo/recursive-type-with-gat.rs similarity index 96% rename from tests/crashes/107362.rs rename to tests/debuginfo/recursive-type-with-gat.rs index 8d55d611eb133..b8a67d8d24b4c 100644 --- a/tests/crashes/107362.rs +++ b/tests/debuginfo/recursive-type-with-gat.rs @@ -1,4 +1,3 @@ -//@ known-bug: #107362 //@ compile-flags: -Cdebuginfo=2 pub trait Functor From b25a593b40e88019a5c76198f5c69e2fcced368d Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sat, 2 Dec 2023 14:17:33 +0000 Subject: [PATCH 059/266] Remove implicit #[no_mangle] for #[rustc_std_internal_symbol] --- src/allocator.rs | 13 +++++++------ src/lib.rs | 1 + 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/allocator.rs b/src/allocator.rs index 416f3231a13c4..f4ebd42ee2dc0 100644 --- a/src/allocator.rs +++ b/src/allocator.rs @@ -8,6 +8,7 @@ use rustc_ast::expand::allocator::{ use rustc_middle::bug; use rustc_middle::ty::TyCtxt; use rustc_session::config::OomStrategy; +use rustc_symbol_mangling::mangle_internal_symbol; use crate::GccContext; #[cfg(feature = "master")] @@ -53,8 +54,8 @@ pub(crate) unsafe fn codegen( panic!("invalid allocator output") } }; - let from_name = global_fn_name(method.name); - let to_name = default_fn_name(method.name); + let from_name = mangle_internal_symbol(tcx, &global_fn_name(method.name)); + let to_name = mangle_internal_symbol(tcx, &default_fn_name(method.name)); create_wrapper_function(tcx, context, &from_name, &to_name, &types, output); } @@ -64,13 +65,13 @@ pub(crate) unsafe fn codegen( create_wrapper_function( tcx, context, - "__rust_alloc_error_handler", - alloc_error_handler_name(alloc_error_handler_kind), + &mangle_internal_symbol(tcx, "__rust_alloc_error_handler"), + &mangle_internal_symbol(tcx, alloc_error_handler_name(alloc_error_handler_kind)), &[usize, usize], None, ); - let name = OomStrategy::SYMBOL.to_string(); + let name = mangle_internal_symbol(tcx, OomStrategy::SYMBOL); let global = context.new_global(None, GlobalKind::Exported, i8, name); #[cfg(feature = "master")] global.add_attribute(VarAttribute::Visibility(symbol_visibility_to_gcc( @@ -80,7 +81,7 @@ pub(crate) unsafe fn codegen( let value = context.new_rvalue_from_int(i8, value as i32); global.global_set_initializer_rvalue(value); - let name = NO_ALLOC_SHIM_IS_UNSTABLE.to_string(); + let name = mangle_internal_symbol(tcx, NO_ALLOC_SHIM_IS_UNSTABLE); let global = context.new_global(None, GlobalKind::Exported, i8, name); #[cfg(feature = "master")] global.add_attribute(VarAttribute::Visibility(symbol_visibility_to_gcc( diff --git a/src/lib.rs b/src/lib.rs index d478b2af46c28..bfa23174a19d9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -52,6 +52,7 @@ extern crate rustc_metadata; extern crate rustc_middle; extern crate rustc_session; extern crate rustc_span; +extern crate rustc_symbol_mangling; extern crate rustc_target; // This prevents duplicating functions and statics that are already part of the host rustc process. From 5743d381af27a24d12e5272043fa4e21dfa5794a Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Mon, 19 Aug 2024 15:20:02 +0200 Subject: [PATCH 060/266] Rename `is_like_osx` to `is_like_darwin` --- src/consts.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/consts.rs b/src/consts.rs index c514b7a428bc6..0dc0a91829886 100644 --- a/src/consts.rs +++ b/src/consts.rs @@ -131,7 +131,7 @@ impl<'gcc, 'tcx> StaticCodegenMethods for CodegenCx<'gcc, 'tcx> { // will use load-unaligned instructions instead, and thus avoiding the crash. // // We could remove this hack whenever we decide to drop macOS 10.10 support. - if self.tcx.sess.target.options.is_like_osx { + if self.tcx.sess.target.options.is_like_darwin { // The `inspect` method is okay here because we checked for provenance, and // because we are doing this access to inspect the final interpreter state // (not as part of the interpreter execution). From 2f5aa084c8bb6e1a4b014396a44087fd65a4c1c8 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 14 Mar 2025 15:56:33 +0000 Subject: [PATCH 061/266] Avoid wrapping constant allocations in packed structs when not necessary This way LLVM will set the string merging flag if the alloc is a nul terminated string, reducing binary sizes. --- src/consts.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/consts.rs b/src/consts.rs index c514b7a428bc6..474475f311f71 100644 --- a/src/consts.rs +++ b/src/consts.rs @@ -364,6 +364,7 @@ pub fn const_alloc_to_gcc<'gcc>( llvals.push(cx.const_bytes(bytes)); } + // FIXME(bjorn3) avoid wrapping in a struct when there is only a single element. cx.const_struct(&llvals, true) } From 54bb849affcbede09ab1327c6cd996e5c5948cdd Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Fri, 28 Mar 2025 22:31:20 +0300 Subject: [PATCH 062/266] hygiene: Rename semi-transparent to semi-opaque The former is just too long, see the examples in `hygiene.rs` --- .../src/attributes/transparency.rs | 2 +- compiler/rustc_feature/src/builtin_attrs.rs | 2 +- compiler/rustc_resolve/src/lib.rs | 6 +-- compiler/rustc_span/src/hygiene.rs | 47 +++++++++---------- compiler/rustc_span/src/lib.rs | 2 +- compiler/rustc_span/src/symbol.rs | 1 + tests/ui/hygiene/rustc-macro-transparency.rs | 12 ++--- .../hygiene/rustc-macro-transparency.stderr | 12 ++--- tests/ui/hygiene/unpretty-debug.stdout | 2 +- tests/ui/proc-macro/meta-macro-hygiene.stdout | 6 +-- .../nonterminal-token-hygiene.stdout | 4 +- 11 files changed, 48 insertions(+), 48 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/transparency.rs b/compiler/rustc_attr_parsing/src/attributes/transparency.rs index ad83a1f7af80c..ce42b0507ed57 100644 --- a/compiler/rustc_attr_parsing/src/attributes/transparency.rs +++ b/compiler/rustc_attr_parsing/src/attributes/transparency.rs @@ -20,7 +20,7 @@ impl SingleAttributeParser for TransparencyParser { fn convert(cx: &AcceptContext<'_>, args: &ArgParser<'_>) -> Option { match args.name_value().and_then(|nv| nv.value_as_str()) { Some(sym::transparent) => Some(Transparency::Transparent), - Some(sym::semitransparent) => Some(Transparency::SemiTransparent), + Some(sym::semiopaque | sym::semitransparent) => Some(Transparency::SemiOpaque), Some(sym::opaque) => Some(Transparency::Opaque), Some(other) => { cx.dcx().span_err(cx.attr_span, format!("unknown macro transparency: `{other}`")); diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 1e33e2e9393f7..a8f0da736c637 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -752,7 +752,7 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ ), rustc_attr!( rustc_macro_transparency, Normal, - template!(NameValueStr: "transparent|semitransparent|opaque"), ErrorFollowing, + template!(NameValueStr: "transparent|semiopaque|opaque"), ErrorFollowing, EncodeCrossCrate::Yes, "used internally for testing macro hygiene", ), rustc_attr!( diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 612e091770f0a..1eac3f848b622 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1998,16 +1998,16 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { result, result.map(|r| r.expn_data()) ); - // Then find the last semi-transparent mark from the end if it exists. + // Then find the last semi-opaque mark from the end if it exists. for (mark, transparency) in iter { - if transparency == Transparency::SemiTransparent { + if transparency == Transparency::SemiOpaque { result = Some(mark); } else { break; } } debug!( - "resolve_crate_root: found semi-transparent mark {:?} {:?}", + "resolve_crate_root: found semi-opaque mark {:?} {:?}", result, result.map(|r| r.expn_data()) ); diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index e7a8dee27f568..c2e7cb4577553 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -66,10 +66,10 @@ pub struct SyntaxContextData { outer_expn: ExpnId, outer_transparency: Transparency, parent: SyntaxContext, - /// This context, but with all transparent and semi-transparent expansions filtered away. + /// This context, but with all transparent and semi-opaque expansions filtered away. opaque: SyntaxContext, /// This context, but with all transparent expansions filtered away. - opaque_and_semitransparent: SyntaxContext, + opaque_and_semiopaque: SyntaxContext, /// Name of the crate to which `$crate` with this context would resolve. dollar_crate_name: Symbol, } @@ -78,14 +78,14 @@ impl SyntaxContextData { fn new( (parent, outer_expn, outer_transparency): SyntaxContextKey, opaque: SyntaxContext, - opaque_and_semitransparent: SyntaxContext, + opaque_and_semiopaque: SyntaxContext, ) -> SyntaxContextData { SyntaxContextData { outer_expn, outer_transparency, parent, opaque, - opaque_and_semitransparent, + opaque_and_semiopaque, dollar_crate_name: kw::DollarCrate, } } @@ -96,7 +96,7 @@ impl SyntaxContextData { outer_transparency: Transparency::Opaque, parent: SyntaxContext::root(), opaque: SyntaxContext::root(), - opaque_and_semitransparent: SyntaxContext::root(), + opaque_and_semiopaque: SyntaxContext::root(), dollar_crate_name: kw::DollarCrate, } } @@ -207,13 +207,13 @@ pub enum Transparency { /// Identifier produced by a transparent expansion is always resolved at call-site. /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this. Transparent, - /// Identifier produced by a semi-transparent expansion may be resolved + /// Identifier produced by a semi-opaque expansion may be resolved /// either at call-site or at definition-site. /// If it's a local variable, label or `$crate` then it's resolved at def-site. /// Otherwise it's resolved at call-site. /// `macro_rules` macros behave like this, built-in macros currently behave like this too, /// but that's an implementation detail. - SemiTransparent, + SemiOpaque, /// Identifier produced by an opaque expansion is always resolved at definition-site. /// Def-site spans in procedural macros, identifiers from `macro` by default use this. Opaque, @@ -221,7 +221,7 @@ pub enum Transparency { impl Transparency { pub fn fallback(macro_rules: bool) -> Self { - if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque } + if macro_rules { Transparency::SemiOpaque } else { Transparency::Opaque } } } @@ -469,7 +469,7 @@ impl HygieneData { fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext { debug_assert!(!self.syntax_context_data[ctxt.0 as usize].is_decode_placeholder()); - self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent + self.syntax_context_data[ctxt.0 as usize].opaque_and_semiopaque } fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId { @@ -562,7 +562,7 @@ impl HygieneData { } let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt(); - let mut call_site_ctxt = if transparency == Transparency::SemiTransparent { + let mut call_site_ctxt = if transparency == Transparency::SemiOpaque { self.normalize_to_macros_2_0(call_site_ctxt) } else { self.normalize_to_macro_rules(call_site_ctxt) @@ -608,33 +608,32 @@ impl HygieneData { self.syntax_context_data.push(SyntaxContextData::decode_placeholder()); self.syntax_context_map.insert(key, ctxt); - // Opaque and semi-transparent versions of the parent. Note that they may be equal to the + // Opaque and semi-opaque versions of the parent. Note that they may be equal to the // parent itself. E.g. `parent_opaque` == `parent` if the expn chain contains only opaques, - // and `parent_opaque_and_semitransparent` == `parent` if the expn contains only opaques - // and semi-transparents. + // and `parent_opaque_and_semiopaque` == `parent` if the expn contains only (semi-)opaques. let parent_opaque = self.syntax_context_data[parent.0 as usize].opaque; - let parent_opaque_and_semitransparent = - self.syntax_context_data[parent.0 as usize].opaque_and_semitransparent; + let parent_opaque_and_semiopaque = + self.syntax_context_data[parent.0 as usize].opaque_and_semiopaque; - // Evaluate opaque and semi-transparent versions of the new syntax context. - let (opaque, opaque_and_semitransparent) = match transparency { - Transparency::Transparent => (parent_opaque, parent_opaque_and_semitransparent), - Transparency::SemiTransparent => ( + // Evaluate opaque and semi-opaque versions of the new syntax context. + let (opaque, opaque_and_semiopaque) = match transparency { + Transparency::Transparent => (parent_opaque, parent_opaque_and_semiopaque), + Transparency::SemiOpaque => ( parent_opaque, - // Will be the same as `ctxt` if the expn chain contains only opaques and semi-transparents. - self.alloc_ctxt(parent_opaque_and_semitransparent, expn_id, transparency), + // Will be the same as `ctxt` if the expn chain contains only (semi-)opaques. + self.alloc_ctxt(parent_opaque_and_semiopaque, expn_id, transparency), ), Transparency::Opaque => ( // Will be the same as `ctxt` if the expn chain contains only opaques. self.alloc_ctxt(parent_opaque, expn_id, transparency), - // Will be the same as `ctxt` if the expn chain contains only opaques and semi-transparents. - self.alloc_ctxt(parent_opaque_and_semitransparent, expn_id, transparency), + // Will be the same as `ctxt` if the expn chain contains only (semi-)opaques. + self.alloc_ctxt(parent_opaque_and_semiopaque, expn_id, transparency), ), }; // Fill the full data, now that we have it. self.syntax_context_data[ctxt.as_u32() as usize] = - SyntaxContextData::new(key, opaque, opaque_and_semitransparent); + SyntaxContextData::new(key, opaque, opaque_and_semiopaque); ctxt } } diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 9e6ba2e1b9ce2..625ece787b909 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -1112,7 +1112,7 @@ impl Span { /// Equivalent of `Span::mixed_site` from the proc macro API, /// except that the location is taken from the `self` span. pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span { - self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent) + self.with_ctxt_from_mark(expn_id, Transparency::SemiOpaque) } /// Produces a span with the same location as `self` and context produced by a macro with the diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 47dd80c432ead..02f89c527e637 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1871,6 +1871,7 @@ symbols! { select_unpredictable, self_in_typedefs, self_struct_ctor, + semiopaque, semitransparent, sha2, sha3, diff --git a/tests/ui/hygiene/rustc-macro-transparency.rs b/tests/ui/hygiene/rustc-macro-transparency.rs index 5f36993af2f30..1a78a7543cfdc 100644 --- a/tests/ui/hygiene/rustc-macro-transparency.rs +++ b/tests/ui/hygiene/rustc-macro-transparency.rs @@ -6,9 +6,9 @@ macro transparent() { let transparent = 0; } #[rustc_macro_transparency = "semitransparent"] -macro semitransparent() { - struct SemiTransparent; - let semitransparent = 0; +macro semiopaque() { + struct SemiOpaque; + let semiopaque = 0; } #[rustc_macro_transparency = "opaque"] macro opaque() { @@ -18,14 +18,14 @@ macro opaque() { fn main() { transparent!(); - semitransparent!(); + semiopaque!(); opaque!(); Transparent; // OK - SemiTransparent; // OK + SemiOpaque; // OK Opaque; //~ ERROR cannot find value `Opaque` in this scope transparent; // OK - semitransparent; //~ ERROR expected value, found macro `semitransparent` + semiopaque; //~ ERROR expected value, found macro `semiopaque` opaque; //~ ERROR expected value, found macro `opaque` } diff --git a/tests/ui/hygiene/rustc-macro-transparency.stderr b/tests/ui/hygiene/rustc-macro-transparency.stderr index 1d2a1e1249864..1bea8a0ee4f31 100644 --- a/tests/ui/hygiene/rustc-macro-transparency.stderr +++ b/tests/ui/hygiene/rustc-macro-transparency.stderr @@ -4,17 +4,17 @@ error[E0425]: cannot find value `Opaque` in this scope LL | Opaque; | ^^^^^^ not found in this scope -error[E0423]: expected value, found macro `semitransparent` +error[E0423]: expected value, found macro `semiopaque` --> $DIR/rustc-macro-transparency.rs:29:5 | -LL | struct SemiTransparent; - | ----------------------- similarly named unit struct `SemiTransparent` defined here +LL | struct SemiOpaque; + | ------------------ similarly named unit struct `SemiOpaque` defined here ... -LL | semitransparent; - | ^^^^^^^^^^^^^^^ +LL | semiopaque; + | ^^^^^^^^^^ | | | not a value - | help: a unit struct with a similar name exists: `SemiTransparent` + | help: a unit struct with a similar name exists (notice the capitalization): `SemiOpaque` error[E0423]: expected value, found macro `opaque` --> $DIR/rustc-macro-transparency.rs:30:5 diff --git a/tests/ui/hygiene/unpretty-debug.stdout b/tests/ui/hygiene/unpretty-debug.stdout index e475cfac2fc17..f35bd7a7cb2ca 100644 --- a/tests/ui/hygiene/unpretty-debug.stdout +++ b/tests/ui/hygiene/unpretty-debug.stdout @@ -24,5 +24,5 @@ crate0::{{expn1}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: SyntaxContexts: #0: parent: #0, outer_mark: (crate0::{{expn0}}, Opaque) -#1: parent: #0, outer_mark: (crate0::{{expn1}}, SemiTransparent) +#1: parent: #0, outer_mark: (crate0::{{expn1}}, SemiOpaque) */ diff --git a/tests/ui/proc-macro/meta-macro-hygiene.stdout b/tests/ui/proc-macro/meta-macro-hygiene.stdout index 1ee7179e84c04..1734b9afe92eb 100644 --- a/tests/ui/proc-macro/meta-macro-hygiene.stdout +++ b/tests/ui/proc-macro/meta-macro-hygiene.stdout @@ -60,11 +60,11 @@ SyntaxContexts: #0: parent: #0, outer_mark: (crate0::{{expn0}}, Opaque) #1: parent: #0, outer_mark: (crate0::{{expn1}}, Opaque) #2: parent: #0, outer_mark: (crate0::{{expn1}}, Transparent) -#3: parent: #0, outer_mark: (crate0::{{expn2}}, SemiTransparent) +#3: parent: #0, outer_mark: (crate0::{{expn2}}, SemiOpaque) #4: parent: #0, outer_mark: (crate0::{{expn3}}, Opaque) #5: parent: #3, outer_mark: (crate0::{{expn3}}, Transparent) -#6: parent: #0, outer_mark: (crate0::{{expn3}}, SemiTransparent) +#6: parent: #0, outer_mark: (crate0::{{expn3}}, SemiOpaque) #7: parent: #0, outer_mark: (crate0::{{expn4}}, Opaque) #8: parent: #4, outer_mark: (crate0::{{expn4}}, Transparent) -#9: parent: #4, outer_mark: (crate0::{{expn4}}, SemiTransparent) +#9: parent: #4, outer_mark: (crate0::{{expn4}}, SemiOpaque) */ diff --git a/tests/ui/proc-macro/nonterminal-token-hygiene.stdout b/tests/ui/proc-macro/nonterminal-token-hygiene.stdout index 6fd6cb474693b..0f1b19ffdeabc 100644 --- a/tests/ui/proc-macro/nonterminal-token-hygiene.stdout +++ b/tests/ui/proc-macro/nonterminal-token-hygiene.stdout @@ -82,10 +82,10 @@ SyntaxContexts: #0: parent: #0, outer_mark: (crate0::{{expn0}}, Opaque) #1: parent: #0, outer_mark: (crate0::{{expn1}}, Opaque) #2: parent: #0, outer_mark: (crate0::{{expn1}}, Transparent) -#3: parent: #0, outer_mark: (crate0::{{expn2}}, SemiTransparent) +#3: parent: #0, outer_mark: (crate0::{{expn2}}, SemiOpaque) #4: parent: #3, outer_mark: (crate0::{{expn3}}, Opaque) #5: parent: #0, outer_mark: (crate0::{{expn3}}, Opaque) #6: parent: #0, outer_mark: (crate0::{{expn4}}, Opaque) #7: parent: #4, outer_mark: (crate0::{{expn4}}, Transparent) -#8: parent: #5, outer_mark: (crate0::{{expn4}}, SemiTransparent) +#8: parent: #5, outer_mark: (crate0::{{expn4}}, SemiOpaque) */ From 027251ff7da03a6c190bfb1e1756a23085e3ff35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20K=C3=A5re=20Alsaker?= Date: Wed, 2 Apr 2025 07:02:25 +0200 Subject: [PATCH 063/266] Use a session counter to make anon dep nodes unique --- .../rustc_query_system/src/dep_graph/graph.rs | 9 ++------- .../src/dep_graph/serialized.rs | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_query_system/src/dep_graph/graph.rs b/compiler/rustc_query_system/src/dep_graph/graph.rs index 127dcd825da56..abd6120bf9df0 100644 --- a/compiler/rustc_query_system/src/dep_graph/graph.rs +++ b/compiler/rustc_query_system/src/dep_graph/graph.rs @@ -1167,8 +1167,7 @@ pub(super) struct CurrentDepGraph { /// ID from the previous session. In order to side-step this problem, we make /// sure that anonymous `NodeId`s allocated in different sessions don't overlap. /// This is implemented by mixing a session-key into the ID fingerprint of - /// each anon node. The session-key is just a random number generated when - /// the `DepGraph` is created. + /// each anon node. The session-key is a hash of the number of previous sessions. anon_id_seed: Fingerprint, /// These are simple counters that are for profiling and @@ -1186,12 +1185,8 @@ impl CurrentDepGraph { record_stats: bool, previous: Arc, ) -> Self { - use std::time::{SystemTime, UNIX_EPOCH}; - - let duration = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); - let nanos = duration.as_nanos(); let mut stable_hasher = StableHasher::new(); - nanos.hash(&mut stable_hasher); + previous.session_count().hash(&mut stable_hasher); let anon_id_seed = stable_hasher.finish(); #[cfg(debug_assertions)] diff --git a/compiler/rustc_query_system/src/dep_graph/serialized.rs b/compiler/rustc_query_system/src/dep_graph/serialized.rs index 7750d6d1fef46..9a639ede662c6 100644 --- a/compiler/rustc_query_system/src/dep_graph/serialized.rs +++ b/compiler/rustc_query_system/src/dep_graph/serialized.rs @@ -92,6 +92,9 @@ pub struct SerializedDepGraph { /// Stores a map from fingerprints to nodes per dep node kind. /// This is the reciprocal of `nodes`. index: Vec>, + /// The number of previous compilation sessions. This is used to generate + /// unique anon dep nodes per session. + session_count: u64, } impl SerializedDepGraph { @@ -146,6 +149,11 @@ impl SerializedDepGraph { pub fn node_count(&self) -> usize { self.nodes.len() } + + #[inline] + pub fn session_count(&self) -> u64 { + self.session_count + } } /// A packed representation of an edge's start index and byte width. @@ -252,6 +260,8 @@ impl SerializedDepGraph { .map(|_| UnhashMap::with_capacity_and_hasher(d.read_u32() as usize, Default::default())) .collect(); + let session_count = d.read_u64(); + for (idx, node) in nodes.iter_enumerated() { if index[node.kind.as_usize()].insert(node.hash, idx).is_some() { // Side effect nodes can have duplicates @@ -273,6 +283,7 @@ impl SerializedDepGraph { edge_list_indices, edge_list_data, index, + session_count, }) } } @@ -601,7 +612,7 @@ impl EncoderState { stats: _, kind_stats, marker: _, - previous: _, + previous, } = self; let node_count = total_node_count.try_into().unwrap(); @@ -612,6 +623,8 @@ impl EncoderState { count.encode(&mut encoder); } + previous.session_count.checked_add(1).unwrap().encode(&mut encoder); + debug!(?node_count, ?edge_count); debug!("position: {:?}", encoder.position()); IntEncodedWithFixedSize(node_count).encode(&mut encoder); From 984c51f6a1d93fa244829f488d2945e7fc06b880 Mon Sep 17 00:00:00 2001 From: clubby789 Date: Tue, 18 Mar 2025 01:01:15 +0000 Subject: [PATCH 064/266] Stabilize `cfg_boolean_literals` --- .../rustc_attr_parsing/src/attributes/cfg.rs | 15 ------- compiler/rustc_feature/src/accepted.rs | 2 + compiler/rustc_feature/src/unstable.rs | 2 - .../language-features/cfg-boolean-literals.md | 22 ---------- .../crates/ide-db/src/generated/lints.rs | 29 ------------- tests/rustdoc-ui/cfg-boolean-literal.rs | 1 - tests/rustdoc-ui/doc-cfg-unstable.rs | 4 -- tests/rustdoc-ui/doc-cfg-unstable.stderr | 14 +----- tests/ui/cfg/true-false.rs | 1 - .../feature-gate-cfg-boolean-literals.rs | 10 ----- .../feature-gate-cfg-boolean-literals.stderr | 43 ------------------- tests/ui/lint/inert-attr-macro.rs | 1 - tests/ui/lint/inert-attr-macro.stderr | 14 +++--- tests/ui/proc-macro/cfg-attr-trace.rs | 1 - tests/ui/proc-macro/cfg-attr-trace.stdout | 30 ++++++------- 15 files changed, 26 insertions(+), 163 deletions(-) delete mode 100644 src/doc/unstable-book/src/language-features/cfg-boolean-literals.md delete mode 100644 tests/ui/feature-gates/feature-gate-cfg-boolean-literals.rs delete mode 100644 tests/ui/feature-gates/feature-gate-cfg-boolean-literals.stderr diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg.rs b/compiler/rustc_attr_parsing/src/attributes/cfg.rs index 0d6d521b40c61..48297b2ebd8c3 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg.rs @@ -7,7 +7,6 @@ use rustc_session::config::ExpectedValues; use rustc_session::lint::BuiltinLintDiag; use rustc_session::lint::builtin::UNEXPECTED_CFGS; use rustc_session::parse::feature_err; -use rustc_span::symbol::kw; use rustc_span::{Span, Symbol, sym}; use crate::session_diagnostics::{self, UnsupportedLiteralReason}; @@ -89,20 +88,6 @@ pub fn eval_condition( let cfg = match cfg { MetaItemInner::MetaItem(meta_item) => meta_item, MetaItemInner::Lit(MetaItemLit { kind: LitKind::Bool(b), .. }) => { - if let Some(features) = features { - // we can't use `try_gate_cfg` as symbols don't differentiate between `r#true` - // and `true`, and we want to keep the former working without feature gate - gate_cfg( - &( - if *b { kw::True } else { kw::False }, - sym::cfg_boolean_literals, - |features: &Features| features.cfg_boolean_literals(), - ), - cfg.span(), - sess, - features, - ); - } return *b; } _ => { diff --git a/compiler/rustc_feature/src/accepted.rs b/compiler/rustc_feature/src/accepted.rs index 88e6593572bc6..a9ef7c3f9f18f 100644 --- a/compiler/rustc_feature/src/accepted.rs +++ b/compiler/rustc_feature/src/accepted.rs @@ -95,6 +95,8 @@ declare_features! ( (accepted, c_unwind, "1.81.0", Some(74990)), /// Allows `#[cfg_attr(predicate, multiple, attributes, here)]`. (accepted, cfg_attr_multi, "1.33.0", Some(54881)), + /// Allows the use of `#[cfg()]`. + (accepted, cfg_boolean_literals, "CURRENT_RUSTC_VERSION", Some(131204)), /// Allows the use of `#[cfg(doctest)]`, set when rustdoc is collecting doctests. (accepted, cfg_doctest, "1.40.0", Some(62210)), /// Enables `#[cfg(panic = "...")]` config key. diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 87b88bb4223ed..6ead07ac0ffbb 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -391,8 +391,6 @@ declare_features! ( (unstable, async_trait_bounds, "1.85.0", Some(62290)), /// Allows using C-variadics. (unstable, c_variadic, "1.34.0", Some(44930)), - /// Allows the use of `#[cfg()]`. - (unstable, cfg_boolean_literals, "1.83.0", Some(131204)), /// Allows the use of `#[cfg(contract_checks)` to check if contract checks are enabled. (unstable, cfg_contract_checks, "1.86.0", Some(128044)), /// Allows the use of `#[cfg(overflow_checks)` to check if integer overflow behaviour. diff --git a/src/doc/unstable-book/src/language-features/cfg-boolean-literals.md b/src/doc/unstable-book/src/language-features/cfg-boolean-literals.md deleted file mode 100644 index ad795ff9d9b26..0000000000000 --- a/src/doc/unstable-book/src/language-features/cfg-boolean-literals.md +++ /dev/null @@ -1,22 +0,0 @@ -# `cfg_boolean_literals` - -The tracking issue for this feature is: [#131204] - -[#131204]: https://github.com/rust-lang/rust/issues/131204 - ------------------------- - -The `cfg_boolean_literals` feature makes it possible to use the `true`/`false` -literal as cfg predicate. They always evaluate to true/false respectively. - -## Examples - -```rust -#![feature(cfg_boolean_literals)] - -#[cfg(true)] -const A: i32 = 5; - -#[cfg(all(false))] -const A: i32 = 58 * 89; -``` diff --git a/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs b/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs index 0a7a7d1fb2411..706d04484f6fe 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs @@ -3789,35 +3789,6 @@ The tracking issue for this feature is: [#64797] [#64797]: https://github.com/rust-lang/rust/issues/64797 ------------------------ -"##, - default_severity: Severity::Allow, - warn_since: None, - deny_since: None, - }, - Lint { - label: "cfg_boolean_literals", - description: r##"# `cfg_boolean_literals` - -The tracking issue for this feature is: [#131204] - -[#131204]: https://github.com/rust-lang/rust/issues/131204 - ------------------------- - -The `cfg_boolean_literals` feature makes it possible to use the `true`/`false` -literal as cfg predicate. They always evaluate to true/false respectively. - -## Examples - -```rust -#![feature(cfg_boolean_literals)] - -#[cfg(true)] -const A: i32 = 5; - -#[cfg(all(false))] -const A: i32 = 58 * 89; -``` "##, default_severity: Severity::Allow, warn_since: None, diff --git a/tests/rustdoc-ui/cfg-boolean-literal.rs b/tests/rustdoc-ui/cfg-boolean-literal.rs index 4d4e599bfeef2..74808d066c715 100644 --- a/tests/rustdoc-ui/cfg-boolean-literal.rs +++ b/tests/rustdoc-ui/cfg-boolean-literal.rs @@ -1,6 +1,5 @@ //@ check-pass -#![feature(cfg_boolean_literals)] #![feature(doc_cfg)] #[doc(cfg(false))] diff --git a/tests/rustdoc-ui/doc-cfg-unstable.rs b/tests/rustdoc-ui/doc-cfg-unstable.rs index 14c2e83ec8540..b77c3654497d2 100644 --- a/tests/rustdoc-ui/doc-cfg-unstable.rs +++ b/tests/rustdoc-ui/doc-cfg-unstable.rs @@ -1,10 +1,6 @@ // #138113: rustdoc didn't gate unstable predicates inside `doc(cfg(..))` #![feature(doc_cfg)] -// `cfg_boolean_literals` -#[doc(cfg(false))] //~ ERROR `cfg(false)` is experimental and subject to change -pub fn cfg_boolean_literals() {} - // `cfg_version` #[doc(cfg(sanitize = "thread"))] //~ ERROR `cfg(sanitize)` is experimental and subject to change pub fn cfg_sanitize() {} diff --git a/tests/rustdoc-ui/doc-cfg-unstable.stderr b/tests/rustdoc-ui/doc-cfg-unstable.stderr index 54de3b178edb6..9651c5f1a0b09 100644 --- a/tests/rustdoc-ui/doc-cfg-unstable.stderr +++ b/tests/rustdoc-ui/doc-cfg-unstable.stderr @@ -1,15 +1,5 @@ -error[E0658]: `cfg(false)` is experimental and subject to change - --> $DIR/doc-cfg-unstable.rs:5:11 - | -LL | #[doc(cfg(false))] - | ^^^^^ - | - = note: see issue #131204 for more information - = help: add `#![feature(cfg_boolean_literals)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - error[E0658]: `cfg(sanitize)` is experimental and subject to change - --> $DIR/doc-cfg-unstable.rs:9:11 + --> $DIR/doc-cfg-unstable.rs:5:11 | LL | #[doc(cfg(sanitize = "thread"))] | ^^^^^^^^^^^^^^^^^^^ @@ -18,6 +8,6 @@ LL | #[doc(cfg(sanitize = "thread"))] = help: add `#![feature(cfg_sanitize)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error: aborting due to 2 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/cfg/true-false.rs b/tests/ui/cfg/true-false.rs index 03d96fbafecbe..0bd1cf427fafd 100644 --- a/tests/ui/cfg/true-false.rs +++ b/tests/ui/cfg/true-false.rs @@ -1,7 +1,6 @@ //@ run-pass #![feature(link_cfg)] -#![feature(cfg_boolean_literals)] #[cfg(true)] fn foo() -> bool { diff --git a/tests/ui/feature-gates/feature-gate-cfg-boolean-literals.rs b/tests/ui/feature-gates/feature-gate-cfg-boolean-literals.rs deleted file mode 100644 index 6784b4450490b..0000000000000 --- a/tests/ui/feature-gates/feature-gate-cfg-boolean-literals.rs +++ /dev/null @@ -1,10 +0,0 @@ -#[cfg(true)] //~ ERROR `cfg(true)` is experimental -fn foo() {} - -#[cfg_attr(true, cfg(false))] //~ ERROR `cfg(true)` is experimental -//~^ ERROR `cfg(false)` is experimental -fn foo() {} - -fn main() { - cfg!(false); //~ ERROR `cfg(false)` is experimental -} diff --git a/tests/ui/feature-gates/feature-gate-cfg-boolean-literals.stderr b/tests/ui/feature-gates/feature-gate-cfg-boolean-literals.stderr deleted file mode 100644 index 64491464f1d43..0000000000000 --- a/tests/ui/feature-gates/feature-gate-cfg-boolean-literals.stderr +++ /dev/null @@ -1,43 +0,0 @@ -error[E0658]: `cfg(true)` is experimental and subject to change - --> $DIR/feature-gate-cfg-boolean-literals.rs:1:7 - | -LL | #[cfg(true)] - | ^^^^ - | - = note: see issue #131204 for more information - = help: add `#![feature(cfg_boolean_literals)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `cfg(true)` is experimental and subject to change - --> $DIR/feature-gate-cfg-boolean-literals.rs:4:12 - | -LL | #[cfg_attr(true, cfg(false))] - | ^^^^ - | - = note: see issue #131204 for more information - = help: add `#![feature(cfg_boolean_literals)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `cfg(false)` is experimental and subject to change - --> $DIR/feature-gate-cfg-boolean-literals.rs:4:22 - | -LL | #[cfg_attr(true, cfg(false))] - | ^^^^^ - | - = note: see issue #131204 for more information - = help: add `#![feature(cfg_boolean_literals)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `cfg(false)` is experimental and subject to change - --> $DIR/feature-gate-cfg-boolean-literals.rs:9:10 - | -LL | cfg!(false); - | ^^^^^ - | - = note: see issue #131204 for more information - = help: add `#![feature(cfg_boolean_literals)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error: aborting due to 4 previous errors - -For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/lint/inert-attr-macro.rs b/tests/ui/lint/inert-attr-macro.rs index 5d4133d6c7748..f2d50e30aecc2 100644 --- a/tests/ui/lint/inert-attr-macro.rs +++ b/tests/ui/lint/inert-attr-macro.rs @@ -1,6 +1,5 @@ //@ check-pass -#![feature(cfg_boolean_literals)] #![warn(unused)] macro_rules! foo { diff --git a/tests/ui/lint/inert-attr-macro.stderr b/tests/ui/lint/inert-attr-macro.stderr index b85b0319e7126..5ccb4ffe79298 100644 --- a/tests/ui/lint/inert-attr-macro.stderr +++ b/tests/ui/lint/inert-attr-macro.stderr @@ -1,41 +1,41 @@ warning: unused attribute `inline` - --> $DIR/inert-attr-macro.rs:11:5 + --> $DIR/inert-attr-macro.rs:10:5 | LL | #[inline] foo!(); | ^^^^^^^^^ | note: the built-in attribute `inline` will be ignored, since it's applied to the macro invocation `foo` - --> $DIR/inert-attr-macro.rs:11:15 + --> $DIR/inert-attr-macro.rs:10:15 | LL | #[inline] foo!(); | ^^^ note: the lint level is defined here - --> $DIR/inert-attr-macro.rs:4:9 + --> $DIR/inert-attr-macro.rs:3:9 | LL | #![warn(unused)] | ^^^^^^ = note: `#[warn(unused_attributes)]` implied by `#[warn(unused)]` warning: unused attribute `allow` - --> $DIR/inert-attr-macro.rs:15:5 + --> $DIR/inert-attr-macro.rs:14:5 | LL | #[allow(warnings)] #[inline] foo!(); | ^^^^^^^^^^^^^^^^^^ | note: the built-in attribute `allow` will be ignored, since it's applied to the macro invocation `foo` - --> $DIR/inert-attr-macro.rs:15:34 + --> $DIR/inert-attr-macro.rs:14:34 | LL | #[allow(warnings)] #[inline] foo!(); | ^^^ warning: unused attribute `inline` - --> $DIR/inert-attr-macro.rs:15:24 + --> $DIR/inert-attr-macro.rs:14:24 | LL | #[allow(warnings)] #[inline] foo!(); | ^^^^^^^^^ | note: the built-in attribute `inline` will be ignored, since it's applied to the macro invocation `foo` - --> $DIR/inert-attr-macro.rs:15:34 + --> $DIR/inert-attr-macro.rs:14:34 | LL | #[allow(warnings)] #[inline] foo!(); | ^^^ diff --git a/tests/ui/proc-macro/cfg-attr-trace.rs b/tests/ui/proc-macro/cfg-attr-trace.rs index 140dd10a7e047..412c65bed1d88 100644 --- a/tests/ui/proc-macro/cfg-attr-trace.rs +++ b/tests/ui/proc-macro/cfg-attr-trace.rs @@ -3,7 +3,6 @@ //@ check-pass //@ proc-macro: test-macros.rs -#![feature(cfg_boolean_literals)] #![feature(cfg_eval)] #[macro_use] diff --git a/tests/ui/proc-macro/cfg-attr-trace.stdout b/tests/ui/proc-macro/cfg-attr-trace.stdout index 52f9ff4e05c59..33bcfe5d69b7e 100644 --- a/tests/ui/proc-macro/cfg-attr-trace.stdout +++ b/tests/ui/proc-macro/cfg-attr-trace.stdout @@ -4,75 +4,75 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ Punct { ch: '#', spacing: Alone, - span: #0 bytes(305..306), + span: #0 bytes(271..272), }, Group { delimiter: Bracket, stream: TokenStream [ Ident { ident: "test_macros", - span: #0 bytes(322..333), + span: #0 bytes(288..299), }, Punct { ch: ':', spacing: Joint, - span: #0 bytes(333..334), + span: #0 bytes(299..300), }, Punct { ch: ':', spacing: Alone, - span: #0 bytes(334..335), + span: #0 bytes(300..301), }, Ident { ident: "print_attr", - span: #0 bytes(335..345), + span: #0 bytes(301..311), }, ], - span: #0 bytes(306..347), + span: #0 bytes(272..313), }, Ident { ident: "struct", - span: #0 bytes(348..354), + span: #0 bytes(314..320), }, Ident { ident: "S", - span: #0 bytes(355..356), + span: #0 bytes(321..322), }, Punct { ch: ';', spacing: Alone, - span: #0 bytes(356..357), + span: #0 bytes(322..323), }, ] PRINT-ATTR INPUT (DISPLAY): struct S; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: #0 bytes(348..354), + span: #0 bytes(314..320), }, Ident { ident: "S", - span: #0 bytes(355..356), + span: #0 bytes(321..322), }, Punct { ch: ';', spacing: Alone, - span: #0 bytes(356..357), + span: #0 bytes(322..323), }, ] PRINT-ATTR INPUT (DISPLAY): struct Z; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: #0 bytes(411..417), + span: #0 bytes(377..383), }, Ident { ident: "Z", - span: #0 bytes(418..419), + span: #0 bytes(384..385), }, Punct { ch: ';', spacing: Alone, - span: #0 bytes(419..420), + span: #0 bytes(385..386), }, ] From d83f4153251ad3e85e975fa3e613378eba913c0b Mon Sep 17 00:00:00 2001 From: clubby789 Date: Tue, 18 Mar 2025 13:06:25 +0000 Subject: [PATCH 065/266] Add more tests for `cfg_boolean_literals` --- tests/ui/cfg/both-true-false.rs | 14 ++++++++++++++ tests/ui/cfg/both-true-false.stderr | 9 +++++++++ tests/ui/cfg/cmdline-false.rs | 9 +++++++++ tests/ui/cfg/cmdline-false.stderr | 9 +++++++++ 4 files changed, 41 insertions(+) create mode 100644 tests/ui/cfg/both-true-false.rs create mode 100644 tests/ui/cfg/both-true-false.stderr create mode 100644 tests/ui/cfg/cmdline-false.rs create mode 100644 tests/ui/cfg/cmdline-false.stderr diff --git a/tests/ui/cfg/both-true-false.rs b/tests/ui/cfg/both-true-false.rs new file mode 100644 index 0000000000000..5fca8f654ad8e --- /dev/null +++ b/tests/ui/cfg/both-true-false.rs @@ -0,0 +1,14 @@ +/// Test that placing a `cfg(true)` and `cfg(false)` on the same item result in +//. it being disabled.` + +#[cfg(false)] +#[cfg(true)] +fn foo() {} + +#[cfg(true)] +#[cfg(false)] +fn foo() {} + +fn main() { + foo(); //~ ERROR cannot find function `foo` in this scope +} diff --git a/tests/ui/cfg/both-true-false.stderr b/tests/ui/cfg/both-true-false.stderr new file mode 100644 index 0000000000000..1526cc2b707b4 --- /dev/null +++ b/tests/ui/cfg/both-true-false.stderr @@ -0,0 +1,9 @@ +error[E0425]: cannot find function `foo` in this scope + --> $DIR/both-true-false.rs:13:5 + | +LL | foo(); + | ^^^ not found in this scope + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0425`. diff --git a/tests/ui/cfg/cmdline-false.rs b/tests/ui/cfg/cmdline-false.rs new file mode 100644 index 0000000000000..d4b7d3bbfdca2 --- /dev/null +++ b/tests/ui/cfg/cmdline-false.rs @@ -0,0 +1,9 @@ +/// Test that `--cfg false` doesn't cause `cfg(false)` to evaluate to `true` +//@ compile-flags: --cfg false + +#[cfg(false)] +fn foo() {} + +fn main() { + foo(); //~ ERROR cannot find function `foo` in this scope +} diff --git a/tests/ui/cfg/cmdline-false.stderr b/tests/ui/cfg/cmdline-false.stderr new file mode 100644 index 0000000000000..5f57c754c403b --- /dev/null +++ b/tests/ui/cfg/cmdline-false.stderr @@ -0,0 +1,9 @@ +error[E0425]: cannot find function `foo` in this scope + --> $DIR/cmdline-false.rs:8:5 + | +LL | foo(); + | ^^^ not found in this scope + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0425`. From 303c1b45c29f8bb186a9a95cb56643d1aef773fa Mon Sep 17 00:00:00 2001 From: clubby789 Date: Sat, 29 Mar 2025 17:24:03 +0000 Subject: [PATCH 066/266] Use `cfg(false)` in UI tests --- tests/pretty/ast-stmt-expr-attr.rs | 2 +- tests/pretty/enum-variant-vis.rs | 2 +- tests/pretty/if-attr.rs | 8 +- tests/pretty/nested-item-vis-defaultness.rs | 6 +- .../associated-types/associated-type-macro.rs | 2 +- .../ui/async-await/feature-async-for-loop.rs | 2 +- tests/ui/async-await/no-unsafe-async.rs | 4 +- tests/ui/attributes/z-crate-attr/cfg-false.rs | 4 +- tests/ui/auto-traits/pre-cfg.rs | 2 +- tests/ui/cfg/auxiliary/cfg_false_lib.rs | 4 +- .../auxiliary/cfg_false_lib_no_std_after.rs | 4 +- .../auxiliary/cfg_false_lib_no_std_before.rs | 4 +- tests/ui/cfg/auxiliary/cfged_out.rs | 4 +- tests/ui/cfg/cfg-false-feature.rs | 4 +- tests/ui/cfg/cfg-macros-notfoo.rs | 2 +- tests/ui/cfg/cfg-match-arm.rs | 2 +- tests/ui/cfg/cfg-stmt-recovery.rs | 2 +- tests/ui/cfg/cfg-stmt-recovery.stderr | 6 +- tests/ui/cfg/cfg_stmt_expr.rs | 30 ++-- tests/ui/cfg/conditional-compile.rs | 36 ++--- tests/ui/cfg/diagnostics-cross-crate.stderr | 4 +- tests/ui/cfg/diagnostics-reexport.rs | 10 +- tests/ui/cfg/diagnostics-reexport.stderr | 8 +- tests/ui/cfg/diagnostics-same-crate.rs | 4 +- tests/ui/cfg/diagnostics-same-crate.stderr | 8 +- tests/ui/check-cfg/allow-same-level.rs | 2 +- tests/ui/check-cfg/allow-same-level.stderr | 8 +- tests/ui/check-cfg/allow-top-level.rs | 2 +- tests/ui/check-cfg/allow-upper-level.rs | 2 +- .../cfg-generic-params.rs | 16 +- .../cfg-generic-params.stderr | 6 +- .../conditional-compilation/cfg-in-crate-1.rs | 2 +- .../cfg-in-crate-1.stderr | 2 +- .../cfg-non-opt-expr.rs | 6 +- .../cfg-non-opt-expr.stderr | 6 +- .../module_with_cfg.rs | 2 +- ...nst-extern-fns-dont-need-fn-specifier-2.rs | 2 +- ...const-extern-fns-dont-need-fn-specifier.rs | 2 +- .../explicit-paths-signature-pass.rs | 2 +- tests/ui/expr/if/attrs/bad-cfg.rs | 2 +- tests/ui/expr/if/attrs/bad-cfg.stderr | 2 +- tests/ui/expr/if/attrs/cfg-false-if-attr.rs | 14 +- tests/ui/expr/if/attrs/else-attrs.rs | 6 +- tests/ui/expr/if/attrs/gate-whole-expr.rs | 2 +- tests/ui/expr/if/attrs/let-chains-attr.rs | 2 +- .../feature-gates/feature-gate-coroutines.rs | 2 +- .../feature-gate-deref_patterns.rs | 2 +- .../feature-gates/feature-gate-gen_blocks.rs | 2 +- .../feature-gate-guard-patterns.rs | 2 +- .../ui/feature-gates/feature-gate-mut-ref.rs | 4 +- .../feature-gate-never_patterns.rs | 8 +- .../feature-gate-postfix_match.rs | 2 +- .../feature-gate-yeet_expr-in-cfg.rs | 4 +- .../soft-syntax-gates-with-errors.rs | 6 +- .../soft-syntax-gates-without-errors.rs | 6 +- .../stmt_expr_attrs_no_feature.rs | 24 +-- tests/ui/filter-block-view-items.rs | 2 +- ...nge-pats-inclusive-dotdotdot-bad-syntax.rs | 2 +- .../half-open-range-pats-inclusive-no-end.rs | 2 +- ...lf-open-range-pats-ref-ambiguous-interp.rs | 2 +- .../half-open-range-pats-syntactic-pass.rs | 2 +- tests/ui/inner-attrs-on-impl.rs | 4 +- tests/ui/issues/issue-11004.rs | 2 +- tests/ui/issues/issue-11085.rs | 8 +- tests/ui/issues/issue-16819.rs | 2 +- tests/ui/lexer/error-stage.rs | 2 +- .../link-attr-validation-late.rs | 2 +- .../link-attr-validation-late.stderr | 2 +- .../ui/lint/unused/unused-attr-macro-rules.rs | 2 +- tests/ui/macros/lint-trailing-macro-call.rs | 2 +- .../ui/macros/lint-trailing-macro-call.stderr | 4 +- tests/ui/macros/macro-attributes.rs | 2 +- tests/ui/macros/macro-inner-attributes.rs | 2 +- tests/ui/macros/macro-outer-attributes.rs | 2 +- tests/ui/macros/macro-outer-attributes.stderr | 2 +- tests/ui/macros/macro-with-attrs2.rs | 2 +- tests/ui/nested-cfg-attrs.rs | 2 +- .../ui/or-patterns/fn-param-wrap-parens.fixed | 2 +- tests/ui/or-patterns/fn-param-wrap-parens.rs | 2 +- .../or-patterns/or-patterns-syntactic-pass.rs | 2 +- .../ui/or-patterns/remove-leading-vert.fixed | 4 +- tests/ui/or-patterns/remove-leading-vert.rs | 4 +- .../assoc-const-underscore-syntactic-pass.rs | 2 +- .../assoc/assoc-static-syntactic-fail.rs | 6 +- .../attribute/attr-stmt-expr-attr-bad.rs | 90 +++++------ .../attribute/attr-stmt-expr-attr-bad.stderr | 150 +++++++++--------- .../multiple-tail-expr-behind-cfg.rs | 2 +- .../multiple-tail-expr-behind-cfg.stderr | 4 +- ...from-trailing-outer-attribute-in-body-2.rs | 2 +- ...-trailing-outer-attribute-in-body-2.stderr | 2 +- ...ints-before-generic-args-syntactic-pass.rs | 2 +- tests/ui/parser/default-on-wrong-item-kind.rs | 8 +- tests/ui/parser/extern-abi-syntactic.rs | 6 +- tests/ui/parser/extern-crate-async.rs | 4 +- .../parser/fn-body-optional-syntactic-pass.rs | 2 +- tests/ui/parser/fn-header-syntactic-pass.rs | 2 +- .../ui/parser/foreign-const-syntactic-fail.rs | 2 +- .../parser/foreign-static-syntactic-pass.rs | 2 +- tests/ui/parser/foreign-ty-syntactic-pass.rs | 2 +- tests/ui/parser/impl-item-const-pass.rs | 2 +- tests/ui/parser/impl-item-fn-no-body-pass.rs | 2 +- .../ui/parser/impl-item-type-no-body-pass.rs | 2 +- .../issue-65041-empty-vis-matcher-in-enum.rs | 2 +- .../issue-65041-empty-vis-matcher-in-trait.rs | 2 +- .../item-free-const-no-body-syntactic-pass.rs | 2 +- ...item-free-static-no-body-syntactic-pass.rs | 2 +- .../item-free-type-bounds-syntactic-pass.rs | 2 +- .../recover/recover-assoc-const-constraint.rs | 2 +- .../recover/recover-assoc-eq-missing-term.rs | 2 +- .../recover-assoc-lifetime-constraint.rs | 2 +- tests/ui/parser/self-param-syntactic-pass.rs | 10 +- .../stripped-nested-outline-mod-pass.rs | 2 +- .../trait-item-with-defaultness-pass.rs | 2 +- .../ui/parser/variadic-ffi-syntactic-pass.rs | 22 +-- ...d-type-ascription-syntactically-invalid.rs | 6 +- .../wild-before-at-syntactically-rejected.rs | 2 +- tests/ui/pattern/rest-pat-syntactic.rs | 2 +- tests/ui/proc-macro/attribute-after-derive.rs | 4 +- .../proc-macro/attribute-after-derive.stdout | 12 +- tests/ui/proc-macro/cfg-eval-fail.rs | 2 +- tests/ui/proc-macro/cfg-eval-fail.stderr | 2 +- tests/ui/proc-macro/cfg-eval-inner.rs | 2 +- tests/ui/proc-macro/cfg-eval.rs | 6 +- .../ui/proc-macro/derive-cfg-nested-tokens.rs | 2 +- .../derive-cfg-nested-tokens.stdout | 4 +- tests/ui/proc-macro/expand-to-derive.rs | 4 +- tests/ui/proc-macro/issue-75930-derive-cfg.rs | 26 +-- .../proc-macro/issue-75930-derive-cfg.stdout | 90 +++++------ tests/ui/proc-macro/nested-derive-cfg.rs | 4 +- .../rfc-2294-if-let-guard/feature-gate.rs | 2 +- tests/ui/rfcs/rfc-2294-if-let-guard/parens.rs | 2 +- .../disallowed-positions.rs | 8 +- .../rfc-2497-if-let-chains/feature-gate.rs | 2 +- .../feature-gate.stderr | 2 +- .../invalid-let-in-a-valid-let-context.rs | 10 +- .../attr-without-param.rs | 6 +- .../specialization/issue-63716-parse-async.rs | 2 +- tests/ui/suggestions/const-no-type.rs | 6 +- .../type-ascription-and-other-error.rs | 2 +- tests/ui/wasm/wasm-import-module.rs | 2 +- tests/ui/wasm/wasm-import-module.stderr | 2 +- 141 files changed, 470 insertions(+), 470 deletions(-) diff --git a/tests/pretty/ast-stmt-expr-attr.rs b/tests/pretty/ast-stmt-expr-attr.rs index fd7272a1b1fd3..4ca60465b54cc 100644 --- a/tests/pretty/ast-stmt-expr-attr.rs +++ b/tests/pretty/ast-stmt-expr-attr.rs @@ -2,7 +2,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn syntax() { let _ = #[attr] []; let _ = #[attr] [0]; diff --git a/tests/pretty/enum-variant-vis.rs b/tests/pretty/enum-variant-vis.rs index 3397e7dc8e281..5b9f7e037595a 100644 --- a/tests/pretty/enum-variant-vis.rs +++ b/tests/pretty/enum-variant-vis.rs @@ -4,5 +4,5 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] enum Foo { pub V, } diff --git a/tests/pretty/if-attr.rs b/tests/pretty/if-attr.rs index 89d6130f65928..8b343a83a1c56 100644 --- a/tests/pretty/if-attr.rs +++ b/tests/pretty/if-attr.rs @@ -1,6 +1,6 @@ //@ pp-exact -#[cfg(FALSE)] +#[cfg(false)] fn simple_attr() { #[attr] @@ -10,21 +10,21 @@ fn simple_attr() { if true {} } -#[cfg(FALSE)] +#[cfg(false)] fn if_else_chain() { #[first_attr] if true {} else if false {} else {} } -#[cfg(FALSE)] +#[cfg(false)] fn if_let() { #[attr] if let Some(_) = Some(true) {} } -#[cfg(FALSE)] +#[cfg(false)] fn let_attr_if() { let _ = #[attr] if let _ = 0 {}; let _ = #[attr] if true {}; diff --git a/tests/pretty/nested-item-vis-defaultness.rs b/tests/pretty/nested-item-vis-defaultness.rs index 1e971fcf07a5f..68f56a1be4507 100644 --- a/tests/pretty/nested-item-vis-defaultness.rs +++ b/tests/pretty/nested-item-vis-defaultness.rs @@ -4,7 +4,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] extern "C" { static X: u8; type X; @@ -14,7 +14,7 @@ extern "C" { pub fn foo(); } -#[cfg(FALSE)] +#[cfg(false)] trait T { const X: u8; type X; @@ -30,7 +30,7 @@ trait T { pub default fn foo(); } -#[cfg(FALSE)] +#[cfg(false)] impl T for S { const X: u8; type X; diff --git a/tests/ui/associated-types/associated-type-macro.rs b/tests/ui/associated-types/associated-type-macro.rs index 22b5bca40103d..8586dc172764a 100644 --- a/tests/ui/associated-types/associated-type-macro.rs +++ b/tests/ui/associated-types/associated-type-macro.rs @@ -1,4 +1,4 @@ fn main() { - #[cfg(FALSE)] + #[cfg(false)] <() as module>::mac!(); //~ ERROR macros cannot use qualified paths } diff --git a/tests/ui/async-await/feature-async-for-loop.rs b/tests/ui/async-await/feature-async-for-loop.rs index 67817cbfa5f3f..22d32907e0e7c 100644 --- a/tests/ui/async-await/feature-async-for-loop.rs +++ b/tests/ui/async-await/feature-async-for-loop.rs @@ -11,7 +11,7 @@ fn f() { }; } -#[cfg(FALSE)] +#[cfg(false)] fn g() { let _ = async { for await _i in core::async_iter::from_iter(0..3) { diff --git a/tests/ui/async-await/no-unsafe-async.rs b/tests/ui/async-await/no-unsafe-async.rs index e58d878c3db04..cc7e89e16cb2b 100644 --- a/tests/ui/async-await/no-unsafe-async.rs +++ b/tests/ui/async-await/no-unsafe-async.rs @@ -3,11 +3,11 @@ struct S; impl S { - #[cfg(FALSE)] + #[cfg(false)] unsafe async fn g() {} //~ ERROR expected one of `extern` or `fn`, found keyword `async` } -#[cfg(FALSE)] +#[cfg(false)] unsafe async fn f() {} //~ ERROR expected one of `extern` or `fn`, found keyword `async` fn main() {} diff --git a/tests/ui/attributes/z-crate-attr/cfg-false.rs b/tests/ui/attributes/z-crate-attr/cfg-false.rs index db37cfdd08637..5e5662c74385f 100644 --- a/tests/ui/attributes/z-crate-attr/cfg-false.rs +++ b/tests/ui/attributes/z-crate-attr/cfg-false.rs @@ -1,5 +1,5 @@ -// Ensure that `-Z crate-attr=cfg(FALSE)` can comment out the whole crate -//@ compile-flags: --crate-type=lib -Zcrate-attr=cfg(FALSE) +// Ensure that `-Z crate-attr=cfg(false)` can comment out the whole crate +//@ compile-flags: --crate-type=lib -Zcrate-attr=cfg(false) //@ check-pass // NOTE: duplicate items are load-bearing diff --git a/tests/ui/auto-traits/pre-cfg.rs b/tests/ui/auto-traits/pre-cfg.rs index e806686f965c3..4820a53535803 100644 --- a/tests/ui/auto-traits/pre-cfg.rs +++ b/tests/ui/auto-traits/pre-cfg.rs @@ -1,6 +1,6 @@ //@ check-pass -#[cfg(FALSE)] +#[cfg(false)] auto trait Foo {} //~^ WARN `auto` traits are unstable //~| WARN unstable syntax can change at any point in the future, causing a hard error! diff --git a/tests/ui/cfg/auxiliary/cfg_false_lib.rs b/tests/ui/cfg/auxiliary/cfg_false_lib.rs index 6c2dbb44d2a40..d1768e69b0d57 100644 --- a/tests/ui/cfg/auxiliary/cfg_false_lib.rs +++ b/tests/ui/cfg/auxiliary/cfg_false_lib.rs @@ -1,4 +1,4 @@ -// `#![no_std]` on a fully unconfigured crate is respected if it's placed before `cfg(FALSE)`. +// `#![no_std]` on a fully unconfigured crate is respected if it's placed before `cfg(false)`. // This crate has no such attribute, therefore this crate does link to libstd. -#![cfg(FALSE)] +#![cfg(false)] diff --git a/tests/ui/cfg/auxiliary/cfg_false_lib_no_std_after.rs b/tests/ui/cfg/auxiliary/cfg_false_lib_no_std_after.rs index 3cfa6c510d020..cd3170f3fb33d 100644 --- a/tests/ui/cfg/auxiliary/cfg_false_lib_no_std_after.rs +++ b/tests/ui/cfg/auxiliary/cfg_false_lib_no_std_after.rs @@ -1,5 +1,5 @@ -// `#![no_std]` on a fully unconfigured crate is respected if it's placed before `cfg(FALSE)`. +// `#![no_std]` on a fully unconfigured crate is respected if it's placed before `cfg(false)`. // Therefore this crate does link to libstd. -#![cfg(FALSE)] +#![cfg(false)] #![no_std] diff --git a/tests/ui/cfg/auxiliary/cfg_false_lib_no_std_before.rs b/tests/ui/cfg/auxiliary/cfg_false_lib_no_std_before.rs index a5c14be4c29de..ce4e1690996b5 100644 --- a/tests/ui/cfg/auxiliary/cfg_false_lib_no_std_before.rs +++ b/tests/ui/cfg/auxiliary/cfg_false_lib_no_std_before.rs @@ -1,8 +1,8 @@ -// `#![no_std]` on a fully unconfigured crate is respected if it's placed before `cfg(FALSE)`. +// `#![no_std]` on a fully unconfigured crate is respected if it's placed before `cfg(false)`. // Therefore this crate doesn't link to libstd. //@ no-prefer-dynamic #![no_std] #![crate_type = "lib"] -#![cfg(FALSE)] +#![cfg(false)] diff --git a/tests/ui/cfg/auxiliary/cfged_out.rs b/tests/ui/cfg/auxiliary/cfged_out.rs index f6a9089cf29de..564280b24f598 100644 --- a/tests/ui/cfg/auxiliary/cfged_out.rs +++ b/tests/ui/cfg/auxiliary/cfged_out.rs @@ -1,8 +1,8 @@ pub mod inner { - #[cfg(FALSE)] + #[cfg(false)] pub fn uwu() {} - #[cfg(FALSE)] + #[cfg(false)] pub mod doesnt_exist { pub fn hello() {} } diff --git a/tests/ui/cfg/cfg-false-feature.rs b/tests/ui/cfg/cfg-false-feature.rs index 716b18492c739..f66e4722440c5 100644 --- a/tests/ui/cfg/cfg-false-feature.rs +++ b/tests/ui/cfg/cfg-false-feature.rs @@ -1,10 +1,10 @@ -// Features above `cfg(FALSE)` are in effect in a fully unconfigured crate (issue #104633). +// Features above `cfg(false)` are in effect in a fully unconfigured crate (issue #104633). //@ check-pass //@ compile-flags: --crate-type lib #![feature(decl_macro)] -#![cfg(FALSE)] +#![cfg(false)] #![feature(box_patterns)] macro mac() {} // OK diff --git a/tests/ui/cfg/cfg-macros-notfoo.rs b/tests/ui/cfg/cfg-macros-notfoo.rs index 9feb06be73e90..c25cf1c39bf54 100644 --- a/tests/ui/cfg/cfg-macros-notfoo.rs +++ b/tests/ui/cfg/cfg-macros-notfoo.rs @@ -3,7 +3,7 @@ // check that cfg correctly chooses between the macro impls (see also // cfg-macros-foo.rs) -#[cfg(FALSE)] +#[cfg(false)] #[macro_use] mod foo { macro_rules! bar { diff --git a/tests/ui/cfg/cfg-match-arm.rs b/tests/ui/cfg/cfg-match-arm.rs index f6cd52c475cfc..cb5bf0ab06539 100644 --- a/tests/ui/cfg/cfg-match-arm.rs +++ b/tests/ui/cfg/cfg-match-arm.rs @@ -11,7 +11,7 @@ fn foo(f: Foo) { Foo::Bar => {}, #[cfg(not(FALSE))] Foo::Baz => {}, - #[cfg(FALSE)] + #[cfg(false)] Basdfwe => {} } } diff --git a/tests/ui/cfg/cfg-stmt-recovery.rs b/tests/ui/cfg/cfg-stmt-recovery.rs index 2e0839d2a1535..f0f9a649165b5 100644 --- a/tests/ui/cfg/cfg-stmt-recovery.rs +++ b/tests/ui/cfg/cfg-stmt-recovery.rs @@ -6,7 +6,7 @@ #[cfg_eval] fn main() { #[cfg_eval] - let _ = #[cfg(FALSE)] 0; + let _ = #[cfg(false)] 0; //~^ ERROR removing an expression is not supported in this position //~| ERROR expected expression, found `;` //~| ERROR removing an expression is not supported in this position diff --git a/tests/ui/cfg/cfg-stmt-recovery.stderr b/tests/ui/cfg/cfg-stmt-recovery.stderr index cb15e21fac698..e34da72afd934 100644 --- a/tests/ui/cfg/cfg-stmt-recovery.stderr +++ b/tests/ui/cfg/cfg-stmt-recovery.stderr @@ -1,19 +1,19 @@ error: removing an expression is not supported in this position --> $DIR/cfg-stmt-recovery.rs:9:13 | -LL | let _ = #[cfg(FALSE)] 0; +LL | let _ = #[cfg(false)] 0; | ^^^^^^^^^^^^^ error: expected expression, found `;` --> $DIR/cfg-stmt-recovery.rs:9:28 | -LL | let _ = #[cfg(FALSE)] 0; +LL | let _ = #[cfg(false)] 0; | ^ expected expression error: removing an expression is not supported in this position --> $DIR/cfg-stmt-recovery.rs:9:13 | -LL | let _ = #[cfg(FALSE)] 0; +LL | let _ = #[cfg(false)] 0; | ^^^^^^^^^^^^^ error: aborting due to 3 previous errors diff --git a/tests/ui/cfg/cfg_stmt_expr.rs b/tests/ui/cfg/cfg_stmt_expr.rs index 9245f6d97576f..361b159a354fd 100644 --- a/tests/ui/cfg/cfg_stmt_expr.rs +++ b/tests/ui/cfg/cfg_stmt_expr.rs @@ -7,47 +7,47 @@ fn main() { let a = 413; - #[cfg(FALSE)] + #[cfg(false)] let a = (); assert_eq!(a, 413); let mut b = 612; - #[cfg(FALSE)] + #[cfg(false)] { b = 1111; } assert_eq!(b, 612); - #[cfg(FALSE)] + #[cfg(false)] undefined_fn(); - #[cfg(FALSE)] + #[cfg(false)] undefined_macro!(); - #[cfg(FALSE)] + #[cfg(false)] undefined_macro![]; - #[cfg(FALSE)] + #[cfg(false)] undefined_macro!{}; // pretty printer bug... - // #[cfg(FALSE)] + // #[cfg(false)] // undefined_macro!{} - let () = (#[cfg(FALSE)] 341,); // Should this also work on parens? - let t = (1, #[cfg(FALSE)] 3, 4); + let () = (#[cfg(false)] 341,); // Should this also work on parens? + let t = (1, #[cfg(false)] 3, 4); assert_eq!(t, (1, 4)); let f = |_: u32, _: u32| (); - f(2, 1, #[cfg(FALSE)] 6); + f(2, 1, #[cfg(false)] 6); - let _: u32 = a.clone(#[cfg(FALSE)] undefined); + let _: u32 = a.clone(#[cfg(false)] undefined); - let _: [(); 0] = [#[cfg(FALSE)] 126]; - let t = [#[cfg(FALSE)] 1, 2, 6]; + let _: [(); 0] = [#[cfg(false)] 126]; + let t = [#[cfg(false)] 1, 2, 6]; assert_eq!(t, [2, 6]); { let r; - #[cfg(FALSE)] + #[cfg(false)] (r = 5); #[cfg(not(FALSE))] (r = 10); @@ -75,7 +75,7 @@ fn main() { 612 }); - assert_eq!((#[cfg(FALSE)] 1, #[cfg(not(FALSE))] 2), (2,)); + assert_eq!((#[cfg(false)] 1, #[cfg(not(FALSE))] 2), (2,)); assert_eq!(n, 612); // check that lints work diff --git a/tests/ui/cfg/conditional-compile.rs b/tests/ui/cfg/conditional-compile.rs index dff280054d659..0739e877bfd14 100644 --- a/tests/ui/cfg/conditional-compile.rs +++ b/tests/ui/cfg/conditional-compile.rs @@ -6,16 +6,16 @@ // Crate use statements -#[cfg(FALSE)] +#[cfg(false)] use flippity; -#[cfg(FALSE)] +#[cfg(false)] static b: bool = false; static b: bool = true; mod rustrt { - #[cfg(FALSE)] + #[cfg(false)] extern "C" { // This symbol doesn't exist and would be a link error if this // module was codegened @@ -25,12 +25,12 @@ mod rustrt { extern "C" {} } -#[cfg(FALSE)] +#[cfg(false)] type t = isize; type t = bool; -#[cfg(FALSE)] +#[cfg(false)] enum tg { foo, } @@ -39,12 +39,12 @@ enum tg { bar, } -#[cfg(FALSE)] +#[cfg(false)] struct r { i: isize, } -#[cfg(FALSE)] +#[cfg(false)] fn r(i: isize) -> r { r { i: i } } @@ -57,7 +57,7 @@ fn r(i: isize) -> r { r { i: i } } -#[cfg(FALSE)] +#[cfg(false)] mod m { // This needs to parse but would fail in typeck. Since it's not in // the current config it should not be typechecked. @@ -69,7 +69,7 @@ mod m { mod m { // Submodules have slightly different code paths than the top-level // module, so let's make sure this jazz works here as well - #[cfg(FALSE)] + #[cfg(false)] pub fn f() {} pub fn f() {} @@ -77,7 +77,7 @@ mod m { // Since the FALSE configuration isn't defined main will just be // parsed, but nothing further will be done with it -#[cfg(FALSE)] +#[cfg(false)] pub fn main() { panic!() } @@ -93,14 +93,14 @@ pub fn main() { } fn test_in_fn_ctxt() { - #[cfg(FALSE)] + #[cfg(false)] fn f() { panic!() } fn f() {} f(); - #[cfg(FALSE)] + #[cfg(false)] static i: isize = 0; static i: isize = 1; assert_eq!(i, 1); @@ -109,7 +109,7 @@ fn test_in_fn_ctxt() { mod test_foreign_items { pub mod rustrt { extern "C" { - #[cfg(FALSE)] + #[cfg(false)] pub fn write() -> String; pub fn write() -> String; } @@ -117,7 +117,7 @@ mod test_foreign_items { } mod test_use_statements { - #[cfg(FALSE)] + #[cfg(false)] use flippity_foo; } @@ -127,24 +127,24 @@ mod test_methods { } impl Fooable for Foo { - #[cfg(FALSE)] + #[cfg(false)] fn what(&self) {} fn what(&self) {} - #[cfg(FALSE)] + #[cfg(false)] fn the(&self) {} fn the(&self) {} } trait Fooable { - #[cfg(FALSE)] + #[cfg(false)] fn what(&self); fn what(&self); - #[cfg(FALSE)] + #[cfg(false)] fn the(&self); fn the(&self); diff --git a/tests/ui/cfg/diagnostics-cross-crate.stderr b/tests/ui/cfg/diagnostics-cross-crate.stderr index 07ad4e3272d1b..3e32a856e9540 100644 --- a/tests/ui/cfg/diagnostics-cross-crate.stderr +++ b/tests/ui/cfg/diagnostics-cross-crate.stderr @@ -12,7 +12,7 @@ LL | pub mod doesnt_exist { note: the item is gated here --> $DIR/auxiliary/cfged_out.rs:5:5 | -LL | #[cfg(FALSE)] +LL | #[cfg(false)] | ^^^^^^^^^^^^^ error[E0425]: cannot find function `uwu` in crate `cfged_out` @@ -35,7 +35,7 @@ LL | pub fn uwu() {} note: the item is gated here --> $DIR/auxiliary/cfged_out.rs:2:5 | -LL | #[cfg(FALSE)] +LL | #[cfg(false)] | ^^^^^^^^^^^^^ error[E0425]: cannot find function `meow` in module `cfged_out::inner::right` diff --git a/tests/ui/cfg/diagnostics-reexport.rs b/tests/ui/cfg/diagnostics-reexport.rs index 9ae7d931fcb8f..56fac56223827 100644 --- a/tests/ui/cfg/diagnostics-reexport.rs +++ b/tests/ui/cfg/diagnostics-reexport.rs @@ -1,10 +1,10 @@ pub mod inner { - #[cfg(FALSE)] + #[cfg(false)] mod gone { pub fn uwu() {} } - #[cfg(FALSE)] //~ NOTE the item is gated here + #[cfg(false)] //~ NOTE the item is gated here pub use super::uwu; //~^ NOTE found an item that was configured out } @@ -14,7 +14,7 @@ pub use a::x; //~| NOTE no `x` in `a` mod a { - #[cfg(FALSE)] //~ NOTE the item is gated here + #[cfg(false)] //~ NOTE the item is gated here pub fn x() {} //~^ NOTE found an item that was configured out } @@ -25,10 +25,10 @@ pub use b::{x, y}; //~| NOTE no `y` in `b` mod b { - #[cfg(FALSE)] //~ NOTE the item is gated here + #[cfg(false)] //~ NOTE the item is gated here pub fn x() {} //~^ NOTE found an item that was configured out - #[cfg(FALSE)] //~ NOTE the item is gated here + #[cfg(false)] //~ NOTE the item is gated here pub fn y() {} //~^ NOTE found an item that was configured out } diff --git a/tests/ui/cfg/diagnostics-reexport.stderr b/tests/ui/cfg/diagnostics-reexport.stderr index 737202fdf9ad9..95dc4fac945e2 100644 --- a/tests/ui/cfg/diagnostics-reexport.stderr +++ b/tests/ui/cfg/diagnostics-reexport.stderr @@ -12,7 +12,7 @@ LL | pub fn x() {} note: the item is gated here --> $DIR/diagnostics-reexport.rs:17:5 | -LL | #[cfg(FALSE)] +LL | #[cfg(false)] | ^^^^^^^^^^^^^ error[E0432]: unresolved imports `b::x`, `b::y` @@ -31,7 +31,7 @@ LL | pub fn x() {} note: the item is gated here --> $DIR/diagnostics-reexport.rs:28:5 | -LL | #[cfg(FALSE)] +LL | #[cfg(false)] | ^^^^^^^^^^^^^ note: found an item that was configured out --> $DIR/diagnostics-reexport.rs:32:12 @@ -41,7 +41,7 @@ LL | pub fn y() {} note: the item is gated here --> $DIR/diagnostics-reexport.rs:31:5 | -LL | #[cfg(FALSE)] +LL | #[cfg(false)] | ^^^^^^^^^^^^^ error[E0425]: cannot find function `uwu` in module `inner` @@ -58,7 +58,7 @@ LL | pub use super::uwu; note: the item is gated here --> $DIR/diagnostics-reexport.rs:7:5 | -LL | #[cfg(FALSE)] +LL | #[cfg(false)] | ^^^^^^^^^^^^^ error: aborting due to 3 previous errors diff --git a/tests/ui/cfg/diagnostics-same-crate.rs b/tests/ui/cfg/diagnostics-same-crate.rs index d6f8dd21a9221..9153f20b29649 100644 --- a/tests/ui/cfg/diagnostics-same-crate.rs +++ b/tests/ui/cfg/diagnostics-same-crate.rs @@ -1,11 +1,11 @@ #![allow(unexpected_cfgs)] // since we want to recognize them as unexpected pub mod inner { - #[cfg(FALSE)] //~ NOTE the item is gated here + #[cfg(false)] //~ NOTE the item is gated here pub fn uwu() {} //~^ NOTE found an item that was configured out - #[cfg(FALSE)] //~ NOTE the item is gated here + #[cfg(false)] //~ NOTE the item is gated here //~^ NOTE the item is gated here //~| NOTE the item is gated here pub mod doesnt_exist { diff --git a/tests/ui/cfg/diagnostics-same-crate.stderr b/tests/ui/cfg/diagnostics-same-crate.stderr index dd0d10c6567ea..75a1bc39a013c 100644 --- a/tests/ui/cfg/diagnostics-same-crate.stderr +++ b/tests/ui/cfg/diagnostics-same-crate.stderr @@ -12,7 +12,7 @@ LL | pub mod doesnt_exist { note: the item is gated here --> $DIR/diagnostics-same-crate.rs:8:5 | -LL | #[cfg(FALSE)] +LL | #[cfg(false)] | ^^^^^^^^^^^^^ error[E0432]: unresolved import `super::inner::doesnt_exist` @@ -29,7 +29,7 @@ LL | pub mod doesnt_exist { note: the item is gated here --> $DIR/diagnostics-same-crate.rs:8:5 | -LL | #[cfg(FALSE)] +LL | #[cfg(false)] | ^^^^^^^^^^^^^ error[E0433]: failed to resolve: could not find `doesnt_exist` in `inner` @@ -46,7 +46,7 @@ LL | pub mod doesnt_exist { note: the item is gated here --> $DIR/diagnostics-same-crate.rs:8:5 | -LL | #[cfg(FALSE)] +LL | #[cfg(false)] | ^^^^^^^^^^^^^ error[E0425]: cannot find function `uwu` in module `inner` @@ -63,7 +63,7 @@ LL | pub fn uwu() {} note: the item is gated here --> $DIR/diagnostics-same-crate.rs:4:5 | -LL | #[cfg(FALSE)] +LL | #[cfg(false)] | ^^^^^^^^^^^^^ error[E0425]: cannot find function `meow` in module `inner::right` diff --git a/tests/ui/check-cfg/allow-same-level.rs b/tests/ui/check-cfg/allow-same-level.rs index 8260b57bad4df..3f673cb884472 100644 --- a/tests/ui/check-cfg/allow-same-level.rs +++ b/tests/ui/check-cfg/allow-same-level.rs @@ -12,7 +12,7 @@ //@ compile-flags: --check-cfg=cfg() --cfg=unknown_but_active_cfg #[allow(unexpected_cfgs)] -#[cfg(FALSE)] +#[cfg(unknown_and_inactive_cfg)] //~^ WARNING unexpected `cfg` condition name fn bar() {} diff --git a/tests/ui/check-cfg/allow-same-level.stderr b/tests/ui/check-cfg/allow-same-level.stderr index a705cd4e5f01e..cfff03048b53c 100644 --- a/tests/ui/check-cfg/allow-same-level.stderr +++ b/tests/ui/check-cfg/allow-same-level.stderr @@ -1,10 +1,10 @@ -warning: unexpected `cfg` condition name: `FALSE` +warning: unexpected `cfg` condition name: `unknown_and_inactive_cfg` --> $DIR/allow-same-level.rs:15:7 | -LL | #[cfg(FALSE)] - | ^^^^^ +LL | #[cfg(unknown_and_inactive_cfg)] + | ^^^^^^^^^^^^^^^^^^^^^^^^ | - = help: to expect this configuration use `--check-cfg=cfg(FALSE)` + = help: to expect this configuration use `--check-cfg=cfg(unknown_and_inactive_cfg)` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/allow-top-level.rs b/tests/ui/check-cfg/allow-top-level.rs index cf94ed5da428f..7ccecd2360e86 100644 --- a/tests/ui/check-cfg/allow-top-level.rs +++ b/tests/ui/check-cfg/allow-top-level.rs @@ -6,7 +6,7 @@ #![allow(unexpected_cfgs)] -#[cfg(FALSE)] +#[cfg(false)] fn bar() {} fn foo() { diff --git a/tests/ui/check-cfg/allow-upper-level.rs b/tests/ui/check-cfg/allow-upper-level.rs index 2e6664c30d395..657a4768f952c 100644 --- a/tests/ui/check-cfg/allow-upper-level.rs +++ b/tests/ui/check-cfg/allow-upper-level.rs @@ -6,7 +6,7 @@ #[allow(unexpected_cfgs)] mod aa { - #[cfg(FALSE)] + #[cfg(false)] fn bar() {} } diff --git a/tests/ui/conditional-compilation/cfg-generic-params.rs b/tests/ui/conditional-compilation/cfg-generic-params.rs index 4bb8f8ae94f69..6480a0f24794c 100644 --- a/tests/ui/conditional-compilation/cfg-generic-params.rs +++ b/tests/ui/conditional-compilation/cfg-generic-params.rs @@ -1,18 +1,18 @@ //@ compile-flags:--cfg yes --check-cfg=cfg(yes,no) -fn f_lt<#[cfg(yes)] 'a: 'a, #[cfg(FALSE)] T>() {} -fn f_ty<#[cfg(FALSE)] 'a: 'a, #[cfg(yes)] T>() {} +fn f_lt<#[cfg(yes)] 'a: 'a, #[cfg(false)] T>() {} +fn f_ty<#[cfg(false)] 'a: 'a, #[cfg(yes)] T>() {} -type FnGood = for<#[cfg(yes)] 'a, #[cfg(FALSE)] T> fn(); // OK -type FnBad = for<#[cfg(FALSE)] 'a, #[cfg(yes)] T> fn(); +type FnGood = for<#[cfg(yes)] 'a, #[cfg(false)] T> fn(); // OK +type FnBad = for<#[cfg(false)] 'a, #[cfg(yes)] T> fn(); //~^ ERROR only lifetime parameters can be used in this context -type PolyGood = dyn for<#[cfg(yes)] 'a, #[cfg(FALSE)] T> Copy; // OK -type PolyBad = dyn for<#[cfg(FALSE)] 'a, #[cfg(yes)] T> Copy; +type PolyGood = dyn for<#[cfg(yes)] 'a, #[cfg(false)] T> Copy; // OK +type PolyBad = dyn for<#[cfg(false)] 'a, #[cfg(yes)] T> Copy; //~^ ERROR only lifetime parameters can be used in this context -struct WhereGood where for<#[cfg(yes)] 'a, #[cfg(FALSE)] T> u8: Copy; // OK -struct WhereBad where for<#[cfg(FALSE)] 'a, #[cfg(yes)] T> u8: Copy; +struct WhereGood where for<#[cfg(yes)] 'a, #[cfg(false)] T> u8: Copy; // OK +struct WhereBad where for<#[cfg(false)] 'a, #[cfg(yes)] T> u8: Copy; //~^ ERROR only lifetime parameters can be used in this context fn f_lt_no<#[cfg_attr(FALSE, unknown)] 'a>() {} // OK diff --git a/tests/ui/conditional-compilation/cfg-generic-params.stderr b/tests/ui/conditional-compilation/cfg-generic-params.stderr index 563616be36bc1..bae75dd0deb03 100644 --- a/tests/ui/conditional-compilation/cfg-generic-params.stderr +++ b/tests/ui/conditional-compilation/cfg-generic-params.stderr @@ -31,7 +31,7 @@ LL | struct WhereYes where for<#[cfg_attr(yes, unknown)] 'a> u8: Copy; error[E0658]: only lifetime parameters can be used in this context --> $DIR/cfg-generic-params.rs:7:48 | -LL | type FnBad = for<#[cfg(FALSE)] 'a, #[cfg(yes)] T> fn(); +LL | type FnBad = for<#[cfg(false)] 'a, #[cfg(yes)] T> fn(); | ^ | = note: see issue #108185 for more information @@ -41,7 +41,7 @@ LL | type FnBad = for<#[cfg(FALSE)] 'a, #[cfg(yes)] T> fn(); error[E0658]: only lifetime parameters can be used in this context --> $DIR/cfg-generic-params.rs:11:54 | -LL | type PolyBad = dyn for<#[cfg(FALSE)] 'a, #[cfg(yes)] T> Copy; +LL | type PolyBad = dyn for<#[cfg(false)] 'a, #[cfg(yes)] T> Copy; | ^ | = note: see issue #108185 for more information @@ -51,7 +51,7 @@ LL | type PolyBad = dyn for<#[cfg(FALSE)] 'a, #[cfg(yes)] T> Copy; error[E0658]: only lifetime parameters can be used in this context --> $DIR/cfg-generic-params.rs:15:57 | -LL | struct WhereBad where for<#[cfg(FALSE)] 'a, #[cfg(yes)] T> u8: Copy; +LL | struct WhereBad where for<#[cfg(false)] 'a, #[cfg(yes)] T> u8: Copy; | ^ | = note: see issue #108185 for more information diff --git a/tests/ui/conditional-compilation/cfg-in-crate-1.rs b/tests/ui/conditional-compilation/cfg-in-crate-1.rs index a1faa2397a33e..b9efa32babefd 100644 --- a/tests/ui/conditional-compilation/cfg-in-crate-1.rs +++ b/tests/ui/conditional-compilation/cfg-in-crate-1.rs @@ -1 +1 @@ -#![cfg(FALSE)] //~ ERROR `main` function not found in crate `cfg_in_crate_1` +#![cfg(false)] //~ ERROR `main` function not found in crate `cfg_in_crate_1` diff --git a/tests/ui/conditional-compilation/cfg-in-crate-1.stderr b/tests/ui/conditional-compilation/cfg-in-crate-1.stderr index 126e10cf0402c..352baf33091b4 100644 --- a/tests/ui/conditional-compilation/cfg-in-crate-1.stderr +++ b/tests/ui/conditional-compilation/cfg-in-crate-1.stderr @@ -1,7 +1,7 @@ error[E0601]: `main` function not found in crate `cfg_in_crate_1` --> $DIR/cfg-in-crate-1.rs:1:15 | -LL | #![cfg(FALSE)] +LL | #![cfg(false)] | ^ consider adding a `main` function to `$DIR/cfg-in-crate-1.rs` error: aborting due to 1 previous error diff --git a/tests/ui/conditional-compilation/cfg-non-opt-expr.rs b/tests/ui/conditional-compilation/cfg-non-opt-expr.rs index ae85f38e645e2..cae07ae0ced10 100644 --- a/tests/ui/conditional-compilation/cfg-non-opt-expr.rs +++ b/tests/ui/conditional-compilation/cfg-non-opt-expr.rs @@ -2,10 +2,10 @@ #![feature(custom_test_frameworks)] fn main() { - let _ = #[cfg(FALSE)] (); + let _ = #[cfg(false)] (); //~^ ERROR removing an expression is not supported in this position - let _ = 1 + 2 + #[cfg(FALSE)] 3; + let _ = 1 + 2 + #[cfg(false)] 3; //~^ ERROR removing an expression is not supported in this position - let _ = [1, 2, 3][#[cfg(FALSE)] 1]; + let _ = [1, 2, 3][#[cfg(false)] 1]; //~^ ERROR removing an expression is not supported in this position } diff --git a/tests/ui/conditional-compilation/cfg-non-opt-expr.stderr b/tests/ui/conditional-compilation/cfg-non-opt-expr.stderr index 06eaa59efdd7a..bd1bfeb06c7ad 100644 --- a/tests/ui/conditional-compilation/cfg-non-opt-expr.stderr +++ b/tests/ui/conditional-compilation/cfg-non-opt-expr.stderr @@ -1,19 +1,19 @@ error: removing an expression is not supported in this position --> $DIR/cfg-non-opt-expr.rs:5:13 | -LL | let _ = #[cfg(FALSE)] (); +LL | let _ = #[cfg(false)] (); | ^^^^^^^^^^^^^ error: removing an expression is not supported in this position --> $DIR/cfg-non-opt-expr.rs:7:21 | -LL | let _ = 1 + 2 + #[cfg(FALSE)] 3; +LL | let _ = 1 + 2 + #[cfg(false)] 3; | ^^^^^^^^^^^^^ error: removing an expression is not supported in this position --> $DIR/cfg-non-opt-expr.rs:9:23 | -LL | let _ = [1, 2, 3][#[cfg(FALSE)] 1]; +LL | let _ = [1, 2, 3][#[cfg(false)] 1]; | ^^^^^^^^^^^^^ error: aborting due to 3 previous errors diff --git a/tests/ui/conditional-compilation/module_with_cfg.rs b/tests/ui/conditional-compilation/module_with_cfg.rs index 778379fa6ea7a..29eb6d43aa794 100644 --- a/tests/ui/conditional-compilation/module_with_cfg.rs +++ b/tests/ui/conditional-compilation/module_with_cfg.rs @@ -1,3 +1,3 @@ //@ ignore-test (auxiliary, used by other tests) -#![cfg_attr(all(), cfg(FALSE))] +#![cfg_attr(all(), cfg(false))] diff --git a/tests/ui/consts/const-extern-fn/issue-68062-const-extern-fns-dont-need-fn-specifier-2.rs b/tests/ui/consts/const-extern-fn/issue-68062-const-extern-fns-dont-need-fn-specifier-2.rs index 7ced24808bf6e..50728970be2cf 100644 --- a/tests/ui/consts/const-extern-fn/issue-68062-const-extern-fns-dont-need-fn-specifier-2.rs +++ b/tests/ui/consts/const-extern-fn/issue-68062-const-extern-fns-dont-need-fn-specifier-2.rs @@ -1,6 +1,6 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn container() { const unsafe WhereIsFerris Now() {} //~^ ERROR expected one of `extern` or `fn` diff --git a/tests/ui/consts/const-extern-fn/issue-68062-const-extern-fns-dont-need-fn-specifier.rs b/tests/ui/consts/const-extern-fn/issue-68062-const-extern-fns-dont-need-fn-specifier.rs index 6f575d055a29b..20e79ca200bbd 100644 --- a/tests/ui/consts/const-extern-fn/issue-68062-const-extern-fns-dont-need-fn-specifier.rs +++ b/tests/ui/consts/const-extern-fn/issue-68062-const-extern-fns-dont-need-fn-specifier.rs @@ -1,6 +1,6 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn container() { const extern "Rust" PUT_ANYTHING_YOU_WANT_HERE bug() -> usize { 1 } //~^ ERROR expected `fn` diff --git a/tests/ui/delegation/explicit-paths-signature-pass.rs b/tests/ui/delegation/explicit-paths-signature-pass.rs index 8c16ad92393c9..11bc8a70db0e3 100644 --- a/tests/ui/delegation/explicit-paths-signature-pass.rs +++ b/tests/ui/delegation/explicit-paths-signature-pass.rs @@ -6,7 +6,7 @@ mod to_reuse { use crate::S; - pub fn foo<'a>(#[cfg(FALSE)] a: u8, _b: &'a S) -> u32 { + pub fn foo<'a>(#[cfg(false)] a: u8, _b: &'a S) -> u32 { 1 } } diff --git a/tests/ui/expr/if/attrs/bad-cfg.rs b/tests/ui/expr/if/attrs/bad-cfg.rs index 3f84929a00e4f..6e7f4b007a925 100644 --- a/tests/ui/expr/if/attrs/bad-cfg.rs +++ b/tests/ui/expr/if/attrs/bad-cfg.rs @@ -1,5 +1,5 @@ #![feature(stmt_expr_attributes)] fn main() { - let _ = #[cfg(FALSE)] if true {}; //~ ERROR removing an expression + let _ = #[cfg(false)] if true {}; //~ ERROR removing an expression } diff --git a/tests/ui/expr/if/attrs/bad-cfg.stderr b/tests/ui/expr/if/attrs/bad-cfg.stderr index ca0eced267d65..d12f5eeaf5fae 100644 --- a/tests/ui/expr/if/attrs/bad-cfg.stderr +++ b/tests/ui/expr/if/attrs/bad-cfg.stderr @@ -1,7 +1,7 @@ error: removing an expression is not supported in this position --> $DIR/bad-cfg.rs:4:13 | -LL | let _ = #[cfg(FALSE)] if true {}; +LL | let _ = #[cfg(false)] if true {}; | ^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/expr/if/attrs/cfg-false-if-attr.rs b/tests/ui/expr/if/attrs/cfg-false-if-attr.rs index c139b347d9983..e6c83b86cb773 100644 --- a/tests/ui/expr/if/attrs/cfg-false-if-attr.rs +++ b/tests/ui/expr/if/attrs/cfg-false-if-attr.rs @@ -1,12 +1,12 @@ //@ check-pass -#[cfg(FALSE)] +#[cfg(false)] fn simple_attr() { #[attr] if true {} #[allow_warnings] if true {} } -#[cfg(FALSE)] +#[cfg(false)] fn if_else_chain() { #[first_attr] if true { } else if false { @@ -14,20 +14,20 @@ fn if_else_chain() { } } -#[cfg(FALSE)] +#[cfg(false)] fn if_let() { #[attr] if let Some(_) = Some(true) {} } fn bar() { - #[cfg(FALSE)] + #[cfg(false)] if true { - let x: () = true; // Should not error due to the #[cfg(FALSE)] + let x: () = true; // Should not error due to the #[cfg(false)] } - #[cfg_attr(not(FALSE), cfg(FALSE))] + #[cfg_attr(not(FALSE), cfg(false))] if true { - let a: () = true; // Should not error due to the applied #[cfg(FALSE)] + let a: () = true; // Should not error due to the applied #[cfg(false)] } } diff --git a/tests/ui/expr/if/attrs/else-attrs.rs b/tests/ui/expr/if/attrs/else-attrs.rs index 85da7cf6bb8c3..4010d9d6132b9 100644 --- a/tests/ui/expr/if/attrs/else-attrs.rs +++ b/tests/ui/expr/if/attrs/else-attrs.rs @@ -1,11 +1,11 @@ -#[cfg(FALSE)] +#[cfg(false)] fn if_else_parse_error() { if true { } #[attr] else if false { //~ ERROR expected } } -#[cfg(FALSE)] +#[cfg(false)] fn else_attr_ifparse_error() { if true { } else #[attr] if false { //~ ERROR outer attributes are not allowed @@ -13,7 +13,7 @@ fn else_attr_ifparse_error() { } } -#[cfg(FALSE)] +#[cfg(false)] fn else_parse_error() { if true { } else if false { diff --git a/tests/ui/expr/if/attrs/gate-whole-expr.rs b/tests/ui/expr/if/attrs/gate-whole-expr.rs index bab01592c247b..885909016b5e1 100644 --- a/tests/ui/expr/if/attrs/gate-whole-expr.rs +++ b/tests/ui/expr/if/attrs/gate-whole-expr.rs @@ -3,7 +3,7 @@ fn main() { let x = 1; - #[cfg(FALSE)] + #[cfg(false)] if false { x = 2; } else if true { diff --git a/tests/ui/expr/if/attrs/let-chains-attr.rs b/tests/ui/expr/if/attrs/let-chains-attr.rs index b3dbd53e5798c..2cf1b169f0698 100644 --- a/tests/ui/expr/if/attrs/let-chains-attr.rs +++ b/tests/ui/expr/if/attrs/let-chains-attr.rs @@ -2,7 +2,7 @@ #![feature(let_chains)] -#[cfg(FALSE)] +#[cfg(false)] fn foo() { #[attr] if let Some(_) = Some(true) && let Ok(_) = Ok(1) { diff --git a/tests/ui/feature-gates/feature-gate-coroutines.rs b/tests/ui/feature-gates/feature-gate-coroutines.rs index f20dc56f12293..b37a61d9105f1 100644 --- a/tests/ui/feature-gates/feature-gate-coroutines.rs +++ b/tests/ui/feature-gates/feature-gate-coroutines.rs @@ -12,7 +12,7 @@ fn main() { //~^^ ERROR `yield` can only be used } -#[cfg(FALSE)] +#[cfg(false)] fn foo() { // Ok in 2024 edition yield; //~ ERROR yield syntax is experimental diff --git a/tests/ui/feature-gates/feature-gate-deref_patterns.rs b/tests/ui/feature-gates/feature-gate-deref_patterns.rs index b43001f2d53fa..53b4301f10c0c 100644 --- a/tests/ui/feature-gates/feature-gate-deref_patterns.rs +++ b/tests/ui/feature-gates/feature-gate-deref_patterns.rs @@ -4,6 +4,6 @@ fn main() { println!("x: {}", x); // `box` syntax is allowed to be cfg-ed out for historical reasons (#65742). - #[cfg(FALSE)] + #[cfg(false)] let box _x = Box::new('c'); } diff --git a/tests/ui/feature-gates/feature-gate-gen_blocks.rs b/tests/ui/feature-gates/feature-gate-gen_blocks.rs index 01fd922b0e999..989daf471bcb9 100644 --- a/tests/ui/feature-gates/feature-gate-gen_blocks.rs +++ b/tests/ui/feature-gates/feature-gate-gen_blocks.rs @@ -17,7 +17,7 @@ fn test_async_gen() { fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn foo() { gen {}; //[e2024]~^ ERROR: gen blocks are experimental diff --git a/tests/ui/feature-gates/feature-gate-guard-patterns.rs b/tests/ui/feature-gates/feature-gate-guard-patterns.rs index 52ed89e668b1f..74fb5817081c7 100644 --- a/tests/ui/feature-gates/feature-gate-guard-patterns.rs +++ b/tests/ui/feature-gates/feature-gate-guard-patterns.rs @@ -30,7 +30,7 @@ fn other_guards_dont() { while let (x if guard(x)) = 0 {} //~^ ERROR: guard patterns are experimental - #[cfg(FALSE)] + #[cfg(false)] while let (x if guard(x)) = 0 {} //~^ ERROR: guard patterns are experimental } diff --git a/tests/ui/feature-gates/feature-gate-mut-ref.rs b/tests/ui/feature-gates/feature-gate-mut-ref.rs index 806b25de66ff2..752ae35d8a9ae 100644 --- a/tests/ui/feature-gates/feature-gate-mut-ref.rs +++ b/tests/ui/feature-gates/feature-gate-mut-ref.rs @@ -6,8 +6,8 @@ fn main() { let mut ref mut z = 14; //~ ERROR [E0658] z = &mut 15; - #[cfg(FALSE)] + #[cfg(false)] let mut ref x = 10; //~ ERROR [E0658] - #[cfg(FALSE)] + #[cfg(false)] let mut ref mut y = 10; //~ ERROR [E0658] } diff --git a/tests/ui/feature-gates/feature-gate-never_patterns.rs b/tests/ui/feature-gates/feature-gate-never_patterns.rs index d23405ada2d4d..2cb0b5a6679d5 100644 --- a/tests/ui/feature-gates/feature-gate-never_patterns.rs +++ b/tests/ui/feature-gates/feature-gate-never_patterns.rs @@ -15,12 +15,12 @@ fn main() { //~^ ERROR `!` patterns are experimental } // Check that the gate operates even behind `cfg`. - #[cfg(FALSE)] + #[cfg(false)] match *ptr { ! //~^ ERROR `!` patterns are experimental } - #[cfg(FALSE)] + #[cfg(false)] match *ptr { ! => {} //~^ ERROR `!` patterns are experimental @@ -60,13 +60,13 @@ fn main() { // Check that the gate operates even behind `cfg`. match Some(0) { None => {} - #[cfg(FALSE)] + #[cfg(false)] Some(_) //~^ ERROR `match` arm with no body } match Some(0) { _ => {} - #[cfg(FALSE)] + #[cfg(false)] Some(_) if false //~^ ERROR `match` arm with no body } diff --git a/tests/ui/feature-gates/feature-gate-postfix_match.rs b/tests/ui/feature-gates/feature-gate-postfix_match.rs index dce7e81a9ae44..2226816e5ea7c 100644 --- a/tests/ui/feature-gates/feature-gate-postfix_match.rs +++ b/tests/ui/feature-gates/feature-gate-postfix_match.rs @@ -9,7 +9,7 @@ fn main() { }; // Test that the gate works behind a cfg - #[cfg(FALSE)] + #[cfg(false)] val.match { //~ ERROR postfix match is experimental Some(42) => "the answer to life, the universe, and everything", _ => "might be the answer to something" diff --git a/tests/ui/feature-gates/feature-gate-yeet_expr-in-cfg.rs b/tests/ui/feature-gates/feature-gate-yeet_expr-in-cfg.rs index 33fda822baad6..bacbbc57c2c90 100644 --- a/tests/ui/feature-gates/feature-gate-yeet_expr-in-cfg.rs +++ b/tests/ui/feature-gates/feature-gate-yeet_expr-in-cfg.rs @@ -1,7 +1,7 @@ //@ compile-flags: --edition 2021 pub fn demo() -> Option { - #[cfg(FALSE)] + #[cfg(false)] { do yeet //~ ERROR `do yeet` expression is experimental } @@ -9,7 +9,7 @@ pub fn demo() -> Option { Some(1) } -#[cfg(FALSE)] +#[cfg(false)] pub fn alternative() -> Result<(), String> { do yeet "hello"; //~ ERROR `do yeet` expression is experimental } diff --git a/tests/ui/feature-gates/soft-syntax-gates-with-errors.rs b/tests/ui/feature-gates/soft-syntax-gates-with-errors.rs index 2aa2ed34020cf..87629a5bcce77 100644 --- a/tests/ui/feature-gates/soft-syntax-gates-with-errors.rs +++ b/tests/ui/feature-gates/soft-syntax-gates-with-errors.rs @@ -5,7 +5,7 @@ macro a() {} //~^ ERROR: `macro` is experimental -#[cfg(FALSE)] +#[cfg(false)] macro b() {} macro_rules! identity { @@ -17,13 +17,13 @@ identity! { //~^ ERROR: `macro` is experimental } -#[cfg(FALSE)] +#[cfg(false)] identity! { macro d() {} // No error } identity! { - #[cfg(FALSE)] + #[cfg(false)] macro e() {} } diff --git a/tests/ui/feature-gates/soft-syntax-gates-without-errors.rs b/tests/ui/feature-gates/soft-syntax-gates-without-errors.rs index 056c8fb04f45d..72d0bf1ccd524 100644 --- a/tests/ui/feature-gates/soft-syntax-gates-without-errors.rs +++ b/tests/ui/feature-gates/soft-syntax-gates-without-errors.rs @@ -2,7 +2,7 @@ // This file is used to test the behavior of the early-pass syntax warnings. // If macro syntax is stabilized, replace with a different unstable syntax. -#[cfg(FALSE)] +#[cfg(false)] macro b() {} //~^ WARN: `macro` is experimental //~| WARN: unstable syntax @@ -11,13 +11,13 @@ macro_rules! identity { ($($x:tt)*) => ($($x)*); } -#[cfg(FALSE)] +#[cfg(false)] identity! { macro d() {} // No error } identity! { - #[cfg(FALSE)] + #[cfg(false)] macro e() {} //~^ WARN: `macro` is experimental //~| WARN: unstable syntax diff --git a/tests/ui/feature-gates/stmt_expr_attrs_no_feature.rs b/tests/ui/feature-gates/stmt_expr_attrs_no_feature.rs index a160a9bb082dc..4523afa7c4bd1 100644 --- a/tests/ui/feature-gates/stmt_expr_attrs_no_feature.rs +++ b/tests/ui/feature-gates/stmt_expr_attrs_no_feature.rs @@ -25,7 +25,7 @@ fn main() { // Check that cfg works right -#[cfg(FALSE)] +#[cfg(false)] fn c() { #[rustc_dummy] 5; @@ -37,7 +37,7 @@ fn j() { 5; } -#[cfg_attr(not(FALSE), cfg(FALSE))] +#[cfg_attr(not(FALSE), cfg(false))] fn d() { #[rustc_dummy] 8; @@ -57,7 +57,7 @@ macro_rules! item_mac { #[rustc_dummy] 42; - #[cfg(FALSE)] + #[cfg(false)] fn f() { #[rustc_dummy] 5; @@ -69,7 +69,7 @@ macro_rules! item_mac { 5; } - #[cfg_attr(not(FALSE), cfg(FALSE))] + #[cfg_attr(not(FALSE), cfg(false))] fn g() { #[rustc_dummy] 8; @@ -90,42 +90,42 @@ item_mac!(e); // check that the gate visitor works right: extern "C" { - #[cfg(FALSE)] + #[cfg(false)] fn x(a: [u8; #[rustc_dummy] 5]); fn y(a: [u8; #[rustc_dummy] 5]); //~ ERROR attributes on expressions are experimental } struct Foo; impl Foo { - #[cfg(FALSE)] + #[cfg(false)] const X: u8 = #[rustc_dummy] 5; const Y: u8 = #[rustc_dummy] 5; //~ ERROR attributes on expressions are experimental } trait Bar { - #[cfg(FALSE)] + #[cfg(false)] const X: [u8; #[rustc_dummy] 5]; const Y: [u8; #[rustc_dummy] 5]; //~ ERROR attributes on expressions are experimental } struct Joyce { - #[cfg(FALSE)] + #[cfg(false)] field: [u8; #[rustc_dummy] 5], field2: [u8; #[rustc_dummy] 5] //~ ERROR attributes on expressions are experimental } struct Walky( - #[cfg(FALSE)] [u8; #[rustc_dummy] 5], + #[cfg(false)] [u8; #[rustc_dummy] 5], [u8; #[rustc_dummy] 5] //~ ERROR attributes on expressions are experimental ); enum Mike { Happy( - #[cfg(FALSE)] [u8; #[rustc_dummy] 5], + #[cfg(false)] [u8; #[rustc_dummy] 5], [u8; #[rustc_dummy] 5] //~ ERROR attributes on expressions are experimental ), Angry { - #[cfg(FALSE)] + #[cfg(false)] field: [u8; #[rustc_dummy] 5], field2: [u8; #[rustc_dummy] 5] //~ ERROR attributes on expressions are experimental } @@ -133,7 +133,7 @@ enum Mike { fn pat() { match 5 { - #[cfg(FALSE)] + #[cfg(false)] 5 => #[rustc_dummy] (), 6 => #[rustc_dummy] (), //~ ERROR attributes on expressions are experimental _ => (), diff --git a/tests/ui/filter-block-view-items.rs b/tests/ui/filter-block-view-items.rs index 975ab19ddf25f..cb599c2726470 100644 --- a/tests/ui/filter-block-view-items.rs +++ b/tests/ui/filter-block-view-items.rs @@ -3,5 +3,5 @@ pub fn main() { // Make sure that this view item is filtered out because otherwise it would // trigger a compilation error - #[cfg(FALSE)] use bar as foo; + #[cfg(false)] use bar as foo; } diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-inclusive-dotdotdot-bad-syntax.rs b/tests/ui/half-open-range-patterns/half-open-range-pats-inclusive-dotdotdot-bad-syntax.rs index 33506a5c444a7..01f4340b14ada 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-inclusive-dotdotdot-bad-syntax.rs +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-inclusive-dotdotdot-bad-syntax.rs @@ -9,7 +9,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn syntax() { match scrutinee { ...X => {} //~ ERROR range-to patterns with `...` are not allowed diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-inclusive-no-end.rs b/tests/ui/half-open-range-patterns/half-open-range-pats-inclusive-no-end.rs index 2f1ec65897211..24eb993473291 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-inclusive-no-end.rs +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-inclusive-no-end.rs @@ -3,7 +3,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn foo() { if let 0... = 1 {} //~ ERROR inclusive range with no end if let 0..= = 1 {} //~ ERROR inclusive range with no end diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-ref-ambiguous-interp.rs b/tests/ui/half-open-range-patterns/half-open-range-pats-ref-ambiguous-interp.rs index 2d63fe0785616..6b33ead3f87dd 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-ref-ambiguous-interp.rs +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-ref-ambiguous-interp.rs @@ -1,6 +1,6 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn syntax() { match &0 { &0.. | _ => {} diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-syntactic-pass.rs b/tests/ui/half-open-range-patterns/half-open-range-pats-syntactic-pass.rs index 4e3fffbef2de5..02699e76ad296 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-syntactic-pass.rs +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-syntactic-pass.rs @@ -4,7 +4,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn syntax() { match scrutinee { X.. | 0.. | 'a'.. | 0.0f32.. => {} diff --git a/tests/ui/inner-attrs-on-impl.rs b/tests/ui/inner-attrs-on-impl.rs index 75f406232e200..1dce1cdd261af 100644 --- a/tests/ui/inner-attrs-on-impl.rs +++ b/tests/ui/inner-attrs-on-impl.rs @@ -3,7 +3,7 @@ struct Foo; impl Foo { - #![cfg(FALSE)] + #![cfg(false)] fn method(&self) -> bool { false } } @@ -12,7 +12,7 @@ impl Foo { #![cfg(not(FALSE))] // check that we don't eat attributes too eagerly. - #[cfg(FALSE)] + #[cfg(false)] fn method(&self) -> bool { false } fn method(&self) -> bool { true } diff --git a/tests/ui/issues/issue-11004.rs b/tests/ui/issues/issue-11004.rs index 09d5476dbe608..7292843c86a9c 100644 --- a/tests/ui/issues/issue-11004.rs +++ b/tests/ui/issues/issue-11004.rs @@ -9,7 +9,7 @@ unsafe fn access(n:*mut A) -> (i32, f64) { (x, y) } -#[cfg(FALSE)] +#[cfg(false)] unsafe fn access(n:*mut A) -> (i32, f64) { let x : i32 = (*n).x; let y : f64 = (*n).y; diff --git a/tests/ui/issues/issue-11085.rs b/tests/ui/issues/issue-11085.rs index d0703b0639542..c3f13199b308e 100644 --- a/tests/ui/issues/issue-11085.rs +++ b/tests/ui/issues/issue-11085.rs @@ -3,7 +3,7 @@ #![allow(dead_code)] struct Foo { - #[cfg(FALSE)] + #[cfg(false)] bar: baz, foo: isize, } @@ -15,18 +15,18 @@ struct Foo2 { enum Bar1 { Bar1_1, - #[cfg(FALSE)] + #[cfg(false)] Bar1_2(NotAType), } enum Bar2 { - #[cfg(FALSE)] + #[cfg(false)] Bar2_1(NotAType), } enum Bar3 { Bar3_1 { - #[cfg(FALSE)] + #[cfg(false)] foo: isize, bar: isize, } diff --git a/tests/ui/issues/issue-16819.rs b/tests/ui/issues/issue-16819.rs index e2b1090917774..2805c82acfb2d 100644 --- a/tests/ui/issues/issue-16819.rs +++ b/tests/ui/issues/issue-16819.rs @@ -3,7 +3,7 @@ // `#[cfg]` on struct field permits empty unusable struct struct S { - #[cfg(FALSE)] + #[cfg(false)] a: int, } diff --git a/tests/ui/lexer/error-stage.rs b/tests/ui/lexer/error-stage.rs index c8d88f745a1f0..f0ccb886d0d28 100644 --- a/tests/ui/lexer/error-stage.rs +++ b/tests/ui/lexer/error-stage.rs @@ -59,7 +59,7 @@ const _: () = sink! { // The invalid literals used to cause errors, but this was changed by #102944. // Except for `0b010.0f32`, because it's a lexer error. -#[cfg(FALSE)] +#[cfg(false)] fn configured_out() { "string"any_suffix; // OK 10u123; // OK diff --git a/tests/ui/link-native-libs/link-attr-validation-late.rs b/tests/ui/link-native-libs/link-attr-validation-late.rs index 34f720dd2d3c5..4eeb8ba4884ff 100644 --- a/tests/ui/link-native-libs/link-attr-validation-late.rs +++ b/tests/ui/link-native-libs/link-attr-validation-late.rs @@ -9,7 +9,7 @@ extern "C" {} #[link(name = "foo", name = "bar")] //~ ERROR multiple `name` arguments #[link(name = "...", kind = "dylib", kind = "bar")] //~ ERROR multiple `kind` arguments #[link(name = "...", modifiers = "+verbatim", modifiers = "bar")] //~ ERROR multiple `modifiers` arguments -#[link(name = "...", cfg(FALSE), cfg(FALSE))] //~ ERROR multiple `cfg` arguments +#[link(name = "...", cfg(false), cfg(false))] //~ ERROR multiple `cfg` arguments #[link(wasm_import_module = "foo", wasm_import_module = "bar")] //~ ERROR multiple `wasm_import_module` arguments extern "C" {} diff --git a/tests/ui/link-native-libs/link-attr-validation-late.stderr b/tests/ui/link-native-libs/link-attr-validation-late.stderr index 1ad5fbaf7de80..f3989c09360fc 100644 --- a/tests/ui/link-native-libs/link-attr-validation-late.stderr +++ b/tests/ui/link-native-libs/link-attr-validation-late.stderr @@ -31,7 +31,7 @@ LL | #[link(name = "...", modifiers = "+verbatim", modifiers = "bar")] error: multiple `cfg` arguments in a single `#[link]` attribute --> $DIR/link-attr-validation-late.rs:12:34 | -LL | #[link(name = "...", cfg(FALSE), cfg(FALSE))] +LL | #[link(name = "...", cfg(false), cfg(false))] | ^^^^^^^^^^ error: multiple `wasm_import_module` arguments in a single `#[link]` attribute diff --git a/tests/ui/lint/unused/unused-attr-macro-rules.rs b/tests/ui/lint/unused/unused-attr-macro-rules.rs index c0fc280ab1a7c..7a8a1bb1ae523 100644 --- a/tests/ui/lint/unused/unused-attr-macro-rules.rs +++ b/tests/ui/lint/unused/unused-attr-macro-rules.rs @@ -17,7 +17,7 @@ macro_rules! foo2 { () => {}; } -#[cfg(FALSE)] +#[cfg(false)] macro_rules! foo { () => {}; } diff --git a/tests/ui/macros/lint-trailing-macro-call.rs b/tests/ui/macros/lint-trailing-macro-call.rs index 66dce057d0f5c..78b861f1df17a 100644 --- a/tests/ui/macros/lint-trailing-macro-call.rs +++ b/tests/ui/macros/lint-trailing-macro-call.rs @@ -6,7 +6,7 @@ macro_rules! expand_it { () => { - #[cfg(FALSE)] 25; //~ WARN trailing semicolon in macro + #[cfg(false)] 25; //~ WARN 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 13cecc3a31d23..223b85e112ed6 100644 --- a/tests/ui/macros/lint-trailing-macro-call.stderr +++ b/tests/ui/macros/lint-trailing-macro-call.stderr @@ -1,7 +1,7 @@ warning: trailing semicolon in macro used in expression position --> $DIR/lint-trailing-macro-call.rs:9:25 | -LL | #[cfg(FALSE)] 25; +LL | #[cfg(false)] 25; | ^ ... LL | expand_it!() @@ -20,7 +20,7 @@ Future incompatibility report: Future breakage diagnostic: warning: trailing semicolon in macro used in expression position --> $DIR/lint-trailing-macro-call.rs:9:25 | -LL | #[cfg(FALSE)] 25; +LL | #[cfg(false)] 25; | ^ ... LL | expand_it!() diff --git a/tests/ui/macros/macro-attributes.rs b/tests/ui/macros/macro-attributes.rs index 8329079076698..976d2cbcccdbb 100644 --- a/tests/ui/macros/macro-attributes.rs +++ b/tests/ui/macros/macro-attributes.rs @@ -9,7 +9,7 @@ macro_rules! compiles_fine { // check that the attributes are recognised by requiring this // to be removed to avoid a compile error - #[cfg(FALSE)] + #[cfg(false)] static MISTYPED: () = "foo"; } } diff --git a/tests/ui/macros/macro-inner-attributes.rs b/tests/ui/macros/macro-inner-attributes.rs index a1eb7cd15c4cc..1a832ca9b0c4b 100644 --- a/tests/ui/macros/macro-inner-attributes.rs +++ b/tests/ui/macros/macro-inner-attributes.rs @@ -5,7 +5,7 @@ macro_rules! test { ($nm:ident, $i:item) => (mod $nm { #![$a] $i }); } test!(a, - #[cfg(FALSE)], + #[cfg(false)], pub fn bar() { }); test!(b, diff --git a/tests/ui/macros/macro-outer-attributes.rs b/tests/ui/macros/macro-outer-attributes.rs index 8c79683f49a96..5b41cf9fd29d6 100644 --- a/tests/ui/macros/macro-outer-attributes.rs +++ b/tests/ui/macros/macro-outer-attributes.rs @@ -5,7 +5,7 @@ macro_rules! test { ($nm:ident, $i:item) => (mod $nm { #[$a] $i }); } test!(a, - #[cfg(FALSE)], + #[cfg(false)], pub fn bar() { }); test!(b, diff --git a/tests/ui/macros/macro-outer-attributes.stderr b/tests/ui/macros/macro-outer-attributes.stderr index a8809f3fcff69..a894c90f4c32a 100644 --- a/tests/ui/macros/macro-outer-attributes.stderr +++ b/tests/ui/macros/macro-outer-attributes.stderr @@ -16,7 +16,7 @@ LL | $i:item) => (mod $nm { #[$a] $i }); } | ^^^^^ LL | LL | / test!(a, -LL | | #[cfg(FALSE)], +LL | | #[cfg(false)], LL | | pub fn bar() { }); | |_______________________- in this macro invocation = note: this error originates in the macro `test` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/macros/macro-with-attrs2.rs b/tests/ui/macros/macro-with-attrs2.rs index 37188e45ad3b5..7d0bf91142532 100644 --- a/tests/ui/macros/macro-with-attrs2.rs +++ b/tests/ui/macros/macro-with-attrs2.rs @@ -1,6 +1,6 @@ //@ run-pass -#[cfg(FALSE)] +#[cfg(false)] macro_rules! foo { () => (1) } #[cfg(not(FALSE))] diff --git a/tests/ui/nested-cfg-attrs.rs b/tests/ui/nested-cfg-attrs.rs index 0af28fc3d8ec6..941807a84310e 100644 --- a/tests/ui/nested-cfg-attrs.rs +++ b/tests/ui/nested-cfg-attrs.rs @@ -1,4 +1,4 @@ -#[cfg_attr(all(), cfg_attr(all(), cfg(FALSE)))] +#[cfg_attr(all(), cfg_attr(all(), cfg(false)))] fn f() {} fn main() { f() } //~ ERROR cannot find function `f` in this scope diff --git a/tests/ui/or-patterns/fn-param-wrap-parens.fixed b/tests/ui/or-patterns/fn-param-wrap-parens.fixed index 7b0bbd04d9784..fbf60069c7d42 100644 --- a/tests/ui/or-patterns/fn-param-wrap-parens.fixed +++ b/tests/ui/or-patterns/fn-param-wrap-parens.fixed @@ -9,5 +9,5 @@ fn main() {} enum E { A, B } use E::*; -#[cfg(FALSE)] +#[cfg(false)] fn fun1((A | B): E) {} //~ ERROR top-level or-patterns are not allowed diff --git a/tests/ui/or-patterns/fn-param-wrap-parens.rs b/tests/ui/or-patterns/fn-param-wrap-parens.rs index dadbb8a906a7b..d796f998e97c7 100644 --- a/tests/ui/or-patterns/fn-param-wrap-parens.rs +++ b/tests/ui/or-patterns/fn-param-wrap-parens.rs @@ -9,5 +9,5 @@ fn main() {} enum E { A, B } use E::*; -#[cfg(FALSE)] +#[cfg(false)] fn fun1(A | B: E) {} //~ ERROR top-level or-patterns are not allowed diff --git a/tests/ui/or-patterns/or-patterns-syntactic-pass.rs b/tests/ui/or-patterns/or-patterns-syntactic-pass.rs index 6a8d0a5adb490..6fd5840e801a9 100644 --- a/tests/ui/or-patterns/or-patterns-syntactic-pass.rs +++ b/tests/ui/or-patterns/or-patterns-syntactic-pass.rs @@ -18,7 +18,7 @@ accept_pat!([p | q]); // Non-macro tests: -#[cfg(FALSE)] +#[cfg(false)] fn or_patterns() { // Top level of `let`: let (| A | B); diff --git a/tests/ui/or-patterns/remove-leading-vert.fixed b/tests/ui/or-patterns/remove-leading-vert.fixed index 3ec815c846843..136ca5765b7e2 100644 --- a/tests/ui/or-patterns/remove-leading-vert.fixed +++ b/tests/ui/or-patterns/remove-leading-vert.fixed @@ -6,7 +6,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn leading() { fn fun1( A: E) {} //~ ERROR top-level or-patterns are not allowed fn fun2( A: E) {} //~ ERROR unexpected `||` before function parameter @@ -21,7 +21,7 @@ fn leading() { let NS { f: | A }: NS; //~ ERROR unexpected token `||` in pattern } -#[cfg(FALSE)] +#[cfg(false)] fn trailing() { let ( A ): E; //~ ERROR a trailing `|` is not allowed in an or-pattern let (a ,): (E,); //~ ERROR a trailing `|` is not allowed in an or-pattern diff --git a/tests/ui/or-patterns/remove-leading-vert.rs b/tests/ui/or-patterns/remove-leading-vert.rs index 2aeeb0e979f6d..d9e9c9fe4d2f8 100644 --- a/tests/ui/or-patterns/remove-leading-vert.rs +++ b/tests/ui/or-patterns/remove-leading-vert.rs @@ -6,7 +6,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn leading() { fn fun1( | A: E) {} //~ ERROR top-level or-patterns are not allowed fn fun2( || A: E) {} //~ ERROR unexpected `||` before function parameter @@ -21,7 +21,7 @@ fn leading() { let NS { f: || A }: NS; //~ ERROR unexpected token `||` in pattern } -#[cfg(FALSE)] +#[cfg(false)] fn trailing() { let ( A | ): E; //~ ERROR a trailing `|` is not allowed in an or-pattern let (a |,): (E,); //~ ERROR a trailing `|` is not allowed in an or-pattern diff --git a/tests/ui/parser/assoc/assoc-const-underscore-syntactic-pass.rs b/tests/ui/parser/assoc/assoc-const-underscore-syntactic-pass.rs index 6c04537919165..63c567b2d0332 100644 --- a/tests/ui/parser/assoc/assoc-const-underscore-syntactic-pass.rs +++ b/tests/ui/parser/assoc/assoc-const-underscore-syntactic-pass.rs @@ -4,7 +4,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] const _: () = { pub trait A { const _: () = (); diff --git a/tests/ui/parser/assoc/assoc-static-syntactic-fail.rs b/tests/ui/parser/assoc/assoc-static-syntactic-fail.rs index 492f2ea16ef57..e875d733bd625 100644 --- a/tests/ui/parser/assoc/assoc-static-syntactic-fail.rs +++ b/tests/ui/parser/assoc/assoc-static-syntactic-fail.rs @@ -2,7 +2,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] impl S { static IA: u8 = 0; //~ ERROR associated `static` items are not allowed static IB: u8; //~ ERROR associated `static` items are not allowed @@ -12,7 +12,7 @@ impl S { //~^ ERROR a static item cannot be `default` } -#[cfg(FALSE)] +#[cfg(false)] trait T { static TA: u8 = 0; //~ ERROR associated `static` items are not allowed static TB: u8; //~ ERROR associated `static` items are not allowed @@ -22,7 +22,7 @@ trait T { //~^ ERROR a static item cannot be `default` } -#[cfg(FALSE)] +#[cfg(false)] impl T for S { static TA: u8 = 0; //~ ERROR associated `static` items are not allowed static TB: u8; //~ ERROR associated `static` items are not allowed diff --git a/tests/ui/parser/attribute/attr-stmt-expr-attr-bad.rs b/tests/ui/parser/attribute/attr-stmt-expr-attr-bad.rs index 26761a1d2544c..1380974538a50 100644 --- a/tests/ui/parser/attribute/attr-stmt-expr-attr-bad.rs +++ b/tests/ui/parser/attribute/attr-stmt-expr-attr-bad.rs @@ -1,108 +1,108 @@ fn main() {} -#[cfg(FALSE)] fn e() { let _ = [#[attr]]; } +#[cfg(false)] fn e() { let _ = [#[attr]]; } //~^ ERROR expected expression, found `]` -#[cfg(FALSE)] fn e() { let _ = foo#[attr](); } +#[cfg(false)] fn e() { let _ = foo#[attr](); } //~^ ERROR expected one of -#[cfg(FALSE)] fn e() { let _ = foo(#![attr]); } +#[cfg(false)] fn e() { let _ = foo(#![attr]); } //~^ ERROR an inner attribute is not permitted in this context //~| ERROR an inner attribute is not permitted in this context //~| ERROR expected expression, found `)` -#[cfg(FALSE)] fn e() { let _ = x.foo(#![attr]); } +#[cfg(false)] fn e() { let _ = x.foo(#![attr]); } //~^ ERROR an inner attribute is not permitted in this context //~| ERROR expected expression, found `)` -#[cfg(FALSE)] fn e() { let _ = 0 + #![attr] 0; } +#[cfg(false)] fn e() { let _ = 0 + #![attr] 0; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = !#![attr] 0; } +#[cfg(false)] fn e() { let _ = !#![attr] 0; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = -#![attr] 0; } +#[cfg(false)] fn e() { let _ = -#![attr] 0; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = x #![attr] as Y; } +#[cfg(false)] fn e() { let _ = x #![attr] as Y; } //~^ ERROR expected one of -#[cfg(FALSE)] fn e() { let _ = || #![attr] foo; } +#[cfg(false)] fn e() { let _ = || #![attr] foo; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = move || #![attr] foo; } +#[cfg(false)] fn e() { let _ = move || #![attr] foo; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = || #![attr] {foo}; } +#[cfg(false)] fn e() { let _ = || #![attr] {foo}; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = move || #![attr] {foo}; } +#[cfg(false)] fn e() { let _ = move || #![attr] {foo}; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = #[attr] ..#[attr] 0; } +#[cfg(false)] fn e() { let _ = #[attr] ..#[attr] 0; } //~^ ERROR attributes are not allowed on range expressions starting with `..` -#[cfg(FALSE)] fn e() { let _ = #[attr] ..; } +#[cfg(false)] fn e() { let _ = #[attr] ..; } //~^ ERROR attributes are not allowed on range expressions starting with `..` -#[cfg(FALSE)] fn e() { let _ = #[attr] &#![attr] 0; } +#[cfg(false)] fn e() { let _ = #[attr] &#![attr] 0; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = #[attr] &mut #![attr] 0; } +#[cfg(false)] fn e() { let _ = #[attr] &mut #![attr] 0; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = if 0 #[attr] {}; } +#[cfg(false)] fn e() { let _ = if 0 #[attr] {}; } //~^ ERROR outer attributes are not allowed on `if` -#[cfg(FALSE)] fn e() { let _ = if 0 {#![attr]}; } +#[cfg(false)] fn e() { let _ = if 0 {#![attr]}; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = if 0 {} #[attr] else {}; } +#[cfg(false)] fn e() { let _ = if 0 {} #[attr] else {}; } //~^ ERROR expected one of -#[cfg(FALSE)] fn e() { let _ = if 0 {} else #[attr] {}; } +#[cfg(false)] fn e() { let _ = if 0 {} else #[attr] {}; } //~^ ERROR outer attributes are not allowed on `if` -#[cfg(FALSE)] fn e() { let _ = if 0 {} else {#![attr]}; } +#[cfg(false)] fn e() { let _ = if 0 {} else {#![attr]}; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = if 0 {} else #[attr] if 0 {}; } +#[cfg(false)] fn e() { let _ = if 0 {} else #[attr] if 0 {}; } //~^ ERROR outer attributes are not allowed on `if` -#[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 #[attr] {}; } +#[cfg(false)] fn e() { let _ = if 0 {} else if 0 #[attr] {}; } //~^ ERROR outer attributes are not allowed on `if` -#[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 {#![attr]}; } +#[cfg(false)] fn e() { let _ = if 0 {} else if 0 {#![attr]}; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = if let _ = 0 #[attr] {}; } +#[cfg(false)] fn e() { let _ = if let _ = 0 #[attr] {}; } //~^ ERROR outer attributes are not allowed on `if` -#[cfg(FALSE)] fn e() { let _ = if let _ = 0 {#![attr]}; } +#[cfg(false)] fn e() { let _ = if let _ = 0 {#![attr]}; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} #[attr] else {}; } +#[cfg(false)] fn e() { let _ = if let _ = 0 {} #[attr] else {}; } //~^ ERROR expected one of -#[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else #[attr] {}; } +#[cfg(false)] fn e() { let _ = if let _ = 0 {} else #[attr] {}; } //~^ ERROR outer attributes are not allowed on `if` -#[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else {#![attr]}; } +#[cfg(false)] fn e() { let _ = if let _ = 0 {} else {#![attr]}; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else #[attr] if let _ = 0 {}; } +#[cfg(false)] fn e() { let _ = if let _ = 0 {} else #[attr] if let _ = 0 {}; } //~^ ERROR outer attributes are not allowed on `if` -#[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 #[attr] {}; } +#[cfg(false)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 #[attr] {}; } //~^ ERROR outer attributes are not allowed on `if` -#[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 {#![attr]}; } +#[cfg(false)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 {#![attr]}; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn s() { #[attr] #![attr] let _ = 0; } +#[cfg(false)] fn s() { #[attr] #![attr] let _ = 0; } //~^ ERROR an inner attribute is not permitted following an outer attribute -#[cfg(FALSE)] fn s() { #[attr] #![attr] 0; } +#[cfg(false)] fn s() { #[attr] #![attr] 0; } //~^ ERROR an inner attribute is not permitted following an outer attribute -#[cfg(FALSE)] fn s() { #[attr] #![attr] foo!(); } +#[cfg(false)] fn s() { #[attr] #![attr] foo!(); } //~^ ERROR an inner attribute is not permitted following an outer attribute -#[cfg(FALSE)] fn s() { #[attr] #![attr] foo![]; } +#[cfg(false)] fn s() { #[attr] #![attr] foo![]; } //~^ ERROR an inner attribute is not permitted following an outer attribute -#[cfg(FALSE)] fn s() { #[attr] #![attr] foo!{}; } +#[cfg(false)] fn s() { #[attr] #![attr] foo!{}; } //~^ ERROR an inner attribute is not permitted following an outer attribute // FIXME: Allow attributes in pattern constexprs? // note: requires parens in patterns to allow disambiguation -#[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] 10 => () } } +#[cfg(false)] fn e() { match 0 { 0..=#[attr] 10 => () } } //~^ ERROR inclusive range with no end //~| ERROR expected one of `=>`, `if`, or `|`, found `#` -#[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] -10 => () } } +#[cfg(false)] fn e() { match 0 { 0..=#[attr] -10 => () } } //~^ ERROR inclusive range with no end //~| ERROR expected one of `=>`, `if`, or `|`, found `#` -#[cfg(FALSE)] fn e() { match 0 { 0..=-#[attr] 10 => () } } +#[cfg(false)] fn e() { match 0 { 0..=-#[attr] 10 => () } } //~^ ERROR unexpected token: `#` -#[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] FOO => () } } +#[cfg(false)] fn e() { match 0 { 0..=#[attr] FOO => () } } //~^ ERROR inclusive range with no end //~| ERROR expected one of `=>`, `if`, or `|`, found `#` -#[cfg(FALSE)] fn e() { let _ = x.#![attr]foo(); } +#[cfg(false)] fn e() { let _ = x.#![attr]foo(); } //~^ ERROR unexpected token: `#` //~| ERROR expected one of `.` -#[cfg(FALSE)] fn e() { let _ = x.#[attr]foo(); } +#[cfg(false)] fn e() { let _ = x.#[attr]foo(); } //~^ ERROR unexpected token: `#` //~| ERROR expected one of `.` // make sure we don't catch this bug again... -#[cfg(FALSE)] fn e() { { fn foo() { #[attr]; } } } +#[cfg(false)] fn e() { { fn foo() { #[attr]; } } } //~^ ERROR expected statement after outer attribute -#[cfg(FALSE)] fn e() { { fn foo() { #[attr] } } } +#[cfg(false)] fn e() { { fn foo() { #[attr] } } } //~^ ERROR expected statement after outer attribute diff --git a/tests/ui/parser/attribute/attr-stmt-expr-attr-bad.stderr b/tests/ui/parser/attribute/attr-stmt-expr-attr-bad.stderr index bd860841b8060..5d94a8dcbdb81 100644 --- a/tests/ui/parser/attribute/attr-stmt-expr-attr-bad.stderr +++ b/tests/ui/parser/attribute/attr-stmt-expr-attr-bad.stderr @@ -1,19 +1,19 @@ error: expected expression, found `]` --> $DIR/attr-stmt-expr-attr-bad.rs:3:40 | -LL | #[cfg(FALSE)] fn e() { let _ = [#[attr]]; } +LL | #[cfg(false)] fn e() { let _ = [#[attr]]; } | ^ expected expression error: expected one of `!`, `.`, `::`, `;`, `?`, `else`, `{`, or an operator, found `#` --> $DIR/attr-stmt-expr-attr-bad.rs:5:35 | -LL | #[cfg(FALSE)] fn e() { let _ = foo#[attr](); } +LL | #[cfg(false)] fn e() { let _ = foo#[attr](); } | ^ expected one of 8 possible tokens error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:7:36 | -LL | #[cfg(FALSE)] fn e() { let _ = foo(#![attr]); } +LL | #[cfg(false)] fn e() { let _ = foo(#![attr]); } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -22,7 +22,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = foo(#![attr]); } error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:7:36 | -LL | #[cfg(FALSE)] fn e() { let _ = foo(#![attr]); } +LL | #[cfg(false)] fn e() { let _ = foo(#![attr]); } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -32,13 +32,13 @@ LL | #[cfg(FALSE)] fn e() { let _ = foo(#![attr]); } error: expected expression, found `)` --> $DIR/attr-stmt-expr-attr-bad.rs:7:44 | -LL | #[cfg(FALSE)] fn e() { let _ = foo(#![attr]); } +LL | #[cfg(false)] fn e() { let _ = foo(#![attr]); } | ^ expected expression error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:11:38 | -LL | #[cfg(FALSE)] fn e() { let _ = x.foo(#![attr]); } +LL | #[cfg(false)] fn e() { let _ = x.foo(#![attr]); } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -47,13 +47,13 @@ LL | #[cfg(FALSE)] fn e() { let _ = x.foo(#![attr]); } error: expected expression, found `)` --> $DIR/attr-stmt-expr-attr-bad.rs:11:46 | -LL | #[cfg(FALSE)] fn e() { let _ = x.foo(#![attr]); } +LL | #[cfg(false)] fn e() { let _ = x.foo(#![attr]); } | ^ expected expression error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:14:36 | -LL | #[cfg(FALSE)] fn e() { let _ = 0 + #![attr] 0; } +LL | #[cfg(false)] fn e() { let _ = 0 + #![attr] 0; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -62,7 +62,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = 0 + #![attr] 0; } error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:16:33 | -LL | #[cfg(FALSE)] fn e() { let _ = !#![attr] 0; } +LL | #[cfg(false)] fn e() { let _ = !#![attr] 0; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -71,7 +71,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = !#![attr] 0; } error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:18:33 | -LL | #[cfg(FALSE)] fn e() { let _ = -#![attr] 0; } +LL | #[cfg(false)] fn e() { let _ = -#![attr] 0; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -80,13 +80,13 @@ LL | #[cfg(FALSE)] fn e() { let _ = -#![attr] 0; } error: expected one of `!`, `.`, `::`, `;`, `?`, `else`, `{`, or an operator, found `#` --> $DIR/attr-stmt-expr-attr-bad.rs:20:34 | -LL | #[cfg(FALSE)] fn e() { let _ = x #![attr] as Y; } +LL | #[cfg(false)] fn e() { let _ = x #![attr] as Y; } | ^ expected one of 8 possible tokens error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:22:35 | -LL | #[cfg(FALSE)] fn e() { let _ = || #![attr] foo; } +LL | #[cfg(false)] fn e() { let _ = || #![attr] foo; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -95,7 +95,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = || #![attr] foo; } error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:24:40 | -LL | #[cfg(FALSE)] fn e() { let _ = move || #![attr] foo; } +LL | #[cfg(false)] fn e() { let _ = move || #![attr] foo; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -104,7 +104,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = move || #![attr] foo; } error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:26:35 | -LL | #[cfg(FALSE)] fn e() { let _ = || #![attr] {foo}; } +LL | #[cfg(false)] fn e() { let _ = || #![attr] {foo}; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -113,7 +113,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = || #![attr] {foo}; } error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:28:40 | -LL | #[cfg(FALSE)] fn e() { let _ = move || #![attr] {foo}; } +LL | #[cfg(false)] fn e() { let _ = move || #![attr] {foo}; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -122,19 +122,19 @@ LL | #[cfg(FALSE)] fn e() { let _ = move || #![attr] {foo}; } error: attributes are not allowed on range expressions starting with `..` --> $DIR/attr-stmt-expr-attr-bad.rs:30:40 | -LL | #[cfg(FALSE)] fn e() { let _ = #[attr] ..#[attr] 0; } +LL | #[cfg(false)] fn e() { let _ = #[attr] ..#[attr] 0; } | ^^ error: attributes are not allowed on range expressions starting with `..` --> $DIR/attr-stmt-expr-attr-bad.rs:32:40 | -LL | #[cfg(FALSE)] fn e() { let _ = #[attr] ..; } +LL | #[cfg(false)] fn e() { let _ = #[attr] ..; } | ^^ error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:34:41 | -LL | #[cfg(FALSE)] fn e() { let _ = #[attr] &#![attr] 0; } +LL | #[cfg(false)] fn e() { let _ = #[attr] &#![attr] 0; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -143,7 +143,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = #[attr] &#![attr] 0; } error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:36:45 | -LL | #[cfg(FALSE)] fn e() { let _ = #[attr] &mut #![attr] 0; } +LL | #[cfg(false)] fn e() { let _ = #[attr] &mut #![attr] 0; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -152,21 +152,21 @@ LL | #[cfg(FALSE)] fn e() { let _ = #[attr] &mut #![attr] 0; } error: outer attributes are not allowed on `if` and `else` branches --> $DIR/attr-stmt-expr-attr-bad.rs:38:37 | -LL | #[cfg(FALSE)] fn e() { let _ = if 0 #[attr] {}; } +LL | #[cfg(false)] fn e() { let _ = if 0 #[attr] {}; } | -- ^^^^^^^ -- the attributes are attached to this branch | | | the branch belongs to this `if` | help: remove the attributes | -LL - #[cfg(FALSE)] fn e() { let _ = if 0 #[attr] {}; } -LL + #[cfg(FALSE)] fn e() { let _ = if 0 {}; } +LL - #[cfg(false)] fn e() { let _ = if 0 #[attr] {}; } +LL + #[cfg(false)] fn e() { let _ = if 0 {}; } | error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:40:38 | -LL | #[cfg(FALSE)] fn e() { let _ = if 0 {#![attr]}; } +LL | #[cfg(false)] fn e() { let _ = if 0 {#![attr]}; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -175,27 +175,27 @@ LL | #[cfg(FALSE)] fn e() { let _ = if 0 {#![attr]}; } error: expected one of `.`, `;`, `?`, `else`, or an operator, found `#` --> $DIR/attr-stmt-expr-attr-bad.rs:42:40 | -LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} #[attr] else {}; } +LL | #[cfg(false)] fn e() { let _ = if 0 {} #[attr] else {}; } | ^ expected one of `.`, `;`, `?`, `else`, or an operator error: outer attributes are not allowed on `if` and `else` branches --> $DIR/attr-stmt-expr-attr-bad.rs:44:45 | -LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else #[attr] {}; } +LL | #[cfg(false)] fn e() { let _ = if 0 {} else #[attr] {}; } | ---- ^^^^^^^ -- the attributes are attached to this branch | | | the branch belongs to this `else` | help: remove the attributes | -LL - #[cfg(FALSE)] fn e() { let _ = if 0 {} else #[attr] {}; } -LL + #[cfg(FALSE)] fn e() { let _ = if 0 {} else {}; } +LL - #[cfg(false)] fn e() { let _ = if 0 {} else #[attr] {}; } +LL + #[cfg(false)] fn e() { let _ = if 0 {} else {}; } | error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:46:46 | -LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else {#![attr]}; } +LL | #[cfg(false)] fn e() { let _ = if 0 {} else {#![attr]}; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -204,35 +204,35 @@ LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else {#![attr]}; } error: outer attributes are not allowed on `if` and `else` branches --> $DIR/attr-stmt-expr-attr-bad.rs:48:45 | -LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else #[attr] if 0 {}; } +LL | #[cfg(false)] fn e() { let _ = if 0 {} else #[attr] if 0 {}; } | ---- ^^^^^^^ ------- the attributes are attached to this branch | | | the branch belongs to this `else` | help: remove the attributes | -LL - #[cfg(FALSE)] fn e() { let _ = if 0 {} else #[attr] if 0 {}; } -LL + #[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 {}; } +LL - #[cfg(false)] fn e() { let _ = if 0 {} else #[attr] if 0 {}; } +LL + #[cfg(false)] fn e() { let _ = if 0 {} else if 0 {}; } | error: outer attributes are not allowed on `if` and `else` branches --> $DIR/attr-stmt-expr-attr-bad.rs:50:50 | -LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 #[attr] {}; } +LL | #[cfg(false)] fn e() { let _ = if 0 {} else if 0 #[attr] {}; } | -- ^^^^^^^ -- the attributes are attached to this branch | | | the branch belongs to this `if` | help: remove the attributes | -LL - #[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 #[attr] {}; } -LL + #[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 {}; } +LL - #[cfg(false)] fn e() { let _ = if 0 {} else if 0 #[attr] {}; } +LL + #[cfg(false)] fn e() { let _ = if 0 {} else if 0 {}; } | error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:52:51 | -LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 {#![attr]}; } +LL | #[cfg(false)] fn e() { let _ = if 0 {} else if 0 {#![attr]}; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -241,21 +241,21 @@ LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 {#![attr]}; } error: outer attributes are not allowed on `if` and `else` branches --> $DIR/attr-stmt-expr-attr-bad.rs:54:45 | -LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 #[attr] {}; } +LL | #[cfg(false)] fn e() { let _ = if let _ = 0 #[attr] {}; } | -- ^^^^^^^ -- the attributes are attached to this branch | | | the branch belongs to this `if` | help: remove the attributes | -LL - #[cfg(FALSE)] fn e() { let _ = if let _ = 0 #[attr] {}; } -LL + #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {}; } +LL - #[cfg(false)] fn e() { let _ = if let _ = 0 #[attr] {}; } +LL + #[cfg(false)] fn e() { let _ = if let _ = 0 {}; } | error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:56:46 | -LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {#![attr]}; } +LL | #[cfg(false)] fn e() { let _ = if let _ = 0 {#![attr]}; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -264,27 +264,27 @@ LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {#![attr]}; } error: expected one of `.`, `;`, `?`, `else`, or an operator, found `#` --> $DIR/attr-stmt-expr-attr-bad.rs:58:48 | -LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} #[attr] else {}; } +LL | #[cfg(false)] fn e() { let _ = if let _ = 0 {} #[attr] else {}; } | ^ expected one of `.`, `;`, `?`, `else`, or an operator error: outer attributes are not allowed on `if` and `else` branches --> $DIR/attr-stmt-expr-attr-bad.rs:60:53 | -LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else #[attr] {}; } +LL | #[cfg(false)] fn e() { let _ = if let _ = 0 {} else #[attr] {}; } | ---- ^^^^^^^ -- the attributes are attached to this branch | | | the branch belongs to this `else` | help: remove the attributes | -LL - #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else #[attr] {}; } -LL + #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else {}; } +LL - #[cfg(false)] fn e() { let _ = if let _ = 0 {} else #[attr] {}; } +LL + #[cfg(false)] fn e() { let _ = if let _ = 0 {} else {}; } | error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:62:54 | -LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else {#![attr]}; } +LL | #[cfg(false)] fn e() { let _ = if let _ = 0 {} else {#![attr]}; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -293,35 +293,35 @@ LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else {#![attr]}; } error: outer attributes are not allowed on `if` and `else` branches --> $DIR/attr-stmt-expr-attr-bad.rs:64:53 | -LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else #[attr] if let _ = 0 {}; } +LL | #[cfg(false)] fn e() { let _ = if let _ = 0 {} else #[attr] if let _ = 0 {}; } | ---- ^^^^^^^ --------------- the attributes are attached to this branch | | | the branch belongs to this `else` | help: remove the attributes | -LL - #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else #[attr] if let _ = 0 {}; } -LL + #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 {}; } +LL - #[cfg(false)] fn e() { let _ = if let _ = 0 {} else #[attr] if let _ = 0 {}; } +LL + #[cfg(false)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 {}; } | error: outer attributes are not allowed on `if` and `else` branches --> $DIR/attr-stmt-expr-attr-bad.rs:66:66 | -LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 #[attr] {}; } +LL | #[cfg(false)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 #[attr] {}; } | -- ^^^^^^^ -- the attributes are attached to this branch | | | the branch belongs to this `if` | help: remove the attributes | -LL - #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 #[attr] {}; } -LL + #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 {}; } +LL - #[cfg(false)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 #[attr] {}; } +LL + #[cfg(false)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 {}; } | error: an inner attribute is not permitted in this context --> $DIR/attr-stmt-expr-attr-bad.rs:68:67 | -LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 {#![attr]}; } +LL | #[cfg(false)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 {#![attr]}; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files @@ -330,7 +330,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 {#![attr]} error: an inner attribute is not permitted following an outer attribute --> $DIR/attr-stmt-expr-attr-bad.rs:71:32 | -LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] let _ = 0; } +LL | #[cfg(false)] fn s() { #[attr] #![attr] let _ = 0; } | ------- ^^^^^^^^ not permitted following an outer attribute | | | previous outer attribute @@ -341,7 +341,7 @@ LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] let _ = 0; } error: an inner attribute is not permitted following an outer attribute --> $DIR/attr-stmt-expr-attr-bad.rs:73:32 | -LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] 0; } +LL | #[cfg(false)] fn s() { #[attr] #![attr] 0; } | ------- ^^^^^^^^ not permitted following an outer attribute | | | previous outer attribute @@ -352,7 +352,7 @@ LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] 0; } error: an inner attribute is not permitted following an outer attribute --> $DIR/attr-stmt-expr-attr-bad.rs:75:32 | -LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] foo!(); } +LL | #[cfg(false)] fn s() { #[attr] #![attr] foo!(); } | ------- ^^^^^^^^ ------- the inner attribute doesn't annotate this item macro invocation | | | | | not permitted following an outer attribute @@ -363,7 +363,7 @@ LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] foo!(); } error: an inner attribute is not permitted following an outer attribute --> $DIR/attr-stmt-expr-attr-bad.rs:77:32 | -LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] foo![]; } +LL | #[cfg(false)] fn s() { #[attr] #![attr] foo![]; } | ------- ^^^^^^^^ ------- the inner attribute doesn't annotate this item macro invocation | | | | | not permitted following an outer attribute @@ -374,7 +374,7 @@ LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] foo![]; } error: an inner attribute is not permitted following an outer attribute --> $DIR/attr-stmt-expr-attr-bad.rs:79:32 | -LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] foo!{}; } +LL | #[cfg(false)] fn s() { #[attr] #![attr] foo!{}; } | ------- ^^^^^^^^ ------ the inner attribute doesn't annotate this item macro invocation | | | | | not permitted following an outer attribute @@ -385,100 +385,100 @@ LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] foo!{}; } error[E0586]: inclusive range with no end --> $DIR/attr-stmt-expr-attr-bad.rs:85:35 | -LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] 10 => () } } +LL | #[cfg(false)] fn e() { match 0 { 0..=#[attr] 10 => () } } | ^^^ | = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) help: use `..` instead | -LL - #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] 10 => () } } -LL + #[cfg(FALSE)] fn e() { match 0 { 0..#[attr] 10 => () } } +LL - #[cfg(false)] fn e() { match 0 { 0..=#[attr] 10 => () } } +LL + #[cfg(false)] fn e() { match 0 { 0..#[attr] 10 => () } } | error: expected one of `=>`, `if`, or `|`, found `#` --> $DIR/attr-stmt-expr-attr-bad.rs:85:38 | -LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] 10 => () } } +LL | #[cfg(false)] fn e() { match 0 { 0..=#[attr] 10 => () } } | ^ expected one of `=>`, `if`, or `|` error[E0586]: inclusive range with no end --> $DIR/attr-stmt-expr-attr-bad.rs:88:35 | -LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] -10 => () } } +LL | #[cfg(false)] fn e() { match 0 { 0..=#[attr] -10 => () } } | ^^^ | = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) help: use `..` instead | -LL - #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] -10 => () } } -LL + #[cfg(FALSE)] fn e() { match 0 { 0..#[attr] -10 => () } } +LL - #[cfg(false)] fn e() { match 0 { 0..=#[attr] -10 => () } } +LL + #[cfg(false)] fn e() { match 0 { 0..#[attr] -10 => () } } | error: expected one of `=>`, `if`, or `|`, found `#` --> $DIR/attr-stmt-expr-attr-bad.rs:88:38 | -LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] -10 => () } } +LL | #[cfg(false)] fn e() { match 0 { 0..=#[attr] -10 => () } } | ^ expected one of `=>`, `if`, or `|` error: unexpected token: `#` --> $DIR/attr-stmt-expr-attr-bad.rs:91:39 | -LL | #[cfg(FALSE)] fn e() { match 0 { 0..=-#[attr] 10 => () } } +LL | #[cfg(false)] fn e() { match 0 { 0..=-#[attr] 10 => () } } | ^ error[E0586]: inclusive range with no end --> $DIR/attr-stmt-expr-attr-bad.rs:93:35 | -LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] FOO => () } } +LL | #[cfg(false)] fn e() { match 0 { 0..=#[attr] FOO => () } } | ^^^ | = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) help: use `..` instead | -LL - #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] FOO => () } } -LL + #[cfg(FALSE)] fn e() { match 0 { 0..#[attr] FOO => () } } +LL - #[cfg(false)] fn e() { match 0 { 0..=#[attr] FOO => () } } +LL + #[cfg(false)] fn e() { match 0 { 0..#[attr] FOO => () } } | error: expected one of `=>`, `if`, or `|`, found `#` --> $DIR/attr-stmt-expr-attr-bad.rs:93:38 | -LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] FOO => () } } +LL | #[cfg(false)] fn e() { match 0 { 0..=#[attr] FOO => () } } | ^ expected one of `=>`, `if`, or `|` error: unexpected token: `#` --> $DIR/attr-stmt-expr-attr-bad.rs:97:34 | -LL | #[cfg(FALSE)] fn e() { let _ = x.#![attr]foo(); } +LL | #[cfg(false)] fn e() { let _ = x.#![attr]foo(); } | ^ error: expected one of `.`, `;`, `?`, `else`, or an operator, found `#` --> $DIR/attr-stmt-expr-attr-bad.rs:97:34 | -LL | #[cfg(FALSE)] fn e() { let _ = x.#![attr]foo(); } +LL | #[cfg(false)] fn e() { let _ = x.#![attr]foo(); } | ^ expected one of `.`, `;`, `?`, `else`, or an operator error: unexpected token: `#` --> $DIR/attr-stmt-expr-attr-bad.rs:100:34 | -LL | #[cfg(FALSE)] fn e() { let _ = x.#[attr]foo(); } +LL | #[cfg(false)] fn e() { let _ = x.#[attr]foo(); } | ^ error: expected one of `.`, `;`, `?`, `else`, or an operator, found `#` --> $DIR/attr-stmt-expr-attr-bad.rs:100:34 | -LL | #[cfg(FALSE)] fn e() { let _ = x.#[attr]foo(); } +LL | #[cfg(false)] fn e() { let _ = x.#[attr]foo(); } | ^ expected one of `.`, `;`, `?`, `else`, or an operator error: expected statement after outer attribute --> $DIR/attr-stmt-expr-attr-bad.rs:105:37 | -LL | #[cfg(FALSE)] fn e() { { fn foo() { #[attr]; } } } +LL | #[cfg(false)] fn e() { { fn foo() { #[attr]; } } } | ^^^^^^^ error: expected statement after outer attribute --> $DIR/attr-stmt-expr-attr-bad.rs:107:37 | -LL | #[cfg(FALSE)] fn e() { { fn foo() { #[attr] } } } +LL | #[cfg(false)] fn e() { { fn foo() { #[attr] } } } | ^^^^^^^ error: aborting due to 53 previous errors diff --git a/tests/ui/parser/attribute/multiple-tail-expr-behind-cfg.rs b/tests/ui/parser/attribute/multiple-tail-expr-behind-cfg.rs index 33671df949280..371f19d487268 100644 --- a/tests/ui/parser/attribute/multiple-tail-expr-behind-cfg.rs +++ b/tests/ui/parser/attribute/multiple-tail-expr-behind-cfg.rs @@ -1,7 +1,7 @@ #![feature(stmt_expr_attributes)] fn foo() -> String { - #[cfg(FALSE)] + #[cfg(false)] [1, 2, 3].iter().map(|c| c.to_string()).collect::() //~ ERROR expected `;`, found `#` #[cfg(not(FALSE))] String::new() diff --git a/tests/ui/parser/attribute/multiple-tail-expr-behind-cfg.stderr b/tests/ui/parser/attribute/multiple-tail-expr-behind-cfg.stderr index 6266718162f8e..3a97a14b3c301 100644 --- a/tests/ui/parser/attribute/multiple-tail-expr-behind-cfg.stderr +++ b/tests/ui/parser/attribute/multiple-tail-expr-behind-cfg.stderr @@ -1,7 +1,7 @@ error: expected `;`, found `#` --> $DIR/multiple-tail-expr-behind-cfg.rs:5:64 | -LL | #[cfg(FALSE)] +LL | #[cfg(false)] | ------------- only `;` terminated statements or tail expressions are allowed after this attribute LL | [1, 2, 3].iter().map(|c| c.to_string()).collect::() | ^ expected `;` here @@ -18,7 +18,7 @@ LL | { [1, 2, 3].iter().map(|c| c.to_string()).collect::() } | + + help: it seems like you are trying to provide different expressions depending on `cfg`, consider using `if cfg!(..)` | -LL ~ if cfg!(FALSE) { +LL ~ if cfg!(false) { LL ~ [1, 2, 3].iter().map(|c| c.to_string()).collect::() LL ~ } else if cfg!(not(FALSE)) { LL ~ String::new() diff --git a/tests/ui/parser/attribute/properly-recover-from-trailing-outer-attribute-in-body-2.rs b/tests/ui/parser/attribute/properly-recover-from-trailing-outer-attribute-in-body-2.rs index e2a62922bcc5d..1cd3f13d7b67a 100644 --- a/tests/ui/parser/attribute/properly-recover-from-trailing-outer-attribute-in-body-2.rs +++ b/tests/ui/parser/attribute/properly-recover-from-trailing-outer-attribute-in-body-2.rs @@ -5,7 +5,7 @@ macro_rules! the_macro { #[cfg()] $foo //~ ERROR expected `;`, found `#` - #[cfg(FALSE)] + #[cfg(false)] $bar }; } diff --git a/tests/ui/parser/attribute/properly-recover-from-trailing-outer-attribute-in-body-2.stderr b/tests/ui/parser/attribute/properly-recover-from-trailing-outer-attribute-in-body-2.stderr index fa4409f73fa50..41e7b5ab759dd 100644 --- a/tests/ui/parser/attribute/properly-recover-from-trailing-outer-attribute-in-body-2.stderr +++ b/tests/ui/parser/attribute/properly-recover-from-trailing-outer-attribute-in-body-2.stderr @@ -6,7 +6,7 @@ LL | #[cfg()] LL | $foo | ^ expected `;` here LL | -LL | #[cfg(FALSE)] +LL | #[cfg(false)] | - unexpected token ... LL | the_macro!( (); (); ); diff --git a/tests/ui/parser/constraints-before-generic-args-syntactic-pass.rs b/tests/ui/parser/constraints-before-generic-args-syntactic-pass.rs index ed3ffed2f8026..acc58a47fbcf4 100644 --- a/tests/ui/parser/constraints-before-generic-args-syntactic-pass.rs +++ b/tests/ui/parser/constraints-before-generic-args-syntactic-pass.rs @@ -1,6 +1,6 @@ //@ check-pass -#[cfg(FALSE)] +#[cfg(false)] fn syntax() { foo::(); foo::(); diff --git a/tests/ui/parser/default-on-wrong-item-kind.rs b/tests/ui/parser/default-on-wrong-item-kind.rs index 98a95cfa35a9e..da990a4b42123 100644 --- a/tests/ui/parser/default-on-wrong-item-kind.rs +++ b/tests/ui/parser/default-on-wrong-item-kind.rs @@ -4,7 +4,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] mod free_items { default extern crate foo; //~ ERROR an extern crate cannot be `default` default use foo; //~ ERROR a `use` import cannot be `default` @@ -28,7 +28,7 @@ mod free_items { default macro_rules! foo {} //~ ERROR a macro definition cannot be `default` } -#[cfg(FALSE)] +#[cfg(false)] extern "C" { default extern crate foo; //~ ERROR an extern crate cannot be `default` //~^ ERROR extern crate is not supported in `extern` blocks @@ -65,7 +65,7 @@ extern "C" { //~^ ERROR macro definition is not supported in `extern` blocks } -#[cfg(FALSE)] +#[cfg(false)] impl S { default extern crate foo; //~ ERROR an extern crate cannot be `default` //~^ ERROR extern crate is not supported in `trait`s or `impl`s @@ -102,7 +102,7 @@ impl S { //~^ ERROR macro definition is not supported in `trait`s or `impl`s } -#[cfg(FALSE)] +#[cfg(false)] trait T { default extern crate foo; //~ ERROR an extern crate cannot be `default` //~^ ERROR extern crate is not supported in `trait`s or `impl`s diff --git a/tests/ui/parser/extern-abi-syntactic.rs b/tests/ui/parser/extern-abi-syntactic.rs index d3e2ba0e2d3f6..28565a3f4befd 100644 --- a/tests/ui/parser/extern-abi-syntactic.rs +++ b/tests/ui/parser/extern-abi-syntactic.rs @@ -5,13 +5,13 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] extern "some_abi_that_we_are_sure_does_not_exist_semantically" fn foo() {} -#[cfg(FALSE)] +#[cfg(false)] extern "some_abi_that_we_are_sure_does_not_exist_semantically" { fn foo(); } -#[cfg(FALSE)] +#[cfg(false)] type T = extern "some_abi_that_we_are_sure_does_not_exist_semantically" fn(); diff --git a/tests/ui/parser/extern-crate-async.rs b/tests/ui/parser/extern-crate-async.rs index 7c7769075b658..529e0f1ab5cb8 100644 --- a/tests/ui/parser/extern-crate-async.rs +++ b/tests/ui/parser/extern-crate-async.rs @@ -5,8 +5,8 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] extern crate async; -#[cfg(FALSE)] +#[cfg(false)] extern crate async as something_else; diff --git a/tests/ui/parser/fn-body-optional-syntactic-pass.rs b/tests/ui/parser/fn-body-optional-syntactic-pass.rs index 140471dfc774b..762247e63e99c 100644 --- a/tests/ui/parser/fn-body-optional-syntactic-pass.rs +++ b/tests/ui/parser/fn-body-optional-syntactic-pass.rs @@ -4,7 +4,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn syntax() { fn f(); fn f() {} diff --git a/tests/ui/parser/fn-header-syntactic-pass.rs b/tests/ui/parser/fn-header-syntactic-pass.rs index 065ded31b0730..1e15886e5645f 100644 --- a/tests/ui/parser/fn-header-syntactic-pass.rs +++ b/tests/ui/parser/fn-header-syntactic-pass.rs @@ -5,7 +5,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn syntax() { async fn f(); unsafe fn f(); diff --git a/tests/ui/parser/foreign-const-syntactic-fail.rs b/tests/ui/parser/foreign-const-syntactic-fail.rs index a6e77f846638e..fc3cd0b3430df 100644 --- a/tests/ui/parser/foreign-const-syntactic-fail.rs +++ b/tests/ui/parser/foreign-const-syntactic-fail.rs @@ -2,7 +2,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] extern "C" { const A: isize; //~ ERROR extern items cannot be `const` const B: isize = 42; //~ ERROR extern items cannot be `const` diff --git a/tests/ui/parser/foreign-static-syntactic-pass.rs b/tests/ui/parser/foreign-static-syntactic-pass.rs index a76b9bab49112..d7c21c672ab6c 100644 --- a/tests/ui/parser/foreign-static-syntactic-pass.rs +++ b/tests/ui/parser/foreign-static-syntactic-pass.rs @@ -4,7 +4,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] extern "C" { static X: u8; static mut Y: u8; diff --git a/tests/ui/parser/foreign-ty-syntactic-pass.rs b/tests/ui/parser/foreign-ty-syntactic-pass.rs index 50bb68cd83be2..337276852010a 100644 --- a/tests/ui/parser/foreign-ty-syntactic-pass.rs +++ b/tests/ui/parser/foreign-ty-syntactic-pass.rs @@ -2,7 +2,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] extern "C" { type A: Ord; type A<'a> where 'a: 'static; diff --git a/tests/ui/parser/impl-item-const-pass.rs b/tests/ui/parser/impl-item-const-pass.rs index 8ebdf633b5b97..6ca4cd9cd9306 100644 --- a/tests/ui/parser/impl-item-const-pass.rs +++ b/tests/ui/parser/impl-item-const-pass.rs @@ -2,7 +2,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] impl X { const Y: u8; } diff --git a/tests/ui/parser/impl-item-fn-no-body-pass.rs b/tests/ui/parser/impl-item-fn-no-body-pass.rs index 5a593fe1d124d..b8269fc42708f 100644 --- a/tests/ui/parser/impl-item-fn-no-body-pass.rs +++ b/tests/ui/parser/impl-item-fn-no-body-pass.rs @@ -2,7 +2,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] impl X { fn f(); } diff --git a/tests/ui/parser/impl-item-type-no-body-pass.rs b/tests/ui/parser/impl-item-type-no-body-pass.rs index 039825bcc538c..979b5f7659600 100644 --- a/tests/ui/parser/impl-item-type-no-body-pass.rs +++ b/tests/ui/parser/impl-item-type-no-body-pass.rs @@ -2,7 +2,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] impl X { type Y; type Z: Ord; diff --git a/tests/ui/parser/issues/issue-65041-empty-vis-matcher-in-enum.rs b/tests/ui/parser/issues/issue-65041-empty-vis-matcher-in-enum.rs index 4fa803bb318e4..13bb9351bb692 100644 --- a/tests/ui/parser/issues/issue-65041-empty-vis-matcher-in-enum.rs +++ b/tests/ui/parser/issues/issue-65041-empty-vis-matcher-in-enum.rs @@ -20,7 +20,7 @@ macro_rules! mac_variant { mac_variant!(MARKER); // We also accept visibilities on variants syntactically but not semantically. -#[cfg(FALSE)] +#[cfg(false)] enum E { pub U, pub(crate) T(u8), diff --git a/tests/ui/parser/issues/issue-65041-empty-vis-matcher-in-trait.rs b/tests/ui/parser/issues/issue-65041-empty-vis-matcher-in-trait.rs index cd474db63b71a..55e69cd14d6b5 100644 --- a/tests/ui/parser/issues/issue-65041-empty-vis-matcher-in-trait.rs +++ b/tests/ui/parser/issues/issue-65041-empty-vis-matcher-in-trait.rs @@ -20,7 +20,7 @@ trait Alpha { } // We also accept visibilities on items in traits syntactically but not semantically. -#[cfg(FALSE)] +#[cfg(false)] trait Foo { pub fn bar(); pub(crate) type baz; diff --git a/tests/ui/parser/item-free-const-no-body-syntactic-pass.rs b/tests/ui/parser/item-free-const-no-body-syntactic-pass.rs index 4edbee54de673..0b9229860bf86 100644 --- a/tests/ui/parser/item-free-const-no-body-syntactic-pass.rs +++ b/tests/ui/parser/item-free-const-no-body-syntactic-pass.rs @@ -4,5 +4,5 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] const X: u8; diff --git a/tests/ui/parser/item-free-static-no-body-syntactic-pass.rs b/tests/ui/parser/item-free-static-no-body-syntactic-pass.rs index df5192645e11e..8dae4338ee7ed 100644 --- a/tests/ui/parser/item-free-static-no-body-syntactic-pass.rs +++ b/tests/ui/parser/item-free-static-no-body-syntactic-pass.rs @@ -4,5 +4,5 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] static X: u8; diff --git a/tests/ui/parser/item-free-type-bounds-syntactic-pass.rs b/tests/ui/parser/item-free-type-bounds-syntactic-pass.rs index 80de3cfc668dc..8603dc3eaf864 100644 --- a/tests/ui/parser/item-free-type-bounds-syntactic-pass.rs +++ b/tests/ui/parser/item-free-type-bounds-syntactic-pass.rs @@ -2,7 +2,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn syntax() { type A: Ord; type B: Ord = u8; diff --git a/tests/ui/parser/recover/recover-assoc-const-constraint.rs b/tests/ui/parser/recover/recover-assoc-const-constraint.rs index 1453e6cb5cd7c..d938b4ccaca7e 100644 --- a/tests/ui/parser/recover/recover-assoc-const-constraint.rs +++ b/tests/ui/parser/recover/recover-assoc-const-constraint.rs @@ -1,4 +1,4 @@ -#[cfg(FALSE)] +#[cfg(false)] fn syntax() { bar::(); //~^ ERROR associated const equality is incomplete diff --git a/tests/ui/parser/recover/recover-assoc-eq-missing-term.rs b/tests/ui/parser/recover/recover-assoc-eq-missing-term.rs index 4b42c44dc64e5..73b4e22cab6fd 100644 --- a/tests/ui/parser/recover/recover-assoc-eq-missing-term.rs +++ b/tests/ui/parser/recover/recover-assoc-eq-missing-term.rs @@ -1,4 +1,4 @@ -#[cfg(FALSE)] +#[cfg(false)] fn syntax() { bar::(); //~ ERROR missing type to the right of `=` } diff --git a/tests/ui/parser/recover/recover-assoc-lifetime-constraint.rs b/tests/ui/parser/recover/recover-assoc-lifetime-constraint.rs index cb65f80b08909..30bac49e63a5f 100644 --- a/tests/ui/parser/recover/recover-assoc-lifetime-constraint.rs +++ b/tests/ui/parser/recover/recover-assoc-lifetime-constraint.rs @@ -1,4 +1,4 @@ -#[cfg(FALSE)] +#[cfg(false)] fn syntax() { bar::(); //~ ERROR lifetimes are not permitted in this context } diff --git a/tests/ui/parser/self-param-syntactic-pass.rs b/tests/ui/parser/self-param-syntactic-pass.rs index c7fdc5297164a..331e652f9c576 100644 --- a/tests/ui/parser/self-param-syntactic-pass.rs +++ b/tests/ui/parser/self-param-syntactic-pass.rs @@ -5,7 +5,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn free() { fn f(self) {} fn f(mut self) {} @@ -17,7 +17,7 @@ fn free() { fn f(mut self: u8) {} } -#[cfg(FALSE)] +#[cfg(false)] extern "C" { fn f(self); fn f(mut self); @@ -29,7 +29,7 @@ extern "C" { fn f(mut self: u8); } -#[cfg(FALSE)] +#[cfg(false)] trait X { fn f(self) {} fn f(mut self) {} @@ -41,7 +41,7 @@ trait X { fn f(mut self: u8) {} } -#[cfg(FALSE)] +#[cfg(false)] impl X for Y { fn f(self) {} fn f(mut self) {} @@ -53,7 +53,7 @@ impl X for Y { fn f(mut self: u8) {} } -#[cfg(FALSE)] +#[cfg(false)] impl X for Y { type X = fn(self); type X = fn(mut self); diff --git a/tests/ui/parser/stripped-nested-outline-mod-pass.rs b/tests/ui/parser/stripped-nested-outline-mod-pass.rs index 8909d8ae0eb63..166a60f257a33 100644 --- a/tests/ui/parser/stripped-nested-outline-mod-pass.rs +++ b/tests/ui/parser/stripped-nested-outline-mod-pass.rs @@ -5,7 +5,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] mod foo { mod bar { mod baz; // This was an error before. diff --git a/tests/ui/parser/trait-item-with-defaultness-pass.rs b/tests/ui/parser/trait-item-with-defaultness-pass.rs index c636342f6ca42..164d0b13b539c 100644 --- a/tests/ui/parser/trait-item-with-defaultness-pass.rs +++ b/tests/ui/parser/trait-item-with-defaultness-pass.rs @@ -2,7 +2,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] trait X { default const A: u8; default const B: u8 = 0; diff --git a/tests/ui/parser/variadic-ffi-syntactic-pass.rs b/tests/ui/parser/variadic-ffi-syntactic-pass.rs index da81f1362160a..ebe0b6c2dd258 100644 --- a/tests/ui/parser/variadic-ffi-syntactic-pass.rs +++ b/tests/ui/parser/variadic-ffi-syntactic-pass.rs @@ -2,31 +2,31 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn f1_1(x: isize, ...) {} -#[cfg(FALSE)] +#[cfg(false)] fn f1_2(...) {} -#[cfg(FALSE)] +#[cfg(false)] extern "C" fn f2_1(x: isize, ...) {} -#[cfg(FALSE)] +#[cfg(false)] extern "C" fn f2_2(...) {} -#[cfg(FALSE)] +#[cfg(false)] extern "C" fn f2_3(..., x: isize) {} -#[cfg(FALSE)] +#[cfg(false)] extern fn f3_1(x: isize, ...) {} -#[cfg(FALSE)] +#[cfg(false)] extern fn f3_2(...) {} -#[cfg(FALSE)] +#[cfg(false)] extern fn f3_3(..., x: isize) {} -#[cfg(FALSE)] +#[cfg(false)] extern { fn e_f1(...); fn e_f2(..., x: isize); @@ -34,7 +34,7 @@ extern { struct X; -#[cfg(FALSE)] +#[cfg(false)] impl X { fn i_f1(x: isize, ...) {} fn i_f2(...) {} @@ -42,7 +42,7 @@ impl X { fn i_f4(..., x: isize, ...) {} } -#[cfg(FALSE)] +#[cfg(false)] trait T { fn t_f1(x: isize, ...) {} fn t_f2(x: isize, ...); diff --git a/tests/ui/pattern/bindings-after-at/nested-type-ascription-syntactically-invalid.rs b/tests/ui/pattern/bindings-after-at/nested-type-ascription-syntactically-invalid.rs index 01a978d55574b..9582d2729a895 100644 --- a/tests/ui/pattern/bindings-after-at/nested-type-ascription-syntactically-invalid.rs +++ b/tests/ui/pattern/bindings-after-at/nested-type-ascription-syntactically-invalid.rs @@ -13,19 +13,19 @@ fn _ok() { fn _f(_a @ _b: u8) {} // OK. } -#[cfg(FALSE)] +#[cfg(false)] fn case_1() { let a: u8 @ b = 0; //~^ ERROR expected one of `!` } -#[cfg(FALSE)] +#[cfg(false)] fn case_2() { let a @ (b: u8); //~^ ERROR expected one of `)` } -#[cfg(FALSE)] +#[cfg(false)] fn case_3() { let a: T1 @ Outer(b: T2); //~^ ERROR expected one of `!` diff --git a/tests/ui/pattern/bindings-after-at/wild-before-at-syntactically-rejected.rs b/tests/ui/pattern/bindings-after-at/wild-before-at-syntactically-rejected.rs index 50ac0ef27834e..c3994d35c421c 100644 --- a/tests/ui/pattern/bindings-after-at/wild-before-at-syntactically-rejected.rs +++ b/tests/ui/pattern/bindings-after-at/wild-before-at-syntactically-rejected.rs @@ -3,7 +3,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] fn wild_before_at_is_bad_syntax() { let _ @ a = 0; //~^ ERROR pattern on wrong side of `@` diff --git a/tests/ui/pattern/rest-pat-syntactic.rs b/tests/ui/pattern/rest-pat-syntactic.rs index 1de29e69b0543..59c687bb5a8d8 100644 --- a/tests/ui/pattern/rest-pat-syntactic.rs +++ b/tests/ui/pattern/rest-pat-syntactic.rs @@ -11,7 +11,7 @@ macro_rules! accept_pat { accept_pat!(..); -#[cfg(FALSE)] +#[cfg(false)] fn rest_patterns() { // Top level: fn foo(..: u8) {} diff --git a/tests/ui/proc-macro/attribute-after-derive.rs b/tests/ui/proc-macro/attribute-after-derive.rs index f2e2eb12a195e..382ef1f6ddfd3 100644 --- a/tests/ui/proc-macro/attribute-after-derive.rs +++ b/tests/ui/proc-macro/attribute-after-derive.rs @@ -14,14 +14,14 @@ extern crate test_macros; #[print_attr] #[derive(Print)] struct AttributeDerive { - #[cfg(FALSE)] + #[cfg(false)] field: u8, } #[derive(Print)] #[print_attr] struct DeriveAttribute { - #[cfg(FALSE)] + #[cfg(false)] field: u8, } diff --git a/tests/ui/proc-macro/attribute-after-derive.stdout b/tests/ui/proc-macro/attribute-after-derive.stdout index 6d9531df8caf2..bc0fc6dc1af14 100644 --- a/tests/ui/proc-macro/attribute-after-derive.stdout +++ b/tests/ui/proc-macro/attribute-after-derive.stdout @@ -1,5 +1,5 @@ -PRINT-ATTR INPUT (DISPLAY): #[derive(Print)] struct AttributeDerive { #[cfg(FALSE)] field: u8, } -PRINT-ATTR DEEP-RE-COLLECTED (DISPLAY): #[derive(Print)] struct AttributeDerive { #[cfg(FALSE)] field : u8, } +PRINT-ATTR INPUT (DISPLAY): #[derive(Print)] struct AttributeDerive { #[cfg(false)] field: u8, } +PRINT-ATTR DEEP-RE-COLLECTED (DISPLAY): #[derive(Print)] struct AttributeDerive { #[cfg(false)] field : u8, } PRINT-ATTR INPUT (DEBUG): TokenStream [ Punct { ch: '#', @@ -53,7 +53,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/attribute-after-derive.rs:17:11: 17:16 (#0), }, ], @@ -131,8 +131,8 @@ PRINT-DERIVE INPUT (DEBUG): TokenStream [ span: $DIR/attribute-after-derive.rs:23:24: 26:2 (#0), }, ] -PRINT-ATTR INPUT (DISPLAY): struct DeriveAttribute { #[cfg(FALSE)] field: u8, } -PRINT-ATTR DEEP-RE-COLLECTED (DISPLAY): struct DeriveAttribute { #[cfg(FALSE)] field : u8, } +PRINT-ATTR INPUT (DISPLAY): struct DeriveAttribute { #[cfg(false)] field: u8, } +PRINT-ATTR DEEP-RE-COLLECTED (DISPLAY): struct DeriveAttribute { #[cfg(false)] field : u8, } PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", @@ -161,7 +161,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/attribute-after-derive.rs:24:11: 24:16 (#0), }, ], diff --git a/tests/ui/proc-macro/cfg-eval-fail.rs b/tests/ui/proc-macro/cfg-eval-fail.rs index a259aa2e6ec0c..a94dcd2837811 100644 --- a/tests/ui/proc-macro/cfg-eval-fail.rs +++ b/tests/ui/proc-macro/cfg-eval-fail.rs @@ -2,6 +2,6 @@ #![feature(stmt_expr_attributes)] fn main() { - let _ = #[cfg_eval] #[cfg(FALSE)] 0; + let _ = #[cfg_eval] #[cfg(false)] 0; //~^ ERROR removing an expression is not supported in this position } diff --git a/tests/ui/proc-macro/cfg-eval-fail.stderr b/tests/ui/proc-macro/cfg-eval-fail.stderr index 945ad46bf33c3..7f21e4646b1cc 100644 --- a/tests/ui/proc-macro/cfg-eval-fail.stderr +++ b/tests/ui/proc-macro/cfg-eval-fail.stderr @@ -1,7 +1,7 @@ error: removing an expression is not supported in this position --> $DIR/cfg-eval-fail.rs:5:25 | -LL | let _ = #[cfg_eval] #[cfg(FALSE)] 0; +LL | let _ = #[cfg_eval] #[cfg(false)] 0; | ^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/proc-macro/cfg-eval-inner.rs b/tests/ui/proc-macro/cfg-eval-inner.rs index 7493f3ea52366..dc4efd6ba15fb 100644 --- a/tests/ui/proc-macro/cfg-eval-inner.rs +++ b/tests/ui/proc-macro/cfg-eval-inner.rs @@ -32,7 +32,7 @@ impl Foo<[u8; { #![cfg_attr(not(FALSE), rustc_dummy(evaluated_attr))] fn bar() { - #[cfg(FALSE)] let a = 1; + #[cfg(false)] let a = 1; } } diff --git a/tests/ui/proc-macro/cfg-eval.rs b/tests/ui/proc-macro/cfg-eval.rs index 1d9b4f23ea5c4..ddf3708059608 100644 --- a/tests/ui/proc-macro/cfg-eval.rs +++ b/tests/ui/proc-macro/cfg-eval.rs @@ -15,7 +15,7 @@ extern crate test_macros; #[cfg_eval] #[print_attr] struct S1 { - #[cfg(FALSE)] + #[cfg(false)] field_false: u8, #[cfg(all(/*true*/))] #[cfg_attr(FALSE, unknown_attr)] @@ -24,7 +24,7 @@ struct S1 { } #[cfg_eval] -#[cfg(FALSE)] +#[cfg(false)] struct S2 {} fn main() { @@ -33,5 +33,5 @@ fn main() { // expression. `#[cfg]` is not supported inside parenthesized expressions, so this will // produce an error when attribute collection runs. let _ = #[cfg_eval] #[print_attr] #[cfg_attr(not(FALSE), rustc_dummy)] - (#[cfg(FALSE)] 0, #[cfg(all(/*true*/))] 1,); + (#[cfg(false)] 0, #[cfg(all(/*true*/))] 1,); } diff --git a/tests/ui/proc-macro/derive-cfg-nested-tokens.rs b/tests/ui/proc-macro/derive-cfg-nested-tokens.rs index 7d4e8d8373d65..ec6aba0d1ea33 100644 --- a/tests/ui/proc-macro/derive-cfg-nested-tokens.rs +++ b/tests/ui/proc-macro/derive-cfg-nested-tokens.rs @@ -15,7 +15,7 @@ struct S { // - on eagerly configured `S` (from `impl Copy`), only 11 should be printed // - on non-configured `S` (from `struct S`), both 10 and 11 should be printed field: [u8; #[print_attr] { - #[cfg(FALSE)] { 10 } + #[cfg(false)] { 10 } #[cfg(not(FALSE))] { 11 } }], } diff --git a/tests/ui/proc-macro/derive-cfg-nested-tokens.stdout b/tests/ui/proc-macro/derive-cfg-nested-tokens.stdout index 05bf21ee8f9bf..9dbddc95902dc 100644 --- a/tests/ui/proc-macro/derive-cfg-nested-tokens.stdout +++ b/tests/ui/proc-macro/derive-cfg-nested-tokens.stdout @@ -54,7 +54,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ span: #0 bytes(452..523), }, ] -PRINT-ATTR INPUT (DISPLAY): { #[cfg(FALSE)] { 10 } #[cfg(not(FALSE))] { 11 } } +PRINT-ATTR INPUT (DISPLAY): { #[cfg(false)] { 10 } #[cfg(not(FALSE))] { 11 } } PRINT-ATTR INPUT (DEBUG): TokenStream [ Group { delimiter: Brace, @@ -75,7 +75,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: #0 bytes(468..473), }, ], diff --git a/tests/ui/proc-macro/expand-to-derive.rs b/tests/ui/proc-macro/expand-to-derive.rs index 0e38e471980bc..05c8e32624313 100644 --- a/tests/ui/proc-macro/expand-to-derive.rs +++ b/tests/ui/proc-macro/expand-to-derive.rs @@ -14,7 +14,7 @@ macro_rules! expand_to_derive { ($item:item) => { #[derive(Print)] struct Foo { - #[cfg(FALSE)] removed: bool, + #[cfg(false)] removed: bool, field: [bool; { $item 0 @@ -26,7 +26,7 @@ macro_rules! expand_to_derive { expand_to_derive! { #[cfg_attr(not(FALSE), rustc_dummy)] struct Inner { - #[cfg(FALSE)] removed_inner_field: bool, + #[cfg(false)] removed_inner_field: bool, other_inner_field: u8, } } diff --git a/tests/ui/proc-macro/issue-75930-derive-cfg.rs b/tests/ui/proc-macro/issue-75930-derive-cfg.rs index 376a8ea42783a..f0851b31e9cb8 100644 --- a/tests/ui/proc-macro/issue-75930-derive-cfg.rs +++ b/tests/ui/proc-macro/issue-75930-derive-cfg.rs @@ -31,7 +31,7 @@ extern crate test_macros; // // It is because of this code from below: // ``` -// struct Foo<#[cfg(FALSE)] A, B> +// struct Foo<#[cfg(false)] A, B> // ``` // When the token stream is formed during parsing, `<` is followed immediately // by `#`, which is punctuation, so it is marked `Joint`. But before being @@ -51,22 +51,22 @@ extern crate test_macros; #[print_attr] #[derive(Print)] #[print_helper(b)] -struct Foo<#[cfg(FALSE)] A, B> { - #[cfg(FALSE)] first: String, +struct Foo<#[cfg(false)] A, B> { + #[cfg(false)] first: String, #[cfg_attr(FALSE, deny(warnings))] second: bool, third: [u8; { - #[cfg(FALSE)] struct Bar; + #[cfg(false)] struct Bar; #[cfg(not(FALSE))] struct Inner; - #[cfg(FALSE)] let a = 25; + #[cfg(false)] let a = 25; match true { - #[cfg(FALSE)] true => {}, + #[cfg(false)] true => {}, #[cfg_attr(not(FALSE), allow(warnings))] false => {}, _ => {} }; #[print_helper(should_be_removed)] fn removed_fn() { - #![cfg(FALSE)] + #![cfg(false)] } #[print_helper(c)] #[cfg(not(FALSE))] fn kept_fn() { @@ -76,22 +76,22 @@ struct Foo<#[cfg(FALSE)] A, B> { enum TupleEnum { Foo( - #[cfg(FALSE)] u8, - #[cfg(FALSE)] bool, + #[cfg(false)] u8, + #[cfg(false)] bool, #[cfg(not(FALSE))] i32, - #[cfg(FALSE)] String, u8 + #[cfg(false)] String, u8 ) } struct TupleStruct( - #[cfg(FALSE)] String, + #[cfg(false)] String, #[cfg(not(FALSE))] i32, - #[cfg(FALSE)] bool, + #[cfg(false)] bool, u8 ); fn plain_removed_fn() { - #![cfg_attr(not(FALSE), cfg(FALSE))] + #![cfg_attr(not(FALSE), cfg(false))] } 0 diff --git a/tests/ui/proc-macro/issue-75930-derive-cfg.stdout b/tests/ui/proc-macro/issue-75930-derive-cfg.stdout index 4dcf2b717d8a8..549621fdca313 100644 --- a/tests/ui/proc-macro/issue-75930-derive-cfg.stdout +++ b/tests/ui/proc-macro/issue-75930-derive-cfg.stdout @@ -1,73 +1,73 @@ PRINT-ATTR INPUT (DISPLAY): #[print_helper(a)] #[allow(dead_code)] #[derive(Print)] #[print_helper(b)] -struct Foo<#[cfg(FALSE)] A, B> +struct Foo<#[cfg(false)] A, B> { - #[cfg(FALSE)] first: String, #[cfg_attr(FALSE, deny(warnings))] second: + #[cfg(false)] first: String, #[cfg_attr(FALSE, deny(warnings))] second: bool, third: [u8; { - #[cfg(FALSE)] struct Bar; #[cfg(not(FALSE))] struct Inner; - #[cfg(FALSE)] let a = 25; match true + #[cfg(false)] struct Bar; #[cfg(not(FALSE))] struct Inner; + #[cfg(false)] let a = 25; match true { - #[cfg(FALSE)] true => {}, #[cfg_attr(not(FALSE), allow(warnings))] + #[cfg(false)] true => {}, #[cfg_attr(not(FALSE), allow(warnings))] false => {}, _ => {} }; #[print_helper(should_be_removed)] fn removed_fn() - { #![cfg(FALSE)] } #[print_helper(c)] #[cfg(not(FALSE))] fn kept_fn() + { #![cfg(false)] } #[print_helper(c)] #[cfg(not(FALSE))] fn kept_fn() { #![cfg(not(FALSE))] let my_val = true; } enum TupleEnum { - Foo(#[cfg(FALSE)] u8, #[cfg(FALSE)] bool, #[cfg(not(FALSE))] i32, - #[cfg(FALSE)] String, u8) + Foo(#[cfg(false)] u8, #[cfg(false)] bool, #[cfg(not(FALSE))] i32, + #[cfg(false)] String, u8) } struct - TupleStruct(#[cfg(FALSE)] String, #[cfg(not(FALSE))] i32, - #[cfg(FALSE)] bool, u8); fn plain_removed_fn() - { #![cfg_attr(not(FALSE), cfg(FALSE))] } 0 + TupleStruct(#[cfg(false)] String, #[cfg(not(FALSE))] i32, + #[cfg(false)] bool, u8); fn plain_removed_fn() + { #![cfg_attr(not(FALSE), cfg(false))] } 0 }], #[print_helper(d)] fourth: B } PRINT-ATTR RE-COLLECTED (DISPLAY): #[print_helper(a)] #[allow(dead_code)] #[derive(Print)] #[print_helper(b)] -struct Foo <#[cfg(FALSE)] A, B > +struct Foo <#[cfg(false)] A, B > { - #[cfg(FALSE)] first: String, #[cfg_attr(FALSE, deny(warnings))] second: + #[cfg(false)] first: String, #[cfg_attr(FALSE, deny(warnings))] second: bool, third: [u8; { - #[cfg(FALSE)] struct Bar; #[cfg(not(FALSE))] struct Inner; - #[cfg(FALSE)] let a = 25; match true + #[cfg(false)] struct Bar; #[cfg(not(FALSE))] struct Inner; + #[cfg(false)] let a = 25; match true { - #[cfg(FALSE)] true => {}, #[cfg_attr(not(FALSE), allow(warnings))] + #[cfg(false)] true => {}, #[cfg_attr(not(FALSE), allow(warnings))] false => {}, _ => {} }; #[print_helper(should_be_removed)] fn removed_fn() - { #![cfg(FALSE)] } #[print_helper(c)] #[cfg(not(FALSE))] fn kept_fn() + { #![cfg(false)] } #[print_helper(c)] #[cfg(not(FALSE))] fn kept_fn() { #![cfg(not(FALSE))] let my_val = true; } enum TupleEnum { - Foo(#[cfg(FALSE)] u8, #[cfg(FALSE)] bool, #[cfg(not(FALSE))] i32, - #[cfg(FALSE)] String, u8) + Foo(#[cfg(false)] u8, #[cfg(false)] bool, #[cfg(not(FALSE))] i32, + #[cfg(false)] String, u8) } struct - TupleStruct(#[cfg(FALSE)] String, #[cfg(not(FALSE))] i32, - #[cfg(FALSE)] bool, u8); fn plain_removed_fn() - { #![cfg_attr(not(FALSE), cfg(FALSE))] } 0 + TupleStruct(#[cfg(false)] String, #[cfg(not(FALSE))] i32, + #[cfg(false)] bool, u8); fn plain_removed_fn() + { #![cfg_attr(not(FALSE), cfg(false))] } 0 }], #[print_helper(d)] fourth: B } PRINT-ATTR DEEP-RE-COLLECTED (DISPLAY): #[print_helper(a)] #[allow(dead_code)] #[derive(Print)] #[print_helper(b)] -struct Foo <#[cfg(FALSE)] A, B > +struct Foo <#[cfg(false)] A, B > { - #[cfg(FALSE)] first : String, #[cfg_attr(FALSE, deny(warnings))] second : + #[cfg(false)] first : String, #[cfg_attr(FALSE, deny(warnings))] second : bool, third : [u8; { - #[cfg(FALSE)] struct Bar; #[cfg(not(FALSE))] struct Inner; - #[cfg(FALSE)] let a = 25; match true + #[cfg(false)] struct Bar; #[cfg(not(FALSE))] struct Inner; + #[cfg(false)] let a = 25; match true { - #[cfg(FALSE)] true => {}, #[cfg_attr(not(FALSE), allow(warnings))] + #[cfg(false)] true => {}, #[cfg_attr(not(FALSE), allow(warnings))] false => {}, _ => {} }; #[print_helper(should_be_removed)] fn removed_fn() - { #! [cfg(FALSE)] } #[print_helper(c)] #[cfg(not(FALSE))] fn kept_fn() + { #! [cfg(false)] } #[print_helper(c)] #[cfg(not(FALSE))] fn kept_fn() { #! [cfg(not(FALSE))] let my_val = true; } enum TupleEnum { - Foo(#[cfg(FALSE)] u8, #[cfg(FALSE)] bool, #[cfg(not(FALSE))] i32, - #[cfg(FALSE)] String, u8) + Foo(#[cfg(false)] u8, #[cfg(false)] bool, #[cfg(not(FALSE))] i32, + #[cfg(false)] String, u8) } struct - TupleStruct(#[cfg(FALSE)] String, #[cfg(not(FALSE))] i32, - #[cfg(FALSE)] bool, u8); fn plain_removed_fn() - { #! [cfg_attr(not(FALSE), cfg(FALSE))] } 0 + TupleStruct(#[cfg(false)] String, #[cfg(not(FALSE))] i32, + #[cfg(false)] bool, u8); fn plain_removed_fn() + { #! [cfg_attr(not(FALSE), cfg(false))] } 0 }], #[print_helper(d)] fourth : B } PRINT-ATTR INPUT (DEBUG): TokenStream [ @@ -200,7 +200,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/issue-75930-derive-cfg.rs:54:18: 54:23 (#0), }, ], @@ -246,7 +246,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/issue-75930-derive-cfg.rs:55:11: 55:16 (#0), }, ], @@ -375,7 +375,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/issue-75930-derive-cfg.rs:58:15: 58:20 (#0), }, ], @@ -461,7 +461,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/issue-75930-derive-cfg.rs:60:15: 60:20 (#0), }, ], @@ -521,7 +521,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/issue-75930-derive-cfg.rs:62:19: 62:24 (#0), }, ], @@ -721,7 +721,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/issue-75930-derive-cfg.rs:69:20: 69:25 (#0), }, ], @@ -908,7 +908,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/issue-75930-derive-cfg.rs:79:23: 79:28 (#0), }, ], @@ -942,7 +942,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/issue-75930-derive-cfg.rs:80:23: 80:28 (#0), }, ], @@ -1020,7 +1020,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/issue-75930-derive-cfg.rs:82:23: 82:28 (#0), }, ], @@ -1075,7 +1075,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/issue-75930-derive-cfg.rs:87:19: 87:24 (#0), }, ], @@ -1153,7 +1153,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/issue-75930-derive-cfg.rs:89:19: 89:24 (#0), }, ], @@ -1246,7 +1246,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ delimiter: Parenthesis, stream: TokenStream [ Ident { - ident: "FALSE", + ident: "false", span: $DIR/issue-75930-derive-cfg.rs:94:41: 94:46 (#0), }, ], diff --git a/tests/ui/proc-macro/nested-derive-cfg.rs b/tests/ui/proc-macro/nested-derive-cfg.rs index bd8f231ac2c2a..b3dcfb7c39665 100644 --- a/tests/ui/proc-macro/nested-derive-cfg.rs +++ b/tests/ui/proc-macro/nested-derive-cfg.rs @@ -10,10 +10,10 @@ extern crate test_macros; #[derive(Print)] struct Foo { - #[cfg(FALSE)] removed: bool, + #[cfg(false)] removed: bool, my_array: [bool; { struct Inner { - #[cfg(FALSE)] removed_inner_field: u8, + #[cfg(false)] removed_inner_field: u8, non_removed_inner_field: usize } 0 diff --git a/tests/ui/rfcs/rfc-2294-if-let-guard/feature-gate.rs b/tests/ui/rfcs/rfc-2294-if-let-guard/feature-gate.rs index 110c03d0e5491..983fe87451f24 100644 --- a/tests/ui/rfcs/rfc-2294-if-let-guard/feature-gate.rs +++ b/tests/ui/rfcs/rfc-2294-if-let-guard/feature-gate.rs @@ -64,7 +64,7 @@ fn _macros() { //~^ ERROR expected expression, found `let` statement //~| ERROR expected expression, found `let` statement match () { - #[cfg(FALSE)] + #[cfg(false)] () if let 0 = 1 => {} //~^ ERROR `if let` guards are experimental _ => {} diff --git a/tests/ui/rfcs/rfc-2294-if-let-guard/parens.rs b/tests/ui/rfcs/rfc-2294-if-let-guard/parens.rs index f12824db9c004..0e71a9d24c970 100644 --- a/tests/ui/rfcs/rfc-2294-if-let-guard/parens.rs +++ b/tests/ui/rfcs/rfc-2294-if-let-guard/parens.rs @@ -3,7 +3,7 @@ #![feature(if_let_guard)] #![feature(let_chains)] -#[cfg(FALSE)] +#[cfg(false)] fn un_cfged() { match () { () if let 0 = 1 => {} diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.rs b/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.rs index 99f99c2be72de..0b0abe6ec1754 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.rs +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.rs @@ -340,12 +340,12 @@ fn outside_if_and_while_expr() { //~| ERROR expected expression, found `let` statement { - #[cfg(FALSE)] + #[cfg(false)] let x = true && let y = 1; //~^ ERROR expected expression, found `let` statement } - #[cfg(FALSE)] + #[cfg(false)] { [1, 2, 3][let _ = ()] //~^ ERROR expected expression, found `let` statement @@ -436,11 +436,11 @@ fn with_parenthesis() { //[no_feature]~^ ERROR `let` expressions in this position are unstable } - #[cfg(FALSE)] + #[cfg(false)] let x = (true && let y = 1); //~^ ERROR expected expression, found `let` statement - #[cfg(FALSE)] + #[cfg(false)] { ([1, 2, 3][let _ = ()]) //~^ ERROR expected expression, found `let` statement diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/feature-gate.rs b/tests/ui/rfcs/rfc-2497-if-let-chains/feature-gate.rs index 2087fc42cf102..dad02b7f10639 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/feature-gate.rs +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/feature-gate.rs @@ -51,7 +51,7 @@ fn _macros() { while $e {} } } - #[cfg(FALSE)] (let 0 = 1); + #[cfg(false)] (let 0 = 1); //~^ ERROR expected expression, found `let` statement use_expr!(let 0 = 1); //~^ ERROR no rules expected keyword `let` diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/feature-gate.stderr b/tests/ui/rfcs/rfc-2497-if-let-chains/feature-gate.stderr index 7c874ae78a8ad..b9dac472dca15 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/feature-gate.stderr +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/feature-gate.stderr @@ -1,7 +1,7 @@ error: expected expression, found `let` statement --> $DIR/feature-gate.rs:54:20 | -LL | #[cfg(FALSE)] (let 0 = 1); +LL | #[cfg(false)] (let 0 = 1); | ^^^ | = note: only supported directly in conditions of `if` and `while` expressions diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/invalid-let-in-a-valid-let-context.rs b/tests/ui/rfcs/rfc-2497-if-let-chains/invalid-let-in-a-valid-let-context.rs index dce1c19ff339a..ae525aed4148f 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/invalid-let-in-a-valid-let-context.rs +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/invalid-let-in-a-valid-let-context.rs @@ -3,12 +3,12 @@ fn main() { let _opt = Some(1i32); - #[cfg(FALSE)] + #[cfg(false)] { let _ = &&let Some(x) = Some(42); //~^ ERROR expected expression, found `let` statement } - #[cfg(FALSE)] + #[cfg(false)] { if let Some(elem) = _opt && [1, 2, 3][let _ = &&let Some(x) = Some(42)] = 1 { //~^ ERROR expected expression, found `let` statement @@ -18,7 +18,7 @@ fn main() { } } - #[cfg(FALSE)] + #[cfg(false)] { if let Some(elem) = _opt && { [1, 2, 3][let _ = ()]; @@ -28,7 +28,7 @@ fn main() { } } - #[cfg(FALSE)] + #[cfg(false)] { if let Some(elem) = _opt && [1, 2, 3][let _ = ()] = 1 { //~^ ERROR expected expression, found `let` statement @@ -36,7 +36,7 @@ fn main() { true } } - #[cfg(FALSE)] + #[cfg(false)] { if let a = 1 && { let x = let y = 1; diff --git a/tests/ui/rfcs/rfc-2565-param-attrs/attr-without-param.rs b/tests/ui/rfcs/rfc-2565-param-attrs/attr-without-param.rs index eeb2191bab462..c0f17570673ce 100644 --- a/tests/ui/rfcs/rfc-2565-param-attrs/attr-without-param.rs +++ b/tests/ui/rfcs/rfc-2565-param-attrs/attr-without-param.rs @@ -1,14 +1,14 @@ -#[cfg(FALSE)] +#[cfg(false)] impl S { fn f(#[attr]) {} //~ ERROR expected parameter name, found `)` } -#[cfg(FALSE)] +#[cfg(false)] impl T for S { fn f(#[attr]) {} //~ ERROR expected parameter name, found `)` } -#[cfg(FALSE)] +#[cfg(false)] trait T { fn f(#[attr]); //~ ERROR expected argument name, found `)` } diff --git a/tests/ui/specialization/issue-63716-parse-async.rs b/tests/ui/specialization/issue-63716-parse-async.rs index 3314b4e20f90b..00c0b291a1ada 100644 --- a/tests/ui/specialization/issue-63716-parse-async.rs +++ b/tests/ui/specialization/issue-63716-parse-async.rs @@ -8,7 +8,7 @@ fn main() {} -#[cfg(FALSE)] +#[cfg(false)] impl Foo for Bar { default async fn baz() {} } diff --git a/tests/ui/suggestions/const-no-type.rs b/tests/ui/suggestions/const-no-type.rs index c6fdcdadbeafc..b72ace95213ce 100644 --- a/tests/ui/suggestions/const-no-type.rs +++ b/tests/ui/suggestions/const-no-type.rs @@ -10,19 +10,19 @@ fn main() {} // These will not reach typeck: -#[cfg(FALSE)] +#[cfg(false)] const C2 = 42; //~^ ERROR missing type for `const` item //~| HELP provide a type for the item //~| SUGGESTION : -#[cfg(FALSE)] +#[cfg(false)] static S2 = "abc"; //~^ ERROR missing type for `static` item //~| HELP provide a type for the item //~| SUGGESTION : -#[cfg(FALSE)] +#[cfg(false)] static mut SM2 = "abc"; //~^ ERROR missing type for `static mut` item //~| HELP provide a type for the item diff --git a/tests/ui/suggestions/type-ascription-and-other-error.rs b/tests/ui/suggestions/type-ascription-and-other-error.rs index 99ab2f3c858b9..da985b53aef6f 100644 --- a/tests/ui/suggestions/type-ascription-and-other-error.rs +++ b/tests/ui/suggestions/type-ascription-and-other-error.rs @@ -1,6 +1,6 @@ fn main() { not rust; //~ ERROR let _ = 0: i32; // (error hidden by existing error) - #[cfg(FALSE)] + #[cfg(false)] let _ = 0: i32; // (warning hidden by existing error) } diff --git a/tests/ui/wasm/wasm-import-module.rs b/tests/ui/wasm/wasm-import-module.rs index bff08847d37dd..2b3bca9a411bb 100644 --- a/tests/ui/wasm/wasm-import-module.rs +++ b/tests/ui/wasm/wasm-import-module.rs @@ -15,7 +15,7 @@ extern "C" {} #[link(wasm_import_module = "foo", kind = "dylib")] //~ ERROR: `wasm_import_module` is incompatible with other arguments extern "C" {} -#[link(wasm_import_module = "foo", cfg(FALSE))] //~ ERROR: `wasm_import_module` is incompatible with other arguments +#[link(wasm_import_module = "foo", cfg(false))] //~ ERROR: `wasm_import_module` is incompatible with other arguments extern "C" {} fn main() {} diff --git a/tests/ui/wasm/wasm-import-module.stderr b/tests/ui/wasm/wasm-import-module.stderr index e792c33e91a9d..84f437941a799 100644 --- a/tests/ui/wasm/wasm-import-module.stderr +++ b/tests/ui/wasm/wasm-import-module.stderr @@ -31,7 +31,7 @@ LL | #[link(wasm_import_module = "foo", kind = "dylib")] error: `wasm_import_module` is incompatible with other arguments in `#[link]` attributes --> $DIR/wasm-import-module.rs:18:8 | -LL | #[link(wasm_import_module = "foo", cfg(FALSE))] +LL | #[link(wasm_import_module = "foo", cfg(false))] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 6 previous errors From da0b9a2b89d257f3198f491fdecc5a20a2e686b9 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 7 Apr 2025 15:18:51 +0200 Subject: [PATCH 067/266] f*::NAN: guarantee that this is a quiet NaN --- library/core/src/num/f128.rs | 18 ++++++++++-------- library/core/src/num/f16.rs | 18 ++++++++++-------- library/core/src/num/f32.rs | 18 ++++++++++-------- library/core/src/num/f64.rs | 18 ++++++++++-------- 4 files changed, 40 insertions(+), 32 deletions(-) diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs index 08c34e852da41..d3d1eebc22753 100644 --- a/library/core/src/num/f128.rs +++ b/library/core/src/num/f128.rs @@ -224,14 +224,16 @@ impl f128 { /// Not a Number (NaN). /// - /// Note that IEEE 754 doesn't define just a single NaN value; - /// a plethora of bit patterns are considered to be NaN. - /// Furthermore, the standard makes a difference - /// between a "signaling" and a "quiet" NaN, - /// and allows inspecting its "payload" (the unspecified bits in the bit pattern). - /// This constant isn't guaranteed to equal to any specific NaN bitpattern, - /// and the stability of its representation over Rust versions - /// and target platforms isn't guaranteed. + /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are + /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and + /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern) + /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more + /// info. + /// + /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions + /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is + /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary. + /// The concrete bit pattern may change across Rust versions and target platforms. #[allow(clippy::eq_op)] #[rustc_diagnostic_item = "f128_nan"] #[unstable(feature = "f128", issue = "116909")] diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs index a33e5f5301469..dceb30177e668 100644 --- a/library/core/src/num/f16.rs +++ b/library/core/src/num/f16.rs @@ -219,14 +219,16 @@ impl f16 { /// Not a Number (NaN). /// - /// Note that IEEE 754 doesn't define just a single NaN value; - /// a plethora of bit patterns are considered to be NaN. - /// Furthermore, the standard makes a difference - /// between a "signaling" and a "quiet" NaN, - /// and allows inspecting its "payload" (the unspecified bits in the bit pattern). - /// This constant isn't guaranteed to equal to any specific NaN bitpattern, - /// and the stability of its representation over Rust versions - /// and target platforms isn't guaranteed. + /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are + /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and + /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern) + /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more + /// info. + /// + /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions + /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is + /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary. + /// The concrete bit pattern may change across Rust versions and target platforms. #[allow(clippy::eq_op)] #[rustc_diagnostic_item = "f16_nan"] #[unstable(feature = "f16", issue = "116909")] diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs index e473fac03935a..c97dbfb63ae17 100644 --- a/library/core/src/num/f32.rs +++ b/library/core/src/num/f32.rs @@ -470,14 +470,16 @@ impl f32 { /// Not a Number (NaN). /// - /// Note that IEEE 754 doesn't define just a single NaN value; - /// a plethora of bit patterns are considered to be NaN. - /// Furthermore, the standard makes a difference - /// between a "signaling" and a "quiet" NaN, - /// and allows inspecting its "payload" (the unspecified bits in the bit pattern). - /// This constant isn't guaranteed to equal to any specific NaN bitpattern, - /// and the stability of its representation over Rust versions - /// and target platforms isn't guaranteed. + /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are + /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and + /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern) + /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more + /// info. + /// + /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions + /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is + /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary. + /// The concrete bit pattern may change across Rust versions and target platforms. #[stable(feature = "assoc_int_consts", since = "1.43.0")] #[rustc_diagnostic_item = "f32_nan"] #[allow(clippy::eq_op)] diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs index 6522a80b0b7e8..91affdb3794b0 100644 --- a/library/core/src/num/f64.rs +++ b/library/core/src/num/f64.rs @@ -469,14 +469,16 @@ impl f64 { /// Not a Number (NaN). /// - /// Note that IEEE 754 doesn't define just a single NaN value; - /// a plethora of bit patterns are considered to be NaN. - /// Furthermore, the standard makes a difference - /// between a "signaling" and a "quiet" NaN, - /// and allows inspecting its "payload" (the unspecified bits in the bit pattern). - /// This constant isn't guaranteed to equal to any specific NaN bitpattern, - /// and the stability of its representation over Rust versions - /// and target platforms isn't guaranteed. + /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are + /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and + /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern) + /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more + /// info. + /// + /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions + /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is + /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary. + /// The concrete bit pattern may change across Rust versions and target platforms. #[rustc_diagnostic_item = "f64_nan"] #[stable(feature = "assoc_int_consts", since = "1.43.0")] #[allow(clippy::eq_op)] From 0da46d1065eb53226211e7dea4ba6103607d6def Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 7 Apr 2025 17:00:28 +0200 Subject: [PATCH 068/266] =?UTF-8?q?targest=20=E2=86=92=20targets=20(spotte?= =?UTF-8?q?d=20as=20I=20had=20the=20same=20typo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/tools/miri/tests/pass/tls/tls_leak_main_thread_allowed.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/miri/tests/pass/tls/tls_leak_main_thread_allowed.rs b/src/tools/miri/tests/pass/tls/tls_leak_main_thread_allowed.rs index 341b2280e0109..abc0968f7c4c6 100644 --- a/src/tools/miri/tests/pass/tls/tls_leak_main_thread_allowed.rs +++ b/src/tools/miri/tests/pass/tls/tls_leak_main_thread_allowed.rs @@ -13,7 +13,7 @@ pub fn main() { TLS.set(Some(Box::leak(Box::new(123)))); // We can only ignore leaks on targets that use `#[thread_local]` statics to implement - // `thread_local!`. Ignore the test on targest that don't. + // `thread_local!`. Ignore the test on targets that don't. if cfg!(target_thread_local) { thread_local! { static TLS_KEY: Cell> = Cell::new(None); From 3c3a6a299593d045141faee662ecde9aeb6ec13b Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 6 Apr 2025 23:37:30 +0000 Subject: [PATCH 069/266] Simplify temp path creation a bit --- src/back/write.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/back/write.rs b/src/back/write.rs index 51c5ba73e32bc..3427b38ce830b 100644 --- a/src/back/write.rs +++ b/src/back/write.rs @@ -24,19 +24,15 @@ pub(crate) unsafe fn codegen( { let context = &module.module_llvm.context; - let module_name = module.name.clone(); - let should_combine_object_files = module.module_llvm.should_combine_object_files; - let module_name = Some(&module_name[..]); - // NOTE: Only generate object files with GIMPLE when this environment variable is set for // now because this requires a particular setup (same gcc/lto1/lto-wrapper commit as libgccjit). // TODO(antoyo): remove this environment variable. let fat_lto = env::var("EMBED_LTO_BITCODE").as_deref() == Ok("1"); - let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name); - let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name); + let bc_out = cgcx.output_filenames.temp_path_for_cgu(OutputType::Bitcode, &module.name); + let obj_out = cgcx.output_filenames.temp_path_for_cgu(OutputType::Object, &module.name); if config.bitcode_needed() { if fat_lto { @@ -117,14 +113,15 @@ pub(crate) unsafe fn codegen( } if config.emit_ir { - let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name); + let out = + cgcx.output_filenames.temp_path_for_cgu(OutputType::LlvmAssembly, &module.name); std::fs::write(out, "").expect("write file"); } if config.emit_asm { let _timer = cgcx.prof.generic_activity_with_arg("GCC_module_codegen_emit_asm", &*module.name); - let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name); + let path = cgcx.output_filenames.temp_path_for_cgu(OutputType::Assembly, &module.name); context.compile_to_file(OutputKind::Assembler, path.to_str().expect("path to str")); } From 22d3c0d70a023f3f1641b4b70e4b48949dcface3 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 6 Apr 2025 23:50:16 +0000 Subject: [PATCH 070/266] Prepend temp files with a string per invocation of rustc --- src/back/write.rs | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/src/back/write.rs b/src/back/write.rs index 3427b38ce830b..16c895322e88a 100644 --- a/src/back/write.rs +++ b/src/back/write.rs @@ -31,8 +31,16 @@ pub(crate) unsafe fn codegen( // TODO(antoyo): remove this environment variable. let fat_lto = env::var("EMBED_LTO_BITCODE").as_deref() == Ok("1"); - let bc_out = cgcx.output_filenames.temp_path_for_cgu(OutputType::Bitcode, &module.name); - let obj_out = cgcx.output_filenames.temp_path_for_cgu(OutputType::Object, &module.name); + let bc_out = cgcx.output_filenames.temp_path_for_cgu( + OutputType::Bitcode, + &module.name, + cgcx.invocation_temp.as_deref(), + ); + let obj_out = cgcx.output_filenames.temp_path_for_cgu( + OutputType::Object, + &module.name, + cgcx.invocation_temp.as_deref(), + ); if config.bitcode_needed() { if fat_lto { @@ -113,15 +121,22 @@ pub(crate) unsafe fn codegen( } if config.emit_ir { - let out = - cgcx.output_filenames.temp_path_for_cgu(OutputType::LlvmAssembly, &module.name); + let out = cgcx.output_filenames.temp_path_for_cgu( + OutputType::LlvmAssembly, + &module.name, + cgcx.invocation_temp.as_deref(), + ); std::fs::write(out, "").expect("write file"); } if config.emit_asm { let _timer = cgcx.prof.generic_activity_with_arg("GCC_module_codegen_emit_asm", &*module.name); - let path = cgcx.output_filenames.temp_path_for_cgu(OutputType::Assembly, &module.name); + let path = cgcx.output_filenames.temp_path_for_cgu( + OutputType::Assembly, + &module.name, + cgcx.invocation_temp.as_deref(), + ); context.compile_to_file(OutputKind::Assembler, path.to_str().expect("path to str")); } @@ -235,6 +250,7 @@ pub(crate) unsafe fn codegen( config.emit_asm, config.emit_ir, &cgcx.output_filenames, + cgcx.invocation_temp.as_deref(), )) } From 3ee62a906e8a025834d11c46b8c2f133d3a12448 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 30 Mar 2025 18:52:25 +0000 Subject: [PATCH 071/266] Do not optimize out SwitchInt before borrowck, or if Zmir-preserve-ub --- compiler/rustc_interface/src/tests.rs | 2 +- .../src/early_otherwise_branch.rs | 2 +- compiler/rustc_mir_transform/src/inline.rs | 4 +- .../rustc_mir_transform/src/match_branches.rs | 2 +- .../src/remove_place_mention.rs | 2 +- .../src/remove_unneeded_drops.rs | 2 +- compiler/rustc_mir_transform/src/simplify.rs | 35 +++++++++---- compiler/rustc_session/src/options.rs | 6 +-- src/tools/miri/src/lib.rs | 2 +- .../tests/fail/read_from_trivial_switch.rs | 14 ++++++ .../fail/read_from_trivial_switch.stderr | 15 ++++++ ....match_tuple.SimplifyCfg-initial.after.mir | 34 +++++++------ .../dead-store-elimination/place_mention.rs | 2 +- ...le_switchint.SimplifyCfg-initial.after.mir | 38 ++++++++------ ...ivial_switch.main.SimplifyCfg-initial.diff | 49 +++++++++++++++++++ tests/mir-opt/read_from_trivial_switch.rs | 15 ++++++ tests/ui/pattern/uninit-trivial.rs | 8 +++ tests/ui/pattern/uninit-trivial.stderr | 16 ++++++ 18 files changed, 197 insertions(+), 51 deletions(-) create mode 100644 src/tools/miri/tests/fail/read_from_trivial_switch.rs create mode 100644 src/tools/miri/tests/fail/read_from_trivial_switch.stderr create mode 100644 tests/mir-opt/read_from_trivial_switch.main.SimplifyCfg-initial.diff create mode 100644 tests/mir-opt/read_from_trivial_switch.rs create mode 100644 tests/ui/pattern/uninit-trivial.rs create mode 100644 tests/ui/pattern/uninit-trivial.stderr diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index a8e556632572e..af30a2d8aa887 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -817,8 +817,8 @@ fn test_unstable_options_tracking_hash() { tracked!(min_function_alignment, Some(Align::EIGHT)); tracked!(mir_emit_retag, true); tracked!(mir_enable_passes, vec![("DestProp".to_string(), false)]); - tracked!(mir_keep_place_mention, true); tracked!(mir_opt_level, Some(4)); + tracked!(mir_preserve_ub, true); tracked!(move_size_limit, Some(4096)); tracked!(mutable_noalias, false); tracked!(next_solver, NextSolverConfig { coherence: true, globally: true }); diff --git a/compiler/rustc_mir_transform/src/early_otherwise_branch.rs b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs index 57f7893be1b8c..ac97b08fbed1e 100644 --- a/compiler/rustc_mir_transform/src/early_otherwise_branch.rs +++ b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs @@ -224,7 +224,7 @@ impl<'tcx> crate::MirPass<'tcx> for EarlyOtherwiseBranch { // Since this optimization adds new basic blocks and invalidates others, // clean up the cfg to make it nicer for other passes if should_cleanup { - simplify_cfg(body); + simplify_cfg(tcx, body); } } diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 0ab24e48d443c..babee81a2ad06 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -63,7 +63,7 @@ impl<'tcx> crate::MirPass<'tcx> for Inline { let _guard = span.enter(); if inline::>(tcx, body) { debug!("running simplify cfg on {:?}", body.source); - simplify_cfg(body); + simplify_cfg(tcx, body); deref_finder(tcx, body); } } @@ -99,7 +99,7 @@ impl<'tcx> crate::MirPass<'tcx> for ForceInline { let _guard = span.enter(); if inline::>(tcx, body) { debug!("running simplify cfg on {:?}", body.source); - simplify_cfg(body); + simplify_cfg(tcx, body); deref_finder(tcx, body); } } diff --git a/compiler/rustc_mir_transform/src/match_branches.rs b/compiler/rustc_mir_transform/src/match_branches.rs index 0d9d0368d3729..d43a35124c2aa 100644 --- a/compiler/rustc_mir_transform/src/match_branches.rs +++ b/compiler/rustc_mir_transform/src/match_branches.rs @@ -45,7 +45,7 @@ impl<'tcx> crate::MirPass<'tcx> for MatchBranchSimplification { } if should_cleanup { - simplify_cfg(body); + simplify_cfg(tcx, body); } } diff --git a/compiler/rustc_mir_transform/src/remove_place_mention.rs b/compiler/rustc_mir_transform/src/remove_place_mention.rs index 15fe77d53195a..cb598ceb4dfea 100644 --- a/compiler/rustc_mir_transform/src/remove_place_mention.rs +++ b/compiler/rustc_mir_transform/src/remove_place_mention.rs @@ -8,7 +8,7 @@ pub(super) struct RemovePlaceMention; impl<'tcx> crate::MirPass<'tcx> for RemovePlaceMention { fn is_enabled(&self, sess: &rustc_session::Session) -> bool { - !sess.opts.unstable_opts.mir_keep_place_mention + !sess.opts.unstable_opts.mir_preserve_ub } fn run_pass(&self, _: TyCtxt<'tcx>, body: &mut Body<'tcx>) { diff --git a/compiler/rustc_mir_transform/src/remove_unneeded_drops.rs b/compiler/rustc_mir_transform/src/remove_unneeded_drops.rs index 8a8cdafc69070..43f80508e4a87 100644 --- a/compiler/rustc_mir_transform/src/remove_unneeded_drops.rs +++ b/compiler/rustc_mir_transform/src/remove_unneeded_drops.rs @@ -35,7 +35,7 @@ impl<'tcx> crate::MirPass<'tcx> for RemoveUnneededDrops { // if we applied optimizations, we potentially have some cfg to cleanup to // make it easier for further passes if should_simplify { - simplify_cfg(body); + simplify_cfg(tcx, body); } } diff --git a/compiler/rustc_mir_transform/src/simplify.rs b/compiler/rustc_mir_transform/src/simplify.rs index 84905f4a400f3..6c8fa1fe9b3f1 100644 --- a/compiler/rustc_mir_transform/src/simplify.rs +++ b/compiler/rustc_mir_transform/src/simplify.rs @@ -26,6 +26,13 @@ //! Here the block (`{ return; }`) has the return type `char`, rather than `()`, but the MIR we //! naively generate still contains the `_a = ()` write in the unreachable block "after" the //! return. +//! +//! **WARNING**: This is one of the few optimizations that runs on built and analysis MIR, and +//! so its effects may affect the type-checking, borrow-checking, and other analysis of MIR. +//! We must be extremely careful to only apply optimizations that preserve UB and all +//! non-determinism, since changes here can affect which programs compile in an insta-stable way. +//! The normal logic that a program with UB can be changed to do anything does not apply to +//! pre-"runtime" MIR! use rustc_index::{Idx, IndexSlice, IndexVec}; use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor}; @@ -66,8 +73,8 @@ impl SimplifyCfg { } } -pub(super) fn simplify_cfg(body: &mut Body<'_>) { - CfgSimplifier::new(body).simplify(); +pub(super) fn simplify_cfg<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { + CfgSimplifier::new(tcx, body).simplify(); remove_dead_blocks(body); // FIXME: Should probably be moved into some kind of pass manager @@ -79,9 +86,9 @@ impl<'tcx> crate::MirPass<'tcx> for SimplifyCfg { self.name() } - fn run_pass(&self, _: TyCtxt<'tcx>, body: &mut Body<'tcx>) { + fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { debug!("SimplifyCfg({:?}) - simplifying {:?}", self.name(), body.source); - simplify_cfg(body); + simplify_cfg(tcx, body); } fn is_required(&self) -> bool { @@ -90,12 +97,13 @@ impl<'tcx> crate::MirPass<'tcx> for SimplifyCfg { } struct CfgSimplifier<'a, 'tcx> { + preserve_switch_reads: bool, basic_blocks: &'a mut IndexSlice>, pred_count: IndexVec, } impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { - fn new(body: &'a mut Body<'tcx>) -> Self { + fn new(tcx: TyCtxt<'tcx>, body: &'a mut Body<'tcx>) -> Self { let mut pred_count = IndexVec::from_elem(0u32, &body.basic_blocks); // we can't use mir.predecessors() here because that counts @@ -110,9 +118,12 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { } } + // Preserve `SwitchInt` reads on built and analysis MIR, or if `-Zmir-preserve-ub`. + let preserve_switch_reads = matches!(body.phase, MirPhase::Built | MirPhase::Analysis(_)) + || tcx.sess.opts.unstable_opts.mir_preserve_ub; let basic_blocks = body.basic_blocks_mut(); - CfgSimplifier { basic_blocks, pred_count } + CfgSimplifier { preserve_switch_reads, basic_blocks, pred_count } } fn simplify(mut self) { @@ -253,9 +264,15 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { // turn a branch with all successors identical to a goto fn simplify_branch(&mut self, terminator: &mut Terminator<'tcx>) -> bool { - match terminator.kind { - TerminatorKind::SwitchInt { .. } => {} - _ => return false, + // Removing a `SwitchInt` terminator may remove reads that result in UB, + // so we must not apply this optimization before borrowck or when + // `-Zmir-preserve-ub` is set. + if self.preserve_switch_reads { + return false; + } + + let TerminatorKind::SwitchInt { .. } = terminator.kind else { + return false; }; let first_succ = { diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index c70f1500d3930..ea959d4ced1e9 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -2319,12 +2319,12 @@ options! { mir_include_spans: MirIncludeSpans = (MirIncludeSpans::default(), parse_mir_include_spans, [UNTRACKED], "include extra comments in mir pretty printing, like line numbers and statement indices, \ details about types, etc. (boolean for all passes, 'nll' to enable in NLL MIR only, default: 'nll')"), - mir_keep_place_mention: bool = (false, parse_bool, [TRACKED], - "keep place mention MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0 \ - (default: no)"), #[rustc_lint_opt_deny_field_access("use `Session::mir_opt_level` instead of this field")] mir_opt_level: Option = (None, parse_opt_number, [TRACKED], "MIR optimization level (0-4; default: 1 in non optimized builds and 2 in optimized builds)"), + mir_preserve_ub: bool = (false, parse_bool, [TRACKED], + "keep place mention statements and reads in trivial SwitchInt terminators, which are interpreted \ + e.g., by miri; implies -Zmir-opt-level=0 (default: no)"), mir_strip_debuginfo: MirStripDebugInfo = (MirStripDebugInfo::None, parse_mir_strip_debuginfo, [TRACKED], "Whether to remove some of the MIR debug info from methods. Default: None"), move_size_limit: Option = (None, parse_opt_number, [TRACKED], diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs index 03f76cfa6524c..6f227e04d00fa 100644 --- a/src/tools/miri/src/lib.rs +++ b/src/tools/miri/src/lib.rs @@ -169,7 +169,7 @@ pub const MIRI_DEFAULT_ARGS: &[&str] = &[ "-Zalways-encode-mir", "-Zextra-const-ub-checks", "-Zmir-emit-retag", - "-Zmir-keep-place-mention", + "-Zmir-preserve-ub", "-Zmir-opt-level=0", "-Zmir-enable-passes=-CheckAlignment,-CheckNull", // Deduplicating diagnostics means we miss events when tracking what happens during an diff --git a/src/tools/miri/tests/fail/read_from_trivial_switch.rs b/src/tools/miri/tests/fail/read_from_trivial_switch.rs new file mode 100644 index 0000000000000..d34b1cd582009 --- /dev/null +++ b/src/tools/miri/tests/fail/read_from_trivial_switch.rs @@ -0,0 +1,14 @@ +// Ensure that we don't optimize out `SwitchInt` reads even if that terminator +// branches to the same basic block on every target, since the operand may have +// side-effects that affect analysis of the MIR. +// +// See . + +use std::mem::MaybeUninit; + +fn main() { + let uninit: MaybeUninit = MaybeUninit::uninit(); + let bad_ref: &i32 = unsafe { uninit.assume_init_ref() }; + let &(0 | _) = bad_ref; + //~^ ERROR: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +} diff --git a/src/tools/miri/tests/fail/read_from_trivial_switch.stderr b/src/tools/miri/tests/fail/read_from_trivial_switch.stderr new file mode 100644 index 0000000000000..6b3d4539b9681 --- /dev/null +++ b/src/tools/miri/tests/fail/read_from_trivial_switch.stderr @@ -0,0 +1,15 @@ +error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory + --> tests/fail/read_from_trivial_switch.rs:LL:CC + | +LL | let &(0 | _) = bad_ref; + | ^^^^^^^^ using uninitialized data, but this operation requires initialized memory + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + = note: BACKTRACE: + = note: inside `main` at tests/fail/read_from_trivial_switch.rs:LL:CC + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/tests/mir-opt/building/match/exponential_or.match_tuple.SimplifyCfg-initial.after.mir b/tests/mir-opt/building/match/exponential_or.match_tuple.SimplifyCfg-initial.after.mir index d52241b459ebd..2a965fe67b9e7 100644 --- a/tests/mir-opt/building/match/exponential_or.match_tuple.SimplifyCfg-initial.after.mir +++ b/tests/mir-opt/building/match/exponential_or.match_tuple.SimplifyCfg-initial.after.mir @@ -24,43 +24,47 @@ fn match_tuple(_1: (u32, bool, Option, u32)) -> u32 { bb1: { _0 = const 0_u32; - goto -> bb10; + goto -> bb11; } bb2: { - _2 = discriminant((_1.2: std::option::Option)); - switchInt(move _2) -> [0: bb4, 1: bb3, otherwise: bb1]; + switchInt(copy (_1.1: bool)) -> [0: bb3, otherwise: bb3]; } bb3: { - switchInt(copy (((_1.2: std::option::Option) as Some).0: i32)) -> [1: bb4, 8: bb4, otherwise: bb1]; + _2 = discriminant((_1.2: std::option::Option)); + switchInt(move _2) -> [0: bb5, 1: bb4, otherwise: bb1]; } bb4: { - _5 = Le(const 6_u32, copy (_1.3: u32)); - switchInt(move _5) -> [0: bb5, otherwise: bb7]; + switchInt(copy (((_1.2: std::option::Option) as Some).0: i32)) -> [1: bb5, 8: bb5, otherwise: bb1]; } bb5: { - _3 = Le(const 13_u32, copy (_1.3: u32)); - switchInt(move _3) -> [0: bb1, otherwise: bb6]; + _5 = Le(const 6_u32, copy (_1.3: u32)); + switchInt(move _5) -> [0: bb6, otherwise: bb8]; } bb6: { - _4 = Le(copy (_1.3: u32), const 16_u32); - switchInt(move _4) -> [0: bb1, otherwise: bb8]; + _3 = Le(const 13_u32, copy (_1.3: u32)); + switchInt(move _3) -> [0: bb1, otherwise: bb7]; } bb7: { - _6 = Le(copy (_1.3: u32), const 9_u32); - switchInt(move _6) -> [0: bb5, otherwise: bb8]; + _4 = Le(copy (_1.3: u32), const 16_u32); + switchInt(move _4) -> [0: bb1, otherwise: bb9]; } bb8: { - falseEdge -> [real: bb9, imaginary: bb1]; + _6 = Le(copy (_1.3: u32), const 9_u32); + switchInt(move _6) -> [0: bb6, otherwise: bb9]; } bb9: { + falseEdge -> [real: bb10, imaginary: bb1]; + } + + bb10: { StorageLive(_7); _7 = copy (_1.0: u32); StorageLive(_8); @@ -74,10 +78,10 @@ fn match_tuple(_1: (u32, bool, Option, u32)) -> u32 { StorageDead(_9); StorageDead(_8); StorageDead(_7); - goto -> bb10; + goto -> bb11; } - bb10: { + bb11: { return; } } diff --git a/tests/mir-opt/dead-store-elimination/place_mention.rs b/tests/mir-opt/dead-store-elimination/place_mention.rs index 5e4a286a20874..1848a02829754 100644 --- a/tests/mir-opt/dead-store-elimination/place_mention.rs +++ b/tests/mir-opt/dead-store-elimination/place_mention.rs @@ -2,7 +2,7 @@ // and don't remove it as a dead store. // //@ test-mir-pass: DeadStoreElimination-initial -//@ compile-flags: -Zmir-keep-place-mention +//@ compile-flags: -Zmir-preserve-ub // EMIT_MIR place_mention.main.DeadStoreElimination-initial.diff fn main() { diff --git a/tests/mir-opt/or_pattern.single_switchint.SimplifyCfg-initial.after.mir b/tests/mir-opt/or_pattern.single_switchint.SimplifyCfg-initial.after.mir index 889ff6f9f5e2b..be0931eaa61d7 100644 --- a/tests/mir-opt/or_pattern.single_switchint.SimplifyCfg-initial.after.mir +++ b/tests/mir-opt/or_pattern.single_switchint.SimplifyCfg-initial.after.mir @@ -14,7 +14,7 @@ fn single_switchint() -> () { } bb1: { - switchInt(copy (_2.0: i32)) -> [3: bb8, 4: bb8, otherwise: bb7]; + switchInt(copy (_2.0: i32)) -> [3: bb9, 4: bb9, otherwise: bb8]; } bb2: { @@ -22,7 +22,7 @@ fn single_switchint() -> () { } bb3: { - falseEdge -> [real: bb12, imaginary: bb4]; + falseEdge -> [real: bb14, imaginary: bb4]; } bb4: { @@ -30,43 +30,51 @@ fn single_switchint() -> () { } bb5: { - falseEdge -> [real: bb11, imaginary: bb6]; + falseEdge -> [real: bb13, imaginary: bb6]; } bb6: { - falseEdge -> [real: bb10, imaginary: bb1]; + switchInt(copy (_2.1: bool)) -> [0: bb7, otherwise: bb7]; } bb7: { - _1 = const 5_i32; - goto -> bb13; + falseEdge -> [real: bb12, imaginary: bb1]; } bb8: { - falseEdge -> [real: bb9, imaginary: bb7]; + _1 = const 5_i32; + goto -> bb15; } bb9: { - _1 = const 4_i32; - goto -> bb13; + switchInt(copy (_2.1: bool)) -> [0: bb10, otherwise: bb10]; } bb10: { - _1 = const 3_i32; - goto -> bb13; + falseEdge -> [real: bb11, imaginary: bb8]; } bb11: { - _1 = const 2_i32; - goto -> bb13; + _1 = const 4_i32; + goto -> bb15; } bb12: { - _1 = const 1_i32; - goto -> bb13; + _1 = const 3_i32; + goto -> bb15; } bb13: { + _1 = const 2_i32; + goto -> bb15; + } + + bb14: { + _1 = const 1_i32; + goto -> bb15; + } + + bb15: { StorageDead(_2); StorageDead(_1); _0 = const (); diff --git a/tests/mir-opt/read_from_trivial_switch.main.SimplifyCfg-initial.diff b/tests/mir-opt/read_from_trivial_switch.main.SimplifyCfg-initial.diff new file mode 100644 index 0000000000000..87758408a1c37 --- /dev/null +++ b/tests/mir-opt/read_from_trivial_switch.main.SimplifyCfg-initial.diff @@ -0,0 +1,49 @@ +- // MIR for `main` before SimplifyCfg-initial ++ // MIR for `main` after SimplifyCfg-initial + + fn main() -> () { + let mut _0: (); + let _1: &i32; + let _2: i32; + scope 1 { + debug ref_ => _1; + scope 2 { + } + } + + bb0: { + StorageLive(_1); + StorageLive(_2); + _2 = const 1_i32; + _1 = &_2; + FakeRead(ForLet(None), _1); + PlaceMention(_1); +- switchInt(copy (*_1)) -> [0: bb2, otherwise: bb1]; ++ switchInt(copy (*_1)) -> [0: bb1, otherwise: bb1]; + } + + bb1: { +- goto -> bb5; +- } +- +- bb2: { +- goto -> bb5; +- } +- +- bb3: { +- goto -> bb1; +- } +- +- bb4: { +- FakeRead(ForMatchedPlace(None), _1); +- unreachable; +- } +- +- bb5: { + _0 = const (); + StorageDead(_2); + StorageDead(_1); + return; + } + } + diff --git a/tests/mir-opt/read_from_trivial_switch.rs b/tests/mir-opt/read_from_trivial_switch.rs new file mode 100644 index 0000000000000..1c64c1d45e831 --- /dev/null +++ b/tests/mir-opt/read_from_trivial_switch.rs @@ -0,0 +1,15 @@ +// Ensure that we don't optimize out `SwitchInt` reads even if that terminator +// branches to the same basic block on every target, since the operand may have +// side-effects that affect analysis of the MIR. +// +// See . + +//@ test-mir-pass: SimplifyCfg-initial +//@ compile-flags: -Zmir-preserve-ub + +// EMIT_MIR read_from_trivial_switch.main.SimplifyCfg-initial.diff +fn main() { + let ref_ = &1i32; + // CHECK: switchInt + let &(0 | _) = ref_; +} diff --git a/tests/ui/pattern/uninit-trivial.rs b/tests/ui/pattern/uninit-trivial.rs new file mode 100644 index 0000000000000..6ea6796c1c1f0 --- /dev/null +++ b/tests/ui/pattern/uninit-trivial.rs @@ -0,0 +1,8 @@ +// Regression test for the semantic changes in +// . + +fn main() { + let x; + let (0 | _) = x; + //~^ ERROR used binding `x` isn't initialized +} diff --git a/tests/ui/pattern/uninit-trivial.stderr b/tests/ui/pattern/uninit-trivial.stderr new file mode 100644 index 0000000000000..2ff8557c94543 --- /dev/null +++ b/tests/ui/pattern/uninit-trivial.stderr @@ -0,0 +1,16 @@ +error[E0381]: used binding `x` isn't initialized + --> $DIR/uninit-trivial.rs:6:10 + | +LL | let x; + | - binding declared here but left uninitialized +LL | let (0 | _) = x; + | ^^^^^ `x` used here but it isn't initialized + | +help: consider assigning a value + | +LL | let x = 42; + | ++++ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0381`. From 199ee4084349361ae44c6e4b0cbc9a5e72913b20 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Tue, 25 Mar 2025 14:48:12 +0100 Subject: [PATCH 072/266] Move errors --- .../src/error_reporting/traits/mod.rs | 1 + .../traits/on_unimplemented.rs | 79 +---------------- .../traits/on_unimplemented_format.rs | 86 +++++++++++++++++++ 3 files changed, 89 insertions(+), 77 deletions(-) create mode 100644 compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs index 8ff7030717a8b..7fd1c0d2743b9 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs @@ -2,6 +2,7 @@ pub mod ambiguity; pub mod call_kind; mod fulfillment_errors; pub mod on_unimplemented; +pub mod on_unimplemented_format; mod overflow; pub mod suggestions; diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs index f0c6e51f2a4c4..9914e828a9338 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs @@ -7,18 +7,18 @@ use rustc_errors::codes::*; use rustc_errors::{ErrorGuaranteed, struct_span_code_err}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{AttrArgs, Attribute}; -use rustc_macros::LintDiagnostic; use rustc_middle::bug; use rustc_middle::ty::print::PrintTraitRefExt as _; use rustc_middle::ty::{self, GenericArgsRef, GenericParamDefKind, TyCtxt}; use rustc_parse_format::{ParseMode, Parser, Piece, Position}; use rustc_session::lint::builtin::UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES; -use rustc_span::{Ident, Span, Symbol, kw, sym}; +use rustc_span::{Span, Symbol, kw, sym}; use tracing::{debug, info}; use {rustc_attr_parsing as attr, rustc_hir as hir}; use super::{ObligationCauseCode, PredicateObligation}; use crate::error_reporting::TypeErrCtxt; +use crate::error_reporting::traits::on_unimplemented_format::errors::*; use crate::errors::{ EmptyOnClauseInOnUnimplemented, InvalidOnClauseInOnUnimplemented, NoValueInOnUnimplemented, }; @@ -320,81 +320,6 @@ pub enum AppendConstMessage { Custom(Symbol, Span), } -#[derive(LintDiagnostic)] -#[diag(trait_selection_malformed_on_unimplemented_attr)] -#[help] -pub struct MalformedOnUnimplementedAttrLint { - #[label] - pub span: Span, -} - -impl MalformedOnUnimplementedAttrLint { - fn new(span: Span) -> Self { - Self { span } - } -} - -#[derive(LintDiagnostic)] -#[diag(trait_selection_missing_options_for_on_unimplemented_attr)] -#[help] -pub struct MissingOptionsForOnUnimplementedAttr; - -#[derive(LintDiagnostic)] -#[diag(trait_selection_ignored_diagnostic_option)] -pub struct IgnoredDiagnosticOption { - pub option_name: &'static str, - #[label] - pub span: Span, - #[label(trait_selection_other_label)] - pub prev_span: Span, -} - -impl IgnoredDiagnosticOption { - fn maybe_emit_warning<'tcx>( - tcx: TyCtxt<'tcx>, - item_def_id: DefId, - new: Option, - old: Option, - option_name: &'static str, - ) { - if let (Some(new_item), Some(old_item)) = (new, old) { - if let Some(item_def_id) = item_def_id.as_local() { - tcx.emit_node_span_lint( - UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, - tcx.local_def_id_to_hir_id(item_def_id), - new_item, - IgnoredDiagnosticOption { span: new_item, prev_span: old_item, option_name }, - ); - } - } - } -} - -#[derive(LintDiagnostic)] -#[diag(trait_selection_unknown_format_parameter_for_on_unimplemented_attr)] -#[help] -pub struct UnknownFormatParameterForOnUnimplementedAttr { - argument_name: Symbol, - trait_name: Ident, -} - -#[derive(LintDiagnostic)] -#[diag(trait_selection_disallowed_positional_argument)] -#[help] -pub struct DisallowedPositionalArgument; - -#[derive(LintDiagnostic)] -#[diag(trait_selection_invalid_format_specifier)] -#[help] -pub struct InvalidFormatSpecifier; - -#[derive(LintDiagnostic)] -#[diag(trait_selection_wrapped_parser_error)] -pub struct WrappedParserError { - description: String, - label: String, -} - impl<'tcx> OnUnimplementedDirective { fn parse( tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs new file mode 100644 index 0000000000000..40a47921fc11a --- /dev/null +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs @@ -0,0 +1,86 @@ +pub mod errors { + use rustc_macros::LintDiagnostic; + use rustc_middle::ty::TyCtxt; + use rustc_session::lint::builtin::UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES; + use rustc_span::Ident; + + use super::*; + + #[derive(LintDiagnostic)] + #[diag(trait_selection_unknown_format_parameter_for_on_unimplemented_attr)] + #[help] + pub struct UnknownFormatParameterForOnUnimplementedAttr { + pub argument_name: Symbol, + pub trait_name: Ident, + } + + #[derive(LintDiagnostic)] + #[diag(trait_selection_disallowed_positional_argument)] + #[help] + pub struct DisallowedPositionalArgument; + + #[derive(LintDiagnostic)] + #[diag(trait_selection_invalid_format_specifier)] + #[help] + pub struct InvalidFormatSpecifier; + + #[derive(LintDiagnostic)] + #[diag(trait_selection_wrapped_parser_error)] + pub struct WrappedParserError { + pub description: String, + pub label: String, + } + #[derive(LintDiagnostic)] + #[diag(trait_selection_malformed_on_unimplemented_attr)] + #[help] + pub struct MalformedOnUnimplementedAttrLint { + #[label] + pub span: Span, + } + + impl MalformedOnUnimplementedAttrLint { + pub fn new(span: Span) -> Self { + Self { span } + } + } + + #[derive(LintDiagnostic)] + #[diag(trait_selection_missing_options_for_on_unimplemented_attr)] + #[help] + pub struct MissingOptionsForOnUnimplementedAttr; + + #[derive(LintDiagnostic)] + #[diag(trait_selection_ignored_diagnostic_option)] + pub struct IgnoredDiagnosticOption { + pub option_name: &'static str, + #[label] + pub span: Span, + #[label(trait_selection_other_label)] + pub prev_span: Span, + } + + impl IgnoredDiagnosticOption { + pub fn maybe_emit_warning<'tcx>( + tcx: TyCtxt<'tcx>, + item_def_id: DefId, + new: Option, + old: Option, + option_name: &'static str, + ) { + if let (Some(new_item), Some(old_item)) = (new, old) { + if let Some(item_def_id) = item_def_id.as_local() { + tcx.emit_node_span_lint( + UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, + tcx.local_def_id_to_hir_id(item_def_id), + new_item, + IgnoredDiagnosticOption { + span: new_item, + prev_span: old_item, + option_name, + }, + ); + } + } + } + } +} From ac4014bd2004811851caea3e81c22cbed7b92aa5 Mon Sep 17 00:00:00 2001 From: Tim Newsome Date: Wed, 22 Jan 2025 16:05:26 -0800 Subject: [PATCH 073/266] Add minimal x86_64-lynx-lynxos178 support. It's possible to build no_std programs with this compiler. > A tier 3 target must have a designated developer or developers (the "target maintainers") on record to be CCed when issues arise regarding the target. (The mechanism to track and CC such developers may evolve over time.) Tim Newsome (@tnewsome-lynx) will be the designated developer for x86_64-lynx-lynxos178 support. > Targets must use naming consistent with any existing targets; for instance, a target for the same CPU or OS as an existing Rust target should use the same name for that CPU or OS. Targets should normally use the same names and naming conventions as used elsewhere in the broader ecosystem beyond Rust (such as in other toolchains), unless they have a very good reason to diverge. Changing the name of a target can be highly disruptive, especially once the target reaches a higher tier, so getting the name right is important even for a tier 3 target. I believe the target is named appropriately. > Target names should not introduce undue confusion or ambiguity unless absolutely necessary to maintain ecosystem compatibility. For example, if the name of the target makes people extremely likely to form incorrect beliefs about what it targets, the name should be changed or augmented to disambiguate it. The target name is not confusing. > If possible, use only letters, numbers, dashes and underscores for the name. Periods (.) are known to cause issues in Cargo. Done. > Tier 3 targets may have unusual requirements to build or use, but must not create legal issues or impose onerous legal terms for the Rust project or for Rust developers or users. > The target must not introduce license incompatibilities. > Anything added to the Rust repository must be under the standard Rust license (MIT OR Apache-2.0). All this new code is licensed under the Apache-2.0 license. > The target must not cause the Rust tools or libraries built for any other host (even when supporting cross-compilation to the target) to depend on any new dependency less permissive than the Rust licensing policy. This applies whether the dependency is a Rust crate that would require adding new license exceptions (as specified by the tidy tool in the rust-lang/rust repository), or whether the dependency is a native library or binary. In other words, the introduction of the target must not cause a user installing or running a version of Rust or the Rust tools to be subject to any new license requirements. Done. > Compiling, linking, and emitting functional binaries, libraries, or other code for the target (whether hosted on the target itself or cross-compiling from another target) must not depend on proprietary (non-FOSS) libraries. Host tools built for the target itself may depend on the ordinary runtime libraries supplied by the platform and commonly used by other applications built for the target, but those libraries must not be required for code generation for the target; cross-compilation to the target must not require such libraries at all. For instance, rustc built for the target may depend on a common proprietary C runtime library or console output library, but must not depend on a proprietary code generation library or code optimization library. Rust's license permits such combinations, but the Rust project has no interest in maintaining such combinations within the scope of Rust itself, even at tier 3. I think we're in the clear here. We do link against some static libraries that are proprietary (like libm and libc), but those are not used to generate code. E.g. the VxWorks target requires `wr-c++` to be installed, which is not publically available. > "onerous" here is an intentionally subjective term. At a minimum, "onerous" legal/licensing terms include but are not limited to: non-disclosure requirements, non-compete requirements, contributor license agreements (CLAs) or equivalent, "non-commercial"/"research-only"/etc terms, requirements conditional on the employer or employment of any particular Rust developers, revocable terms, any requirements that create liability for the Rust project or its developers or users, or any requirements that adversely affect the livelihood or prospects of the Rust project or its developers or users. Our intention is to allow anyone with access to LynxOS CDK to use Rust for it. > Neither this policy nor any decisions made regarding targets shall create any binding agreement or estoppel by any party. If any member of an approving Rust team serves as one of the maintainers of a target, or has any legal or employment requirement (explicit or implicit) that might affect their decisions regarding a target, they must recuse themselves from any approval decisions regarding the target's tier status, though they may otherwise participate in discussions. > This requirement does not prevent part or all of this policy from being cited in an explicit contract or work agreement (e.g. to implement or maintain support for a target). This requirement exists to ensure that a developer or team responsible for reviewing and approving a target does not face any legal threats or obligations that would prevent them from freely exercising their judgment in such approval, even if such judgment involves subjective matters or goes beyond the letter of these requirements. No problem. > Tier 3 targets should attempt to implement as much of the standard libraries as possible and appropriate (core for most targets, alloc for targets that can support dynamic memory allocation, std for targets with an operating system or equivalent layer of system-provided functionality), but may leave some code unimplemented (either unavailable or stubbed out as appropriate), whether because the target makes it impossible to implement or challenging to implement. The authors of pull requests are not obligated to avoid calling any portions of the standard library on the basis of a tier 3 target not implementing those portions. With this first PR, only core is supported. I am working on support for the std library and intend to submit that once all the tests are passing. > The target must provide documentation for the Rust community explaining how to build for the target, using cross-compilation if possible. If the target supports running binaries, or running tests (even if they do not pass), the documentation must explain how to run such binaries or tests for the target, using emulation if possible or dedicated hardware if necessary. This is documented in `src/doc/rustc/src/platform-support/lynxos_178.md`. > Tier 3 targets must not impose burden on the authors of pull requests, or other developers in the community, to maintain the target. In particular, do not post comments (automated or manual) on a PR that derail or suggest a block on the PR based on a tier 3 target. Do not send automated messages or notifications (via any medium, including via @) to a PR author or others involved with a PR regarding a tier 3 target, unless they have opted into such messages. > Backlinks such as those generated by the issue/PR tracker when linking to an issue or PR are not considered a violation of this policy, within reason. However, such messages (even on a separate repository) must not generate notifications to anyone involved with a PR who has not requested such notifications. Understood. > Patches adding or updating tier 3 targets must not break any existing tier 2 or tier 1 target, and must not knowingly break another tier 3 target without approval of either the compiler team or the maintainers of the other tier 3 target. > In particular, this may come up when working on closely related targets, such as variations of the same architecture with different features. Avoid introducing unconditional uses of features that another variation of the target may not have; use conditional compilation or runtime detection, as appropriate, to let each target run code supported by that target. As far as I know this change does not affect any other targets. > Tier 3 targets must be able to produce assembly using at least one of rustc's supported backends from any host target. (Having support in a fork of the backend is not sufficient, it must be upstream.) Many targets produce assembly for x86_64 so that also works for LynxOS-178. --- .../rustc_target/src/spec/base/lynxos178.rs | 31 ++++++++ compiler/rustc_target/src/spec/base/mod.rs | 1 + compiler/rustc_target/src/spec/mod.rs | 1 + .../src/spec/targets/x86_64_lynx_lynxos178.rs | 34 ++++++++ src/bootstrap/src/core/sanity.rs | 1 + src/doc/rustc/src/SUMMARY.md | 1 + src/doc/rustc/src/platform-support.md | 1 + .../rustc/src/platform-support/lynxos178.md | 77 +++++++++++++++++++ tests/assembly/targets/targets-elf.rs | 3 + tests/ui/check-cfg/well-known-values.stderr | 4 +- 10 files changed, 152 insertions(+), 2 deletions(-) create mode 100644 compiler/rustc_target/src/spec/base/lynxos178.rs create mode 100644 compiler/rustc_target/src/spec/targets/x86_64_lynx_lynxos178.rs create mode 100644 src/doc/rustc/src/platform-support/lynxos178.md diff --git a/compiler/rustc_target/src/spec/base/lynxos178.rs b/compiler/rustc_target/src/spec/base/lynxos178.rs new file mode 100644 index 0000000000000..b9434ff5faaf6 --- /dev/null +++ b/compiler/rustc_target/src/spec/base/lynxos178.rs @@ -0,0 +1,31 @@ +use std::borrow::Cow; + +use crate::spec::{ + PanicStrategy, RelocModel, RelroLevel, SplitDebuginfo, StackProbeType, TargetOptions, cvs, +}; + +pub(crate) fn opts() -> TargetOptions { + TargetOptions { + os: "lynxos178".into(), + dynamic_linking: false, + families: cvs!["unix"], + position_independent_executables: false, + static_position_independent_executables: false, + relro_level: RelroLevel::Full, + has_thread_local: false, + crt_static_respected: true, + panic_strategy: PanicStrategy::Abort, + linker: Some(Cow::Borrowed("x86_64-lynx-lynxos178-gcc")), + no_default_libraries: false, + eh_frame_header: false, // GNU ld (GNU Binutils) 2.37.50 does not support --eh-frame-hdr + max_atomic_width: Some(64), + supported_split_debuginfo: Cow::Borrowed(&[ + SplitDebuginfo::Packed, + SplitDebuginfo::Unpacked, + SplitDebuginfo::Off, + ]), + relocation_model: RelocModel::Static, + stack_probes: StackProbeType::Inline, + ..Default::default() + } +} diff --git a/compiler/rustc_target/src/spec/base/mod.rs b/compiler/rustc_target/src/spec/base/mod.rs index 71b6528c2dd11..b368d93f00726 100644 --- a/compiler/rustc_target/src/spec/base/mod.rs +++ b/compiler/rustc_target/src/spec/base/mod.rs @@ -19,6 +19,7 @@ pub(crate) mod linux_musl; pub(crate) mod linux_ohos; pub(crate) mod linux_uclibc; pub(crate) mod linux_wasm; +pub(crate) mod lynxos178; pub(crate) mod msvc; pub(crate) mod netbsd; pub(crate) mod nto_qnx; diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 64171fcc7ab34..3c769dad630a1 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -2078,6 +2078,7 @@ supported_targets! { ("riscv32imafc-unknown-nuttx-elf", riscv32imafc_unknown_nuttx_elf), ("riscv64imac-unknown-nuttx-elf", riscv64imac_unknown_nuttx_elf), ("riscv64gc-unknown-nuttx-elf", riscv64gc_unknown_nuttx_elf), + ("x86_64-lynx-lynxos178", x86_64_lynx_lynxos178), ("x86_64-pc-cygwin", x86_64_pc_cygwin), } diff --git a/compiler/rustc_target/src/spec/targets/x86_64_lynx_lynxos178.rs b/compiler/rustc_target/src/spec/targets/x86_64_lynx_lynxos178.rs new file mode 100644 index 0000000000000..654ae7c9c5bea --- /dev/null +++ b/compiler/rustc_target/src/spec/targets/x86_64_lynx_lynxos178.rs @@ -0,0 +1,34 @@ +use crate::spec::{SanitizerSet, StackProbeType, Target, base}; + +pub(crate) fn target() -> Target { + let mut base = base::lynxos178::opts(); + base.cpu = "x86-64".into(); + base.plt_by_default = false; + base.max_atomic_width = Some(64); + base.stack_probes = StackProbeType::Inline; + base.static_position_independent_executables = false; + base.supported_sanitizers = SanitizerSet::ADDRESS + | SanitizerSet::CFI + | SanitizerSet::KCFI + | SanitizerSet::DATAFLOW + | SanitizerSet::LEAK + | SanitizerSet::MEMORY + | SanitizerSet::SAFESTACK + | SanitizerSet::THREAD; + base.supports_xray = true; + + Target { + llvm_target: "x86_64-unknown-unknown-gnu".into(), + metadata: crate::spec::TargetMetadata { + description: Some("LynxOS-178".into()), + tier: Some(3), + host_tools: Some(false), + std: Some(false), + }, + pointer_width: 64, + data_layout: + "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128".into(), + arch: "x86_64".into(), + options: base, + } +} diff --git a/src/bootstrap/src/core/sanity.rs b/src/bootstrap/src/core/sanity.rs index 891340add908e..9e4a72bc9c37d 100644 --- a/src/bootstrap/src/core/sanity.rs +++ b/src/bootstrap/src/core/sanity.rs @@ -34,6 +34,7 @@ pub struct Finder { // Targets can be removed from this list once they are present in the stage0 compiler (usually by updating the beta compiler of the bootstrap). const STAGE0_MISSING_TARGETS: &[&str] = &[ // just a dummy comment so the list doesn't get onelined + "x86_64-lynx-lynxos178", ]; /// Minimum version threshold for libstdc++ required when using prebuilt LLVM diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md index 9bb64adfa7869..cf41f5b86a85c 100644 --- a/src/doc/rustc/src/SUMMARY.md +++ b/src/doc/rustc/src/SUMMARY.md @@ -78,6 +78,7 @@ - [illumos](platform-support/illumos.md) - [loongarch\*-unknown-linux-\*](platform-support/loongarch-linux.md) - [loongarch\*-unknown-none\*](platform-support/loongarch-none.md) + - [\*-lynxos178-\*](platform-support/lynxos178.md) - [m68k-unknown-linux-gnu](platform-support/m68k-unknown-linux-gnu.md) - [m68k-unknown-none-elf](platform-support/m68k-unknown-none-elf.md) - [mips64-openwrt-linux-musl](platform-support/mips64-openwrt-linux-musl.md) diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index 4149b4cb92020..9870e5011ebf6 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -407,6 +407,7 @@ target | std | host | notes [`wasm32-wali-linux-musl`](platform-support/wasm32-wali-linux.md) | ? | | WebAssembly with [WALI](https://github.com/arjunr2/WALI) [`x86_64-apple-tvos`](platform-support/apple-tvos.md) | ✓ | | x86 64-bit tvOS [`x86_64-apple-watchos-sim`](platform-support/apple-watchos.md) | ✓ | | x86 64-bit Apple WatchOS simulator +[`x86_64-lynx-lynxos178`](platform-support/lynxos178.md) | | | x86_64 LynxOS-178 [`x86_64-pc-cygwin`](platform-support/x86_64-pc-cygwin.md) | ✓ | | 64-bit x86 Cygwin | [`x86_64-pc-nto-qnx710`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 7.1 RTOS with default network stack (io-pkt) | [`x86_64-pc-nto-qnx710_iosock`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 7.1 RTOS with new network stack (io-sock) | diff --git a/src/doc/rustc/src/platform-support/lynxos178.md b/src/doc/rustc/src/platform-support/lynxos178.md new file mode 100644 index 0000000000000..6463f95a0b8e0 --- /dev/null +++ b/src/doc/rustc/src/platform-support/lynxos178.md @@ -0,0 +1,77 @@ +# `*-lynxos178-*` + +**Tier: 3** + +Targets for the LynxOS-178 operating system. + +[LynxOS-178](https://www.lynx.com/products/lynxos-178-do-178c-certified-posix-rtos) +is a commercial RTOS designed for safety-critical real-time systems. It is +developed by Lynx Software Technologies as part of the +[MOSA.ic](https://www.lynx.com/solutions/safe-and-secure-operating-environment) +product suite. + +Target triples available: +- `x86_64-lynx-lynxos178` + +## Target maintainers + +- Renat Fatykhov, https://github.com/rfatykhov-lynx + +## Requirements + +To build Rust programs for LynxOS-178, you must first have LYNX MOSA.ic +installed on the build machine. + +This target supports only cross-compilation, from the same hosts supported by +the Lynx CDK. + +Currently only `no_std` programs are supported. Work to support `std` is in +progress. + +## Building the target + +You can build Rust with support for x86_64-lynx-lynxos178 by adding that +to the `target` list in `config.toml`, and then running `./x build --target +x86_64-lynx-lynxos178 compiler`. + +## Building Rust programs + +Rust does not yet ship pre-compiled artifacts for this target. To compile for +this target, you will need to build Rust with the target enabled (see "Building +the target" above). + +Before executing `cargo`, you must configure the environment to build LynxOS-178 +binaries by running `source setup.sh` from the los178 directory. + +If your program/crates contain procedural macros, Rust must be able to build +binaries for the host as well. The host gcc is hidden by sourcing setup.sh. To +deal with this, add the following to your project's `.cargo/config.toml`: +```toml +[target.x86_64-unknown-linux-gnu] +linker = "lynx-host-gcc" +``` +(If necessary substitute your host target triple for x86_64-unknown-linux-gnu.) + +To point `cargo` at the correct rustc binary, set the RUSTC environment +variable. + +The core library should be usable. You can try by building it as part of your +project: +```bash +cargo +nightly build -Z build-std=core --target x86_64-lynx-lynxos178 +``` + +## Testing + +Binaries built with rust can be provided to a LynxOS-178 instance on its file +system, where they can be executed. Rust binaries tend to be large, so it may +be necessary to strip them first. + +It is possible to run the Rust testsuite by providing a test runner that takes +the test binary and executes it under LynxOS-178. Most (all?) tests won't run +without std support though, which is not yet supported. + +## Cross-compilation toolchains and C code + +LYNX MOSA.ic comes with all the tools required to cross-compile C code for +LynxOS-178. diff --git a/tests/assembly/targets/targets-elf.rs b/tests/assembly/targets/targets-elf.rs index 8f2fef0e9c911..3255591119498 100644 --- a/tests/assembly/targets/targets-elf.rs +++ b/tests/assembly/targets/targets-elf.rs @@ -571,6 +571,9 @@ //@ revisions: x86_64_linux_android //@ [x86_64_linux_android] compile-flags: --target x86_64-linux-android //@ [x86_64_linux_android] needs-llvm-components: x86 +//@ revisions: x86_64_lynx_lynxos178 +//@ [x86_64_lynx_lynxos178] compile-flags: --target x86_64-lynx-lynxos178 +//@ [x86_64_lynx_lynxos178] needs-llvm-components: x86 //@ revisions: x86_64_pc_nto_qnx710 //@ [x86_64_pc_nto_qnx710] compile-flags: --target x86_64-pc-nto-qnx710 //@ [x86_64_pc_nto_qnx710] needs-llvm-components: x86 diff --git a/tests/ui/check-cfg/well-known-values.stderr b/tests/ui/check-cfg/well-known-values.stderr index 4636b6945d060..7cda6c2eaa529 100644 --- a/tests/ui/check-cfg/well-known-values.stderr +++ b/tests/ui/check-cfg/well-known-values.stderr @@ -201,7 +201,7 @@ warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` LL | target_os = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `cygwin`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `psx`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm` + = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `cygwin`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `lynxos178`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `psx`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm` = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` @@ -274,7 +274,7 @@ LL | #[cfg(target_os = "linuz")] // testing that we suggest `linux` | | | help: there is a expected value with a similar name: `"linux"` | - = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `cygwin`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `psx`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm` + = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `cygwin`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `lynxos178`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `psx`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm` = note: see for more information about checking conditional configuration warning: 28 warnings emitted From 2007c8994db6d46533f84f4697fea5734c6df53d Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 27 Mar 2025 15:39:23 +0100 Subject: [PATCH 074/266] Write the format string parserand split it from conditions parser --- compiler/rustc_span/src/symbol.rs | 1 + .../src/error_reporting/traits/mod.rs | 1 + .../traits/on_unimplemented.rs | 399 ++++++------------ .../traits/on_unimplemented_condition.rs | 64 +++ .../traits/on_unimplemented_format.rs | 344 +++++++++++++++ .../on_unimplemented/broken_format.stderr | 48 +-- ...ons_of_the_internal_rustc_attribute.stderr | 80 ++-- ...t_fail_parsing_on_invalid_options_1.stderr | 8 +- tests/ui/on-unimplemented/bad-annotation.rs | 4 +- .../ui/on-unimplemented/bad-annotation.stderr | 22 +- tests/ui/on-unimplemented/impl-substs.stderr | 2 +- 11 files changed, 613 insertions(+), 360 deletions(-) create mode 100644 compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_condition.rs diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 31847ae3b4658..0c458db0b23d4 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -372,6 +372,7 @@ symbols! { SyncUnsafeCell, T, Target, + This, ToOwned, ToString, TokenStream, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs index 7fd1c0d2743b9..78f9287b407b3 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs @@ -2,6 +2,7 @@ pub mod ambiguity; pub mod call_kind; mod fulfillment_errors; pub mod on_unimplemented; +pub mod on_unimplemented_condition; pub mod on_unimplemented_format; mod overflow; pub mod suggestions; diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs index 9914e828a9338..6a7f32234213f 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs @@ -1,7 +1,7 @@ use std::iter; use std::path::PathBuf; -use rustc_ast::MetaItemInner; +use rustc_ast::{LitKind, MetaItem, MetaItemInner, MetaItemKind, MetaItemLit}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::codes::*; use rustc_errors::{ErrorGuaranteed, struct_span_code_err}; @@ -10,35 +10,21 @@ use rustc_hir::{AttrArgs, Attribute}; use rustc_middle::bug; use rustc_middle::ty::print::PrintTraitRefExt as _; use rustc_middle::ty::{self, GenericArgsRef, GenericParamDefKind, TyCtxt}; -use rustc_parse_format::{ParseMode, Parser, Piece, Position}; use rustc_session::lint::builtin::UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES; -use rustc_span::{Span, Symbol, kw, sym}; +use rustc_span::{Span, Symbol, sym}; use tracing::{debug, info}; use {rustc_attr_parsing as attr, rustc_hir as hir}; use super::{ObligationCauseCode, PredicateObligation}; use crate::error_reporting::TypeErrCtxt; +use crate::error_reporting::traits::on_unimplemented_condition::Condition; use crate::error_reporting::traits::on_unimplemented_format::errors::*; +use crate::error_reporting::traits::on_unimplemented_format::{Ctx, FormatString}; use crate::errors::{ EmptyOnClauseInOnUnimplemented, InvalidOnClauseInOnUnimplemented, NoValueInOnUnimplemented, }; use crate::infer::InferCtxtExt; -/// The symbols which are always allowed in a format string -static ALLOWED_FORMAT_SYMBOLS: &[Symbol] = &[ - kw::SelfUpper, - sym::ItemContext, - sym::from_desugaring, - sym::direct, - sym::cause, - sym::integral, - sym::integer_, - sym::float, - sym::_Self, - sym::crate_local, - sym::Trait, -]; - impl<'tcx> TypeErrCtxt<'_, 'tcx> { fn impl_similar_to( &self, @@ -275,6 +261,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } })); + flags.push((sym::This, Some(self.tcx.def_path_str(trait_pred.trait_ref.def_id)))); + if let Ok(Some(command)) = OnUnimplementedDirective::of_item(self.tcx, def_id) { command.evaluate(self.tcx, trait_pred.trait_ref, &flags, long_ty_file) } else { @@ -283,19 +271,23 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } } +/// Represents a format string in a on_unimplemented attribute, +/// like the "content" in `#[diagnostic::on_unimplemented(message = "content")]` #[derive(Clone, Debug)] pub struct OnUnimplementedFormatString { - symbol: Symbol, - span: Span, - is_diagnostic_namespace_variant: bool, + /// Symbol of the format string, i.e. `"content"` + pub symbol: Symbol, + ///The span of the format string, i.e. `"content"` + pub span: Span, + pub is_diagnostic_namespace_variant: bool, } #[derive(Debug)] pub struct OnUnimplementedDirective { - pub condition: Option, + pub condition: Option, pub subcommands: Vec, - pub message: Option, - pub label: Option, + pub message: Option<(Span, OnUnimplementedFormatString)>, + pub label: Option<(Span, OnUnimplementedFormatString)>, pub notes: Vec, pub parent_label: Option, pub append_const_msg: Option, @@ -332,12 +324,12 @@ impl<'tcx> OnUnimplementedDirective { let mut errored = None; let mut item_iter = items.iter(); - let parse_value = |value_str, value_span| { + let parse_value = |value_str, span| { OnUnimplementedFormatString::try_parse( tcx, item_def_id, value_str, - value_span, + span, is_diagnostic_namespace_variant, ) .map(Some) @@ -359,7 +351,7 @@ impl<'tcx> OnUnimplementedDirective { } true }); - Some(cond.clone()) + Some(Condition { inner: cond.clone() }) }; let mut message = None; @@ -369,24 +361,36 @@ impl<'tcx> OnUnimplementedDirective { let mut subcommands = vec![]; let mut append_const_msg = None; + let get_value_and_span = |item: &_, key| { + if let MetaItemInner::MetaItem(MetaItem { + path, + kind: MetaItemKind::NameValue(MetaItemLit { span, kind: LitKind::Str(s, _), .. }), + .. + }) = item + && *path == key + { + Some((*s, *span)) + } else { + None + } + }; + for item in item_iter { - if item.has_name(sym::message) && message.is_none() { - if let Some(message_) = item.value_str() { - message = parse_value(message_, item.span())?; - continue; - } - } else if item.has_name(sym::label) && label.is_none() { - if let Some(label_) = item.value_str() { - label = parse_value(label_, item.span())?; + if let Some((message_, span)) = get_value_and_span(item, sym::message) + && message.is_none() + { + message = parse_value(message_, span)?.map(|l| (item.span(), l)); + continue; + } else if let Some((label_, span)) = get_value_and_span(item, sym::label) + && label.is_none() + { + label = parse_value(label_, span)?.map(|l| (item.span(), l)); + continue; + } else if let Some((note_, span)) = get_value_and_span(item, sym::note) { + if let Some(note) = parse_value(note_, span)? { + notes.push(note); continue; } - } else if item.has_name(sym::note) { - if let Some(note_) = item.value_str() { - if let Some(note) = parse_value(note_, item.span())? { - notes.push(note); - continue; - } - } } else if item.has_name(sym::parent_label) && parent_label.is_none() && !is_diagnostic_namespace_variant @@ -479,15 +483,15 @@ impl<'tcx> OnUnimplementedDirective { IgnoredDiagnosticOption::maybe_emit_warning( tcx, item_def_id, - directive.message.as_ref().map(|f| f.span), - aggr.message.as_ref().map(|f| f.span), + directive.message.as_ref().map(|f| f.0), + aggr.message.as_ref().map(|f| f.0), "message", ); IgnoredDiagnosticOption::maybe_emit_warning( tcx, item_def_id, - directive.label.as_ref().map(|f| f.span), - aggr.label.as_ref().map(|f| f.span), + directive.label.as_ref().map(|f| f.0), + aggr.label.as_ref().map(|f| f.0), "label", ); IgnoredDiagnosticOption::maybe_emit_warning( @@ -561,13 +565,16 @@ impl<'tcx> OnUnimplementedDirective { condition: None, message: None, subcommands: vec![], - label: Some(OnUnimplementedFormatString::try_parse( - tcx, - item_def_id, - value, + label: Some(( attr.span(), - is_diagnostic_namespace_variant, - )?), + OnUnimplementedFormatString::try_parse( + tcx, + item_def_id, + value, + attr.value_span().unwrap_or(attr.span()), + is_diagnostic_namespace_variant, + )?, + )), notes: Vec::new(), parent_label: None, append_const_msg: None, @@ -643,27 +650,7 @@ impl<'tcx> OnUnimplementedDirective { for command in self.subcommands.iter().chain(Some(self)).rev() { debug!(?command); if let Some(ref condition) = command.condition - && !attr::eval_condition(condition, &tcx.sess, Some(tcx.features()), &mut |cfg| { - let value = cfg.value.map(|v| { - // `with_no_visible_paths` is also used when generating the options, - // so we need to match it here. - ty::print::with_no_visible_paths!( - OnUnimplementedFormatString { - symbol: v, - span: cfg.span, - is_diagnostic_namespace_variant: false - } - .format( - tcx, - trait_ref, - &options_map, - long_ty_file - ) - ) - }); - - options.contains(&(cfg.name, value)) - }) + && !condition.matches_predicate(tcx, options, &options_map) { debug!("evaluate: skipping {:?} due to condition", command); continue; @@ -687,8 +674,8 @@ impl<'tcx> OnUnimplementedDirective { } OnUnimplementedNote { - label: label.map(|l| l.format(tcx, trait_ref, &options_map, long_ty_file)), - message: message.map(|m| m.format(tcx, trait_ref, &options_map, long_ty_file)), + label: label.map(|l| l.1.format(tcx, trait_ref, &options_map, long_ty_file)), + message: message.map(|m| m.1.format(tcx, trait_ref, &options_map, long_ty_file)), notes: notes .into_iter() .map(|n| n.format(tcx, trait_ref, &options_map, long_ty_file)) @@ -705,144 +692,65 @@ impl<'tcx> OnUnimplementedFormatString { tcx: TyCtxt<'tcx>, item_def_id: DefId, from: Symbol, - value_span: Span, + span: Span, is_diagnostic_namespace_variant: bool, ) -> Result { - let result = OnUnimplementedFormatString { - symbol: from, - span: value_span, - is_diagnostic_namespace_variant, - }; + let result = + OnUnimplementedFormatString { symbol: from, span, is_diagnostic_namespace_variant }; result.verify(tcx, item_def_id)?; Ok(result) } fn verify(&self, tcx: TyCtxt<'tcx>, item_def_id: DefId) -> Result<(), ErrorGuaranteed> { - let trait_def_id = if tcx.is_trait(item_def_id) { - item_def_id + let trait_def_id = if tcx.is_trait(item_def_id) { item_def_id } else { return Ok(()) }; + + let ctx = if self.is_diagnostic_namespace_variant { + Ctx::DiagnosticOnUnimplemented { tcx, trait_def_id } } else { - tcx.trait_id_of_impl(item_def_id) - .expect("expected `on_unimplemented` to correspond to a trait") + Ctx::RustcOnUnimplemented { tcx, trait_def_id } }; - let trait_name = tcx.item_ident(trait_def_id); - let generics = tcx.generics_of(item_def_id); - let s = self.symbol.as_str(); - let mut parser = Parser::new(s, None, None, false, ParseMode::Format); + let mut result = Ok(()); - for token in &mut parser { - match token { - Piece::Lit(_) => (), // Normal string, no need to check it - Piece::NextArgument(a) => { - let format_spec = a.format; - if self.is_diagnostic_namespace_variant - && (format_spec.ty_span.is_some() - || format_spec.width_span.is_some() - || format_spec.precision_span.is_some() - || format_spec.fill_span.is_some()) - { + + match FormatString::parse(self.symbol, self.span, &ctx) { + // Warnings about format specifiers, deprecated parameters, wrong parameters etc. + // In other words we'd like to let the author know, but we can still try to format the string later + Ok(FormatString { warnings, .. }) => { + for w in warnings { + w.emit_warning(tcx, trait_def_id) + } + } + // Errors from the underlying `rustc_parse_format::Parser` + Err(errors) => { + // we cannot return errors from processing the format string as hard error here + // as the diagnostic namespace guarantees that malformed input cannot cause an error + // + // if we encounter any error while processing we nevertheless want to show it as warning + // so that users are aware that something is not correct + for e in errors { + if self.is_diagnostic_namespace_variant { if let Some(item_def_id) = item_def_id.as_local() { tcx.emit_node_span_lint( UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, tcx.local_def_id_to_hir_id(item_def_id), self.span, - InvalidFormatSpecifier, + WrappedParserError { description: e.description, label: e.label }, ); } - } - match a.position { - Position::ArgumentNamed(s) => { - match Symbol::intern(s) { - // `{ThisTraitsName}` is allowed - s if s == trait_name.name - && !self.is_diagnostic_namespace_variant => - { - () - } - s if ALLOWED_FORMAT_SYMBOLS.contains(&s) - && !self.is_diagnostic_namespace_variant => - { - () - } - // So is `{A}` if A is a type parameter - s if generics.own_params.iter().any(|param| param.name == s) => (), - s => { - if self.is_diagnostic_namespace_variant { - if let Some(item_def_id) = item_def_id.as_local() { - tcx.emit_node_span_lint( - UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, - tcx.local_def_id_to_hir_id(item_def_id), - self.span, - UnknownFormatParameterForOnUnimplementedAttr { - argument_name: s, - trait_name, - }, - ); - } - } else { - result = Err(struct_span_code_err!( - tcx.dcx(), - self.span, - E0230, - "there is no parameter `{}` on {}", - s, - if trait_def_id == item_def_id { - format!("trait `{trait_name}`") - } else { - "impl".to_string() - } - ) - .emit()); - } - } - } - } - // `{:1}` and `{}` are not to be used - Position::ArgumentIs(..) | Position::ArgumentImplicitlyIs(_) => { - if self.is_diagnostic_namespace_variant { - if let Some(item_def_id) = item_def_id.as_local() { - tcx.emit_node_span_lint( - UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, - tcx.local_def_id_to_hir_id(item_def_id), - self.span, - DisallowedPositionalArgument, - ); - } - } else { - let reported = struct_span_code_err!( - tcx.dcx(), - self.span, - E0231, - "only named generic parameters are allowed" - ) - .emit(); - result = Err(reported); - } - } + } else { + let reported = struct_span_code_err!( + tcx.dcx(), + self.span, + E0231, + "{}", + e.description, + ) + .emit(); + result = Err(reported); } } } } - // we cannot return errors from processing the format string as hard error here - // as the diagnostic namespace guarantees that malformed input cannot cause an error - // - // if we encounter any error while processing we nevertheless want to show it as warning - // so that users are aware that something is not correct - for e in parser.errors { - if self.is_diagnostic_namespace_variant { - if let Some(item_def_id) = item_def_id.as_local() { - tcx.emit_node_span_lint( - UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, - tcx.local_def_id_to_hir_id(item_def_id), - self.span, - WrappedParserError { description: e.description, label: e.label }, - ); - } - } else { - let reported = - struct_span_code_err!(tcx.dcx(), self.span, E0231, "{}", e.description,).emit(); - result = Err(reported); - } - } result } @@ -854,95 +762,26 @@ impl<'tcx> OnUnimplementedFormatString { options: &FxHashMap, long_ty_file: &mut Option, ) -> String { - let name = tcx.item_name(trait_ref.def_id); - let trait_str = tcx.def_path_str(trait_ref.def_id); - let generics = tcx.generics_of(trait_ref.def_id); - let generic_map = generics - .own_params - .iter() - .filter_map(|param| { - let value = match param.kind { - GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => { - if let Some(ty) = trait_ref.args[param.index as usize].as_type() { - tcx.short_string(ty, long_ty_file) - } else { - trait_ref.args[param.index as usize].to_string() - } - } - GenericParamDefKind::Lifetime => return None, - }; - let name = param.name; - Some((name, value)) - }) - .collect::>(); - let empty_string = String::new(); - - let s = self.symbol.as_str(); - let mut parser = Parser::new(s, None, None, false, ParseMode::Format); - let item_context = (options.get(&sym::ItemContext)).unwrap_or(&empty_string); - let constructed_message = (&mut parser) - .map(|p| match p { - Piece::Lit(s) => s.to_owned(), - Piece::NextArgument(a) => match a.position { - Position::ArgumentNamed(arg) => { - let s = Symbol::intern(arg); - match generic_map.get(&s) { - Some(val) => val.to_string(), - None if self.is_diagnostic_namespace_variant => { - format!("{{{arg}}}") - } - None if s == name => trait_str.clone(), - None => { - if let Some(val) = options.get(&s) { - val.clone() - } else if s == sym::from_desugaring { - // don't break messages using these two arguments incorrectly - String::new() - } else if s == sym::ItemContext - && !self.is_diagnostic_namespace_variant - { - item_context.clone() - } else if s == sym::integral { - String::from("{integral}") - } else if s == sym::integer_ { - String::from("{integer}") - } else if s == sym::float { - String::from("{float}") - } else { - bug!( - "broken on_unimplemented {:?} for {:?}: \ - no argument matching {:?}", - self.symbol, - trait_ref, - s - ) - } - } - } - } - Position::ArgumentImplicitlyIs(_) if self.is_diagnostic_namespace_variant => { - String::from("{}") - } - Position::ArgumentIs(idx) if self.is_diagnostic_namespace_variant => { - format!("{{{idx}}}") - } - _ => bug!("broken on_unimplemented {:?} - bad format arg", self.symbol), - }, - }) - .collect(); - // we cannot return errors from processing the format string as hard error here - // as the diagnostic namespace guarantees that malformed input cannot cause an error - // - // if we encounter any error while processing the format string - // we don't want to show the potentially half assembled formatted string, - // therefore we fall back to just showing the input string in this case - // - // The actual parser errors are emitted earlier - // as lint warnings in OnUnimplementedFormatString::verify - if self.is_diagnostic_namespace_variant && !parser.errors.is_empty() { - String::from(s) + let trait_def_id = trait_ref.def_id; + let ctx = if self.is_diagnostic_namespace_variant { + Ctx::DiagnosticOnUnimplemented { tcx, trait_def_id } + } else { + Ctx::RustcOnUnimplemented { tcx, trait_def_id } + }; + + if let Ok(s) = FormatString::parse(self.symbol, self.span, &ctx) { + s.format(tcx, trait_ref, options, long_ty_file) } else { - constructed_message + // we cannot return errors from processing the format string as hard error here + // as the diagnostic namespace guarantees that malformed input cannot cause an error + // + // if we encounter any error while processing the format string + // we don't want to show the potentially half assembled formatted string, + // therefore we fall back to just showing the input string in this case + // + // The actual parser errors are emitted earlier + // as lint warnings in OnUnimplementedFormatString::verify + self.symbol.as_str().into() } } } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_condition.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_condition.rs new file mode 100644 index 0000000000000..4c852c1023a10 --- /dev/null +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_condition.rs @@ -0,0 +1,64 @@ +use rustc_ast::MetaItemInner; +use rustc_attr_parsing as attr; +use rustc_data_structures::fx::FxHashMap; +use rustc_middle::ty::{self, TyCtxt}; +use rustc_parse_format::{ParseMode, Parser, Piece, Position}; +use rustc_span::{Span, Symbol, sym}; + +pub static ALLOWED_CONDITION_SYMBOLS: &[Symbol] = &[ + sym::from_desugaring, + sym::direct, + sym::cause, + sym::integral, + sym::integer_, + sym::float, + sym::_Self, + sym::crate_local, +]; + +#[derive(Debug)] +pub struct Condition { + pub inner: MetaItemInner, +} + +impl Condition { + pub fn span(&self) -> Span { + self.inner.span() + } + + pub fn matches_predicate<'tcx>( + &self, + tcx: TyCtxt<'tcx>, + options: &[(Symbol, Option)], + options_map: &FxHashMap, + ) -> bool { + attr::eval_condition(&self.inner, tcx.sess, Some(tcx.features()), &mut |cfg| { + let value = cfg.value.map(|v| { + // `with_no_visible_paths` is also used when generating the options, + // so we need to match it here. + ty::print::with_no_visible_paths!({ + let mut parser = Parser::new(v.as_str(), None, None, false, ParseMode::Format); + let constructed_message = (&mut parser) + .map(|p| match p { + Piece::Lit(s) => s.to_owned(), + Piece::NextArgument(a) => match a.position { + Position::ArgumentNamed(arg) => { + let s = Symbol::intern(arg); + match options_map.get(&s) { + Some(val) => val.to_string(), + None => format!("{{{arg}}}"), + } + } + Position::ArgumentImplicitlyIs(_) => String::from("{}"), + Position::ArgumentIs(idx) => format!("{{{idx}}}"), + }, + }) + .collect(); + constructed_message + }) + }); + + options.contains(&(cfg.name, value)) + }) + } +} diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs index 40a47921fc11a..21db207496cac 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs @@ -1,3 +1,347 @@ +use std::fmt::Write; +use std::path::PathBuf; + +use errors::*; +use rustc_data_structures::fx::FxHashMap; +use rustc_middle::span_bug; +use rustc_middle::ty::{self, GenericParamDefKind, TyCtxt}; +use rustc_parse_format::{ + Alignment, Argument, Count, FormatSpec, InnerSpan, ParseError, ParseMode, Parser, + Piece as RpfPiece, Position, +}; +use rustc_session::lint::builtin::UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES; +use rustc_span::def_id::DefId; +use rustc_span::{BytePos, Pos, Span, Symbol, kw, sym}; + +pub struct FormatString { + input: Symbol, + input_span: Span, + pieces: Vec, + // the formatting string was parsed succesfully but with warnings + pub warnings: Vec, +} + +enum Piece { + Lit(String), + Arg(FormatArg), +} + +pub enum FormatArg { + // A generic parameter, like `{T}` if we're on the `From` trait. + GenericParam { generic_param: Symbol, span: Span }, + // `{Self}` + SelfUpper, + This, + Trait, + ItemContext, + AsIs(String), +} + +pub enum Ctx<'tcx> { + // `#[rustc_on_unimplemented]` + RustcOnUnimplemented { tcx: TyCtxt<'tcx>, trait_def_id: DefId }, + // `#[diagnostic::...]` + DiagnosticOnUnimplemented { tcx: TyCtxt<'tcx>, trait_def_id: DefId }, +} + +pub enum FormatWarning { + UnknownParam { argument_name: Symbol, span: Span }, + PositionalArgument { span: Span, help: String }, + InvalidSpecifier { name: String, span: Span }, + FutureIncompat { span: Span, help: String }, +} + +impl FormatWarning { + pub fn emit_warning<'tcx>(&self, tcx: TyCtxt<'tcx>, item_def_id: DefId) { + match *self { + FormatWarning::UnknownParam { argument_name, span } => { + let this = tcx.item_ident(item_def_id); + if let Some(item_def_id) = item_def_id.as_local() { + tcx.emit_node_span_lint( + UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, + tcx.local_def_id_to_hir_id(item_def_id), + span, + UnknownFormatParameterForOnUnimplementedAttr { + argument_name, + trait_name: this, + }, + ); + } + } + FormatWarning::PositionalArgument { span, .. } => { + if let Some(item_def_id) = item_def_id.as_local() { + tcx.emit_node_span_lint( + UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, + tcx.local_def_id_to_hir_id(item_def_id), + span, + DisallowedPositionalArgument, + ); + } + } + FormatWarning::InvalidSpecifier { span, .. } => { + if let Some(item_def_id) = item_def_id.as_local() { + tcx.emit_node_span_lint( + UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, + tcx.local_def_id_to_hir_id(item_def_id), + span, + InvalidFormatSpecifier, + ); + } + } + FormatWarning::FutureIncompat { .. } => { + // We've never deprecated anything in diagnostic namespace format strings + // but if we do we will emit a warning here + + // FIXME(mejrs) in a couple releases, start emitting warnings for + // #[rustc_on_unimplemented] deprecated args + } + } + } +} + +impl FormatString { + pub fn parse(input: Symbol, input_span: Span, ctx: &Ctx<'_>) -> Result> { + let s = input.as_str(); + let mut parser = Parser::new(s, None, None, false, ParseMode::Format); + let mut pieces = Vec::new(); + let mut warnings = Vec::new(); + + for piece in &mut parser { + match piece { + RpfPiece::Lit(lit) => { + pieces.push(Piece::Lit(lit.into())); + } + RpfPiece::NextArgument(arg) => { + warn_on_format_spec(arg.format, &mut warnings, input_span); + let arg = parse_arg(&arg, ctx, &mut warnings, input_span); + pieces.push(Piece::Arg(arg)); + } + } + } + + if parser.errors.is_empty() { + Ok(FormatString { input, input_span, pieces, warnings }) + } else { + Err(parser.errors) + } + } + + pub fn format<'tcx>( + &self, + tcx: TyCtxt<'tcx>, + trait_ref: ty::TraitRef<'tcx>, + options: &FxHashMap, + long_ty_file: &mut Option, + ) -> String { + let generics = tcx.generics_of(trait_ref.def_id); + let generic_map = generics + .own_params + .iter() + .filter_map(|param| { + let value = match param.kind { + GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => { + if let Some(ty) = trait_ref.args[param.index as usize].as_type() { + tcx.short_string(ty, long_ty_file) + } else { + trait_ref.args[param.index as usize].to_string() + } + } + GenericParamDefKind::Lifetime => return None, + }; + let name = param.name; + Some((name, value)) + }) + .collect::>(); + + let mut ret = String::new(); + for piece in &self.pieces { + match piece { + Piece::Lit(s) | Piece::Arg(FormatArg::AsIs(s)) => ret.push_str(&s), + + // `A` if we have `trait Trait {}` and `note = "i'm the actual type of {A}"` + Piece::Arg(FormatArg::GenericParam { generic_param, span }) => { + // Should always be some but we can't raise errors here + if let Some(value) = generic_map.get(&generic_param) { + ret.push_str(value); + } else if cfg!(debug_assertions) { + span_bug!(*span, "invalid generic parameter"); + } else { + let _ = ret.write_fmt(format_args!("{{{}}}", generic_param.as_str())); + } + } + // `{Self}` + Piece::Arg(FormatArg::SelfUpper) => { + let Some(slf) = generic_map.get(&kw::SelfUpper) else { + span_bug!( + self.input_span, + "broken format string {:?} for {:?}: \ + no argument matching `Self`", + self.input, + trait_ref, + ) + }; + ret.push_str(&slf); + } + + // It's only `rustc_onunimplemented` from here + Piece::Arg(FormatArg::This) => { + let Some(this) = options.get(&sym::This) else { + span_bug!( + self.input_span, + "broken format string {:?} for {:?}: \ + no argument matching This", + self.input, + trait_ref, + ) + }; + ret.push_str(this); + } + Piece::Arg(FormatArg::Trait) => { + let Some(this) = options.get(&sym::Trait) else { + span_bug!( + self.input_span, + "broken format string {:?} for {:?}: \ + no argument matching Trait", + self.input, + trait_ref, + ) + }; + ret.push_str(this); + } + Piece::Arg(FormatArg::ItemContext) => { + let itemcontext = options.get(&sym::ItemContext); + ret.push_str(itemcontext.unwrap_or(&String::new())); + } + } + } + ret + } +} + +fn parse_arg( + arg: &Argument<'_>, + ctx: &Ctx<'_>, + warnings: &mut Vec, + input_span: Span, +) -> FormatArg { + let (Ctx::RustcOnUnimplemented { tcx, trait_def_id } + | Ctx::DiagnosticOnUnimplemented { tcx, trait_def_id }) = ctx; + let trait_name = tcx.item_ident(*trait_def_id); + let generics = tcx.generics_of(trait_def_id); + let span = slice_span(input_span, arg.position_span); + + match arg.position { + // Something like "hello {name}" + Position::ArgumentNamed(name) => match (ctx, Symbol::intern(name)) { + // accepted, but deprecated + (Ctx::RustcOnUnimplemented { .. }, sym::_Self) => { + warnings + .push(FormatWarning::FutureIncompat { span, help: String::from("use {Self}") }); + FormatArg::SelfUpper + } + ( + Ctx::RustcOnUnimplemented { .. }, + sym::from_desugaring + | sym::crate_local + | sym::direct + | sym::cause + | sym::float + | sym::integer_ + | sym::integral, + ) => { + warnings.push(FormatWarning::FutureIncompat { + span, + help: String::from("don't use this in a format string"), + }); + FormatArg::AsIs(String::new()) + } + + // Only `#[rustc_on_unimplemented]` can use these + (Ctx::RustcOnUnimplemented { .. }, sym::ItemContext) => FormatArg::ItemContext, + (Ctx::RustcOnUnimplemented { .. }, sym::This) => FormatArg::This, + (Ctx::RustcOnUnimplemented { .. }, sym::Trait) => FormatArg::Trait, + // `{ThisTraitsName}`. Some attrs in std use this, but I'd like to change it to the more general `{This}` + // because that'll be simpler to parse and extend in the future + (Ctx::RustcOnUnimplemented { .. }, name) if name == trait_name.name => { + warnings + .push(FormatWarning::FutureIncompat { span, help: String::from("use {This}") }); + FormatArg::This + } + + // Any attribute can use these + ( + Ctx::RustcOnUnimplemented { .. } | Ctx::DiagnosticOnUnimplemented { .. }, + kw::SelfUpper, + ) => FormatArg::SelfUpper, + ( + Ctx::RustcOnUnimplemented { .. } | Ctx::DiagnosticOnUnimplemented { .. }, + generic_param, + ) if generics.own_params.iter().any(|param| param.name == generic_param) => { + FormatArg::GenericParam { generic_param, span } + } + + (_, argument_name) => { + warnings.push(FormatWarning::UnknownParam { argument_name, span }); + FormatArg::AsIs(format!("{{{}}}", argument_name.as_str())) + } + }, + + // `{:1}` and `{}` are ignored + Position::ArgumentIs(idx) => { + warnings.push(FormatWarning::PositionalArgument { + span, + help: format!("use `{{{idx}}}` to print a number in braces"), + }); + FormatArg::AsIs(format!("{{{idx}}}")) + } + Position::ArgumentImplicitlyIs(_) => { + warnings.push(FormatWarning::PositionalArgument { + span, + help: String::from("use `{{}}` to print empty braces"), + }); + FormatArg::AsIs(String::from("{}")) + } + } +} + +/// `#[rustc_on_unimplemented]` and `#[diagnostic::...]` don't actually do anything +/// with specifiers, so emit a warning if they are used. +fn warn_on_format_spec(spec: FormatSpec<'_>, warnings: &mut Vec, input_span: Span) { + if !matches!( + spec, + FormatSpec { + fill: None, + fill_span: None, + align: Alignment::AlignUnknown, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, + precision: Count::CountImplied, + precision_span: None, + width: Count::CountImplied, + width_span: None, + ty: _, + ty_span: _, + }, + ) { + let span = spec.ty_span.map(|inner| slice_span(input_span, inner)).unwrap_or(input_span); + warnings.push(FormatWarning::InvalidSpecifier { span, name: spec.ty.into() }) + } +} + +fn slice_span(input: Span, inner: InnerSpan) -> Span { + let InnerSpan { start, end } = inner; + let span = input.data(); + + Span::new( + span.lo + BytePos::from_usize(start), + span.lo + BytePos::from_usize(end), + span.ctxt, + span.parent, + ) +} + pub mod errors { use rustc_macros::LintDiagnostic; use rustc_middle::ty::TyCtxt; diff --git a/tests/ui/diagnostic_namespace/on_unimplemented/broken_format.stderr b/tests/ui/diagnostic_namespace/on_unimplemented/broken_format.stderr index 7fd51c7527f92..a82a1e78da0cf 100644 --- a/tests/ui/diagnostic_namespace/on_unimplemented/broken_format.stderr +++ b/tests/ui/diagnostic_namespace/on_unimplemented/broken_format.stderr @@ -1,52 +1,52 @@ warning: unmatched `}` found - --> $DIR/broken_format.rs:2:32 + --> $DIR/broken_format.rs:2:42 | LL | #[diagnostic::on_unimplemented(message = "{{Test } thing")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^ | = note: `#[warn(unknown_or_malformed_diagnostic_attributes)]` on by default warning: positional format arguments are not allowed here - --> $DIR/broken_format.rs:7:32 + --> $DIR/broken_format.rs:7:49 | LL | #[diagnostic::on_unimplemented(message = "Test {}")] - | ^^^^^^^^^^^^^^^^^^^ + | ^ | = help: only named format arguments with the name of one of the generic types are allowed in this context warning: positional format arguments are not allowed here - --> $DIR/broken_format.rs:12:32 + --> $DIR/broken_format.rs:12:49 | LL | #[diagnostic::on_unimplemented(message = "Test {1:}")] - | ^^^^^^^^^^^^^^^^^^^^^ + | ^ | = help: only named format arguments with the name of one of the generic types are allowed in this context warning: invalid format specifier - --> $DIR/broken_format.rs:17:32 + --> $DIR/broken_format.rs:17:42 | LL | #[diagnostic::on_unimplemented(message = "Test {Self:123}")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^ | = help: no format specifier are supported in this position warning: expected `}`, found `!` - --> $DIR/broken_format.rs:22:32 + --> $DIR/broken_format.rs:22:42 | LL | #[diagnostic::on_unimplemented(message = "Test {Self:!}")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ warning: unmatched `}` found - --> $DIR/broken_format.rs:22:32 + --> $DIR/broken_format.rs:22:42 | LL | #[diagnostic::on_unimplemented(message = "Test {Self:!}")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ warning: unmatched `}` found - --> $DIR/broken_format.rs:2:32 + --> $DIR/broken_format.rs:2:42 | LL | #[diagnostic::on_unimplemented(message = "{{Test } thing")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` @@ -70,10 +70,10 @@ LL | fn check_1(_: impl ImportantTrait1) {} | ^^^^^^^^^^^^^^^ required by this bound in `check_1` warning: positional format arguments are not allowed here - --> $DIR/broken_format.rs:7:32 + --> $DIR/broken_format.rs:7:49 | LL | #[diagnostic::on_unimplemented(message = "Test {}")] - | ^^^^^^^^^^^^^^^^^^^ + | ^ | = help: only named format arguments with the name of one of the generic types are allowed in this context = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` @@ -98,10 +98,10 @@ LL | fn check_2(_: impl ImportantTrait2) {} | ^^^^^^^^^^^^^^^ required by this bound in `check_2` warning: positional format arguments are not allowed here - --> $DIR/broken_format.rs:12:32 + --> $DIR/broken_format.rs:12:49 | LL | #[diagnostic::on_unimplemented(message = "Test {1:}")] - | ^^^^^^^^^^^^^^^^^^^^^ + | ^ | = help: only named format arguments with the name of one of the generic types are allowed in this context = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` @@ -126,10 +126,10 @@ LL | fn check_3(_: impl ImportantTrait3) {} | ^^^^^^^^^^^^^^^ required by this bound in `check_3` warning: invalid format specifier - --> $DIR/broken_format.rs:17:32 + --> $DIR/broken_format.rs:17:42 | LL | #[diagnostic::on_unimplemented(message = "Test {Self:123}")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^ | = help: no format specifier are supported in this position = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` @@ -154,18 +154,18 @@ LL | fn check_4(_: impl ImportantTrait4) {} | ^^^^^^^^^^^^^^^ required by this bound in `check_4` warning: expected `}`, found `!` - --> $DIR/broken_format.rs:22:32 + --> $DIR/broken_format.rs:22:42 | LL | #[diagnostic::on_unimplemented(message = "Test {Self:!}")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: unmatched `}` found - --> $DIR/broken_format.rs:22:32 + --> $DIR/broken_format.rs:22:42 | LL | #[diagnostic::on_unimplemented(message = "Test {Self:!}")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/diagnostic_namespace/on_unimplemented/do_not_accept_options_of_the_internal_rustc_attribute.stderr b/tests/ui/diagnostic_namespace/on_unimplemented/do_not_accept_options_of_the_internal_rustc_attribute.stderr index bb455d929406d..88816a98dcf00 100644 --- a/tests/ui/diagnostic_namespace/on_unimplemented/do_not_accept_options_of_the_internal_rustc_attribute.stderr +++ b/tests/ui/diagnostic_namespace/on_unimplemented/do_not_accept_options_of_the_internal_rustc_attribute.stderr @@ -39,82 +39,82 @@ LL | #[diagnostic::on_unimplemented = "Message"] = help: only `message`, `note` and `label` are allowed as options warning: there is no parameter `from_desugaring` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:17 | LL | message = "{from_desugaring}{direct}{cause}{integral}{integer}", - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument warning: there is no parameter `direct` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:34 | LL | message = "{from_desugaring}{direct}{cause}{integral}{integer}", - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument warning: there is no parameter `cause` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:42 | LL | message = "{from_desugaring}{direct}{cause}{integral}{integer}", - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument warning: there is no parameter `integral` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:49 | LL | message = "{from_desugaring}{direct}{cause}{integral}{integer}", - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument warning: there is no parameter `integer` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:59 | LL | message = "{from_desugaring}{direct}{cause}{integral}{integer}", - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument warning: there is no parameter `float` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:15 | LL | label = "{float}{_Self}{crate_local}{Trait}{ItemContext}" - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument warning: there is no parameter `_Self` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:22 | LL | label = "{float}{_Self}{crate_local}{Trait}{ItemContext}" - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument warning: there is no parameter `crate_local` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:29 | LL | label = "{float}{_Self}{crate_local}{Trait}{ItemContext}" - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument warning: there is no parameter `Trait` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:42 | LL | label = "{float}{_Self}{crate_local}{Trait}{ItemContext}" - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument warning: there is no parameter `ItemContext` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:49 | LL | label = "{float}{_Self}{crate_local}{Trait}{ItemContext}" - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument @@ -191,91 +191,91 @@ LL | fn takes_bar(_: impl Bar) {} | ^^^ required by this bound in `takes_bar` warning: there is no parameter `from_desugaring` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:17 | LL | message = "{from_desugaring}{direct}{cause}{integral}{integer}", - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: there is no parameter `direct` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:34 | LL | message = "{from_desugaring}{direct}{cause}{integral}{integer}", - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: there is no parameter `cause` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:42 | LL | message = "{from_desugaring}{direct}{cause}{integral}{integer}", - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: there is no parameter `integral` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:49 | LL | message = "{from_desugaring}{direct}{cause}{integral}{integer}", - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: there is no parameter `integer` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:33:59 | LL | message = "{from_desugaring}{direct}{cause}{integral}{integer}", - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: there is no parameter `float` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:15 | LL | label = "{float}{_Self}{crate_local}{Trait}{ItemContext}" - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: there is no parameter `_Self` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:22 | LL | label = "{float}{_Self}{crate_local}{Trait}{ItemContext}" - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: there is no parameter `crate_local` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:29 | LL | label = "{float}{_Self}{crate_local}{Trait}{ItemContext}" - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: there is no parameter `Trait` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:42 | LL | label = "{float}{_Self}{crate_local}{Trait}{ItemContext}" - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: there is no parameter `ItemContext` on trait `Baz` - --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:5 + --> $DIR/do_not_accept_options_of_the_internal_rustc_attribute.rs:44:49 | LL | label = "{float}{_Self}{crate_local}{Trait}{ItemContext}" - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/diagnostic_namespace/on_unimplemented/do_not_fail_parsing_on_invalid_options_1.stderr b/tests/ui/diagnostic_namespace/on_unimplemented/do_not_fail_parsing_on_invalid_options_1.stderr index 11263580b15e2..4dd8c1afca020 100644 --- a/tests/ui/diagnostic_namespace/on_unimplemented/do_not_fail_parsing_on_invalid_options_1.stderr +++ b/tests/ui/diagnostic_namespace/on_unimplemented/do_not_fail_parsing_on_invalid_options_1.stderr @@ -47,10 +47,10 @@ LL | #[diagnostic::on_unimplemented] = help: at least one of the `message`, `note` and `label` options are expected warning: there is no parameter `DoesNotExist` on trait `Test` - --> $DIR/do_not_fail_parsing_on_invalid_options_1.rs:31:32 + --> $DIR/do_not_fail_parsing_on_invalid_options_1.rs:31:44 | LL | #[diagnostic::on_unimplemented(message = "{DoesNotExist}")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument @@ -167,10 +167,10 @@ LL | fn take_whatever(_: impl Whatever) {} | ^^^^^^^^ required by this bound in `take_whatever` warning: there is no parameter `DoesNotExist` on trait `Test` - --> $DIR/do_not_fail_parsing_on_invalid_options_1.rs:31:32 + --> $DIR/do_not_fail_parsing_on_invalid_options_1.rs:31:44 | LL | #[diagnostic::on_unimplemented(message = "{DoesNotExist}")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = help: expect either a generic argument name or `{Self}` as format argument = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` diff --git a/tests/ui/on-unimplemented/bad-annotation.rs b/tests/ui/on-unimplemented/bad-annotation.rs index 3f0f69749bf72..0936b25847c4c 100644 --- a/tests/ui/on-unimplemented/bad-annotation.rs +++ b/tests/ui/on-unimplemented/bad-annotation.rs @@ -20,12 +20,12 @@ trait BadAnnotation1 {} #[rustc_on_unimplemented = "Unimplemented trait error on `{Self}` with params `<{A},{B},{C}>`"] -//~^ ERROR there is no parameter `C` on trait `BadAnnotation2` +//~^ WARNING there is no parameter `C` on trait `BadAnnotation2` trait BadAnnotation2 {} #[rustc_on_unimplemented = "Unimplemented trait error on `{Self}` with params `<{A},{B},{}>`"] -//~^ ERROR only named generic parameters are allowed +//~^ ERROR positional format arguments are not allowed here trait BadAnnotation3 {} diff --git a/tests/ui/on-unimplemented/bad-annotation.stderr b/tests/ui/on-unimplemented/bad-annotation.stderr index 4ceea779b29dc..1fefd93aa7ecb 100644 --- a/tests/ui/on-unimplemented/bad-annotation.stderr +++ b/tests/ui/on-unimplemented/bad-annotation.stderr @@ -11,17 +11,22 @@ LL | #[rustc_on_unimplemented = "message"] LL | #[rustc_on_unimplemented(/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...")] | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -error[E0230]: there is no parameter `C` on trait `BadAnnotation2` - --> $DIR/bad-annotation.rs:22:1 +warning: there is no parameter `C` on trait `BadAnnotation2` + --> $DIR/bad-annotation.rs:22:90 | LL | #[rustc_on_unimplemented = "Unimplemented trait error on `{Self}` with params `<{A},{B},{C}>`"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^ + | + = help: expect either a generic argument name or `{Self}` as format argument + = note: `#[warn(unknown_or_malformed_diagnostic_attributes)]` on by default -error[E0231]: only named generic parameters are allowed - --> $DIR/bad-annotation.rs:27:1 +warning: positional format arguments are not allowed here + --> $DIR/bad-annotation.rs:27:90 | LL | #[rustc_on_unimplemented = "Unimplemented trait error on `{Self}` with params `<{A},{B},{}>`"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^ + | + = help: only named format arguments with the name of one of the generic types are allowed in this context error[E0232]: this attribute must have a valid value --> $DIR/bad-annotation.rs:32:26 @@ -77,7 +82,6 @@ LL | #[rustc_on_unimplemented(on(desugared, on(desugared, message="x")), message | = note: eg `#[rustc_on_unimplemented(message="foo")]` -error: aborting due to 10 previous errors +error: aborting due to 8 previous errors; 2 warnings emitted -Some errors have detailed explanations: E0230, E0231, E0232. -For more information about an error, try `rustc --explain E0230`. +For more information about this error, try `rustc --explain E0232`. diff --git a/tests/ui/on-unimplemented/impl-substs.stderr b/tests/ui/on-unimplemented/impl-substs.stderr index b85d45eba5bbc..0eabe9714922c 100644 --- a/tests/ui/on-unimplemented/impl-substs.stderr +++ b/tests/ui/on-unimplemented/impl-substs.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `(i32, i32, i32): Foo` is not satisfied --> $DIR/impl-substs.rs:13:23 | LL | Foo::::foo((1i32, 1i32, 1i32)); - | ----------------- ^^^^^^^^^^^^^^^^^^ an impl did not match: usize _ _ + | ----------------- ^^^^^^^^^^^^^^^^^^ an impl did not match: usize {B} {C} | | | required by a bound introduced by this call | From ba9f51b05503a567cb637db03eaa943c59e36922 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 27 Mar 2025 23:09:44 +0100 Subject: [PATCH 075/266] Parse condition options into a struct --- .../traits/on_unimplemented.rs | 178 ++++++++++-------- .../traits/on_unimplemented_condition.rs | 45 +++-- .../traits/on_unimplemented_format.rs | 110 ++++------- 3 files changed, 168 insertions(+), 165 deletions(-) diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs index 6a7f32234213f..7d8ecba3b2e09 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs @@ -2,14 +2,13 @@ use std::iter; use std::path::PathBuf; use rustc_ast::{LitKind, MetaItem, MetaItemInner, MetaItemKind, MetaItemLit}; -use rustc_data_structures::fx::FxHashMap; use rustc_errors::codes::*; use rustc_errors::{ErrorGuaranteed, struct_span_code_err}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{AttrArgs, Attribute}; use rustc_middle::bug; -use rustc_middle::ty::print::PrintTraitRefExt as _; -use rustc_middle::ty::{self, GenericArgsRef, GenericParamDefKind, TyCtxt}; +use rustc_middle::ty::print::PrintTraitRefExt; +use rustc_middle::ty::{self, GenericArgsRef, GenericParamDef, GenericParamDefKind, TyCtxt}; use rustc_session::lint::builtin::UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES; use rustc_span::{Span, Symbol, sym}; use tracing::{debug, info}; @@ -17,9 +16,9 @@ use {rustc_attr_parsing as attr, rustc_hir as hir}; use super::{ObligationCauseCode, PredicateObligation}; use crate::error_reporting::TypeErrCtxt; -use crate::error_reporting::traits::on_unimplemented_condition::Condition; +use crate::error_reporting::traits::on_unimplemented_condition::{Condition, ConditionOptions}; use crate::error_reporting::traits::on_unimplemented_format::errors::*; -use crate::error_reporting::traits::on_unimplemented_format::{Ctx, FormatString}; +use crate::error_reporting::traits::on_unimplemented_format::{Ctx, FormatArgs, FormatString}; use crate::errors::{ EmptyOnClauseInOnUnimplemented, InvalidOnClauseInOnUnimplemented, NoValueInOnUnimplemented, }; @@ -107,86 +106,81 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { .unwrap_or_else(|| (trait_pred.def_id(), trait_pred.skip_binder().trait_ref.args)); let trait_pred = trait_pred.skip_binder(); - let mut flags = vec![]; + let mut self_types = vec![]; + let mut generic_args: Vec<(Symbol, String)> = vec![]; + let mut crate_local = false; // FIXME(-Zlower-impl-trait-in-trait-to-assoc-ty): HIR is not present for RPITITs, // but I guess we could synthesize one here. We don't see any errors that rely on // that yet, though. - let enclosure = self.describe_enclosure(obligation.cause.body_id).map(|t| t.to_owned()); - flags.push((sym::ItemContext, enclosure)); + let item_context = self + .describe_enclosure(obligation.cause.body_id) + .map(|t| t.to_owned()) + .unwrap_or(String::new()); - match obligation.cause.code() { + let direct = match obligation.cause.code() { ObligationCauseCode::BuiltinDerived(..) | ObligationCauseCode::ImplDerived(..) - | ObligationCauseCode::WellFormedDerived(..) => {} + | ObligationCauseCode::WellFormedDerived(..) => false, _ => { // this is a "direct", user-specified, rather than derived, // obligation. - flags.push((sym::direct, None)); + true } - } - - if let Some(k) = obligation.cause.span.desugaring_kind() { - flags.push((sym::from_desugaring, None)); - flags.push((sym::from_desugaring, Some(format!("{k:?}")))); - } + }; - if let ObligationCauseCode::MainFunctionType = obligation.cause.code() { - flags.push((sym::cause, Some("MainFunctionType".to_string()))); - } + let from_desugaring = obligation.cause.span.desugaring_kind().map(|k| format!("{k:?}")); - flags.push((sym::Trait, Some(trait_pred.trait_ref.print_trait_sugared().to_string()))); + let cause = if let ObligationCauseCode::MainFunctionType = obligation.cause.code() { + Some("MainFunctionType".to_string()) + } else { + None + }; // Add all types without trimmed paths or visible paths, ensuring they end up with // their "canonical" def path. ty::print::with_no_trimmed_paths!(ty::print::with_no_visible_paths!({ let generics = self.tcx.generics_of(def_id); let self_ty = trait_pred.self_ty(); - // This is also included through the generics list as `Self`, - // but the parser won't allow you to use it - flags.push((sym::_Self, Some(self_ty.to_string()))); + self_types.push(self_ty.to_string()); if let Some(def) = self_ty.ty_adt_def() { // We also want to be able to select self's original // signature with no type arguments resolved - flags.push(( - sym::_Self, - Some(self.tcx.type_of(def.did()).instantiate_identity().to_string()), - )); + self_types.push(self.tcx.type_of(def.did()).instantiate_identity().to_string()); } - for param in generics.own_params.iter() { - let value = match param.kind { + for GenericParamDef { name, kind, index, .. } in generics.own_params.iter() { + let value = match kind { GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => { - args[param.index as usize].to_string() + args[*index as usize].to_string() } GenericParamDefKind::Lifetime => continue, }; - let name = param.name; - flags.push((name, Some(value))); + generic_args.push((*name, value)); - if let GenericParamDefKind::Type { .. } = param.kind { - let param_ty = args[param.index as usize].expect_ty(); + if let GenericParamDefKind::Type { .. } = kind { + let param_ty = args[*index as usize].expect_ty(); if let Some(def) = param_ty.ty_adt_def() { // We also want to be able to select the parameter's // original signature with no type arguments resolved - flags.push(( - name, - Some(self.tcx.type_of(def.did()).instantiate_identity().to_string()), + generic_args.push(( + *name, + self.tcx.type_of(def.did()).instantiate_identity().to_string(), )); } } } if let Some(true) = self_ty.ty_adt_def().map(|def| def.did().is_local()) { - flags.push((sym::crate_local, None)); + crate_local = true; } // Allow targeting all integers using `{integral}`, even if the exact type was resolved if self_ty.is_integral() { - flags.push((sym::_Self, Some("{integral}".to_owned()))); + self_types.push("{integral}".to_owned()); } if self_ty.is_array_slice() { - flags.push((sym::_Self, Some("&[]".to_owned()))); + self_types.push("&[]".to_owned()); } if self_ty.is_fn() { @@ -201,53 +195,51 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { hir::Safety::Unsafe => "unsafe fn", } }; - flags.push((sym::_Self, Some(shortname.to_owned()))); + self_types.push(shortname.to_owned()); } // Slices give us `[]`, `[{ty}]` if let ty::Slice(aty) = self_ty.kind() { - flags.push((sym::_Self, Some("[]".to_string()))); + self_types.push("[]".to_owned()); if let Some(def) = aty.ty_adt_def() { // We also want to be able to select the slice's type's original // signature with no type arguments resolved - flags.push(( - sym::_Self, - Some(format!("[{}]", self.tcx.type_of(def.did()).instantiate_identity())), - )); + self_types + .push(format!("[{}]", self.tcx.type_of(def.did()).instantiate_identity())); } if aty.is_integral() { - flags.push((sym::_Self, Some("[{integral}]".to_string()))); + self_types.push("[{integral}]".to_string()); } } // Arrays give us `[]`, `[{ty}; _]` and `[{ty}; N]` if let ty::Array(aty, len) = self_ty.kind() { - flags.push((sym::_Self, Some("[]".to_string()))); + self_types.push("[]".to_string()); let len = len.try_to_target_usize(self.tcx); - flags.push((sym::_Self, Some(format!("[{aty}; _]")))); + self_types.push(format!("[{aty}; _]")); if let Some(n) = len { - flags.push((sym::_Self, Some(format!("[{aty}; {n}]")))); + self_types.push(format!("[{aty}; {n}]")); } if let Some(def) = aty.ty_adt_def() { // We also want to be able to select the array's type's original // signature with no type arguments resolved let def_ty = self.tcx.type_of(def.did()).instantiate_identity(); - flags.push((sym::_Self, Some(format!("[{def_ty}; _]")))); + self_types.push(format!("[{def_ty}; _]")); if let Some(n) = len { - flags.push((sym::_Self, Some(format!("[{def_ty}; {n}]")))); + self_types.push(format!("[{def_ty}; {n}]")); } } if aty.is_integral() { - flags.push((sym::_Self, Some("[{integral}; _]".to_string()))); + self_types.push("[{integral}; _]".to_string()); if let Some(n) = len { - flags.push((sym::_Self, Some(format!("[{{integral}}; {n}]")))); + self_types.push(format!("[{{integral}}; {n}]")); } } } if let ty::Dynamic(traits, _, _) = self_ty.kind() { for t in traits.iter() { if let ty::ExistentialPredicate::Trait(trait_ref) = t.skip_binder() { - flags.push((sym::_Self, Some(self.tcx.def_path_str(trait_ref.def_id)))) + self_types.push(self.tcx.def_path_str(trait_ref.def_id)); } } } @@ -257,14 +249,51 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { && let ty::Slice(sty) = ref_ty.kind() && sty.is_integral() { - flags.push((sym::_Self, Some("&[{integral}]".to_owned()))); + self_types.push("&[{integral}]".to_owned()); } })); - flags.push((sym::This, Some(self.tcx.def_path_str(trait_pred.trait_ref.def_id)))); + let this = self.tcx.def_path_str(trait_pred.trait_ref.def_id).to_string(); + let trait_sugared = trait_pred.trait_ref.print_trait_sugared().to_string(); + + let condition_options = ConditionOptions { + self_types, + from_desugaring, + cause, + crate_local, + direct, + generic_args, + }; + + // Unlike the generic_args earlier, + // this one is *not* collected under `with_no_trimmed_paths!` + // for printing the type to the user + let generic_args = self + .tcx + .generics_of(trait_pred.trait_ref.def_id) + .own_params + .iter() + .filter_map(|param| { + let value = match param.kind { + GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => { + if let Some(ty) = trait_pred.trait_ref.args[param.index as usize].as_type() + { + self.tcx.short_string(ty, long_ty_file) + } else { + trait_pred.trait_ref.args[param.index as usize].to_string() + } + } + GenericParamDefKind::Lifetime => return None, + }; + let name = param.name; + Some((name, value)) + }) + .collect(); + + let format_args = FormatArgs { this, trait_sugared, generic_args, item_context }; if let Ok(Some(command)) = OnUnimplementedDirective::of_item(self.tcx, def_id) { - command.evaluate(self.tcx, trait_pred.trait_ref, &flags, long_ty_file) + command.evaluate(self.tcx, trait_pred.trait_ref, &condition_options, &format_args) } else { OnUnimplementedNote::default() } @@ -634,23 +663,23 @@ impl<'tcx> OnUnimplementedDirective { &self, tcx: TyCtxt<'tcx>, trait_ref: ty::TraitRef<'tcx>, - options: &[(Symbol, Option)], - long_ty_file: &mut Option, + condition_options: &ConditionOptions, + args: &FormatArgs, ) -> OnUnimplementedNote { let mut message = None; let mut label = None; let mut notes = Vec::new(); let mut parent_label = None; let mut append_const_msg = None; - info!("evaluate({:?}, trait_ref={:?}, options={:?})", self, trait_ref, options); - - let options_map: FxHashMap = - options.iter().filter_map(|(k, v)| v.clone().map(|v| (*k, v))).collect(); + info!( + "evaluate({:?}, trait_ref={:?}, options={:?}, args ={:?})", + self, trait_ref, condition_options, args + ); for command in self.subcommands.iter().chain(Some(self)).rev() { debug!(?command); if let Some(ref condition) = command.condition - && !condition.matches_predicate(tcx, options, &options_map) + && !condition.matches_predicate(tcx, condition_options) { debug!("evaluate: skipping {:?} due to condition", command); continue; @@ -674,14 +703,10 @@ impl<'tcx> OnUnimplementedDirective { } OnUnimplementedNote { - label: label.map(|l| l.1.format(tcx, trait_ref, &options_map, long_ty_file)), - message: message.map(|m| m.1.format(tcx, trait_ref, &options_map, long_ty_file)), - notes: notes - .into_iter() - .map(|n| n.format(tcx, trait_ref, &options_map, long_ty_file)) - .collect(), - parent_label: parent_label - .map(|e_s| e_s.format(tcx, trait_ref, &options_map, long_ty_file)), + label: label.map(|l| l.1.format(tcx, trait_ref, args)), + message: message.map(|m| m.1.format(tcx, trait_ref, args)), + notes: notes.into_iter().map(|n| n.format(tcx, trait_ref, args)).collect(), + parent_label: parent_label.map(|e_s| e_s.format(tcx, trait_ref, args)), append_const_msg, } } @@ -759,8 +784,7 @@ impl<'tcx> OnUnimplementedFormatString { &self, tcx: TyCtxt<'tcx>, trait_ref: ty::TraitRef<'tcx>, - options: &FxHashMap, - long_ty_file: &mut Option, + args: &FormatArgs, ) -> String { let trait_def_id = trait_ref.def_id; let ctx = if self.is_diagnostic_namespace_variant { @@ -770,7 +794,7 @@ impl<'tcx> OnUnimplementedFormatString { }; if let Ok(s) = FormatString::parse(self.symbol, self.span, &ctx) { - s.format(tcx, trait_ref, options, long_ty_file) + s.format(args) } else { // we cannot return errors from processing the format string as hard error here // as the diagnostic namespace guarantees that malformed input cannot cause an error diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_condition.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_condition.rs index 4c852c1023a10..491ba6d7ffc08 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_condition.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_condition.rs @@ -1,9 +1,8 @@ use rustc_ast::MetaItemInner; use rustc_attr_parsing as attr; -use rustc_data_structures::fx::FxHashMap; use rustc_middle::ty::{self, TyCtxt}; use rustc_parse_format::{ParseMode, Parser, Piece, Position}; -use rustc_span::{Span, Symbol, sym}; +use rustc_span::{Span, Symbol, kw, sym}; pub static ALLOWED_CONDITION_SYMBOLS: &[Symbol] = &[ sym::from_desugaring, @@ -26,12 +25,7 @@ impl Condition { self.inner.span() } - pub fn matches_predicate<'tcx>( - &self, - tcx: TyCtxt<'tcx>, - options: &[(Symbol, Option)], - options_map: &FxHashMap, - ) -> bool { + pub fn matches_predicate<'tcx>(&self, tcx: TyCtxt<'tcx>, options: &ConditionOptions) -> bool { attr::eval_condition(&self.inner, tcx.sess, Some(tcx.features()), &mut |cfg| { let value = cfg.value.map(|v| { // `with_no_visible_paths` is also used when generating the options, @@ -44,8 +38,8 @@ impl Condition { Piece::NextArgument(a) => match a.position { Position::ArgumentNamed(arg) => { let s = Symbol::intern(arg); - match options_map.get(&s) { - Some(val) => val.to_string(), + match options.generic_args.iter().find(|(k, _)| *k == s) { + Some((_, val)) => val.to_string(), None => format!("{{{arg}}}"), } } @@ -58,7 +52,36 @@ impl Condition { }) }); - options.contains(&(cfg.name, value)) + options.contains(cfg.name, &value) }) } } + +#[derive(Debug)] +pub struct ConditionOptions { + pub self_types: Vec, + pub from_desugaring: Option, + pub cause: Option, + pub crate_local: bool, + pub direct: bool, + pub generic_args: Vec<(Symbol, String)>, +} + +impl ConditionOptions { + pub fn contains(&self, key: Symbol, value: &Option) -> bool { + match (key, value) { + (sym::_Self | kw::SelfUpper, Some(value)) => self.self_types.contains(&value), + // from_desugaring as a flag + (sym::from_desugaring, None) => self.from_desugaring.is_some(), + // from_desugaring as key == value + (sym::from_desugaring, v) => *v == self.from_desugaring, + (sym::cause, Some(value)) => self.cause.as_deref() == Some(value), + (sym::crate_local, None) => self.crate_local, + (sym::direct, None) => self.direct, + (other, Some(value)) => { + self.generic_args.iter().any(|(k, v)| *k == other && v == value) + } + _ => false, + } + } +} diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs index 21db207496cac..1bf15a3450947 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs @@ -1,10 +1,5 @@ -use std::fmt::Write; -use std::path::PathBuf; - use errors::*; -use rustc_data_structures::fx::FxHashMap; -use rustc_middle::span_bug; -use rustc_middle::ty::{self, GenericParamDefKind, TyCtxt}; +use rustc_middle::ty::TyCtxt; use rustc_parse_format::{ Alignment, Argument, Count, FormatSpec, InnerSpan, ParseError, ParseMode, Parser, Piece as RpfPiece, Position, @@ -13,6 +8,7 @@ use rustc_session::lint::builtin::UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES; use rustc_span::def_id::DefId; use rustc_span::{BytePos, Pos, Span, Symbol, kw, sym}; +#[allow(dead_code)] pub struct FormatString { input: Symbol, input_span: Span, @@ -99,6 +95,24 @@ impl FormatWarning { } } +#[derive(Debug)] +pub struct ConditionOptions { + pub self_types: Vec, + pub from_desugaring: Option, + pub cause: Option, + pub crate_local: bool, + pub direct: bool, + pub generic_args: Vec<(Symbol, String)>, +} + +#[derive(Debug)] +pub struct FormatArgs { + pub this: String, + pub trait_sugared: String, + pub item_context: String, + pub generic_args: Vec<(Symbol, String)>, +} + impl FormatString { pub fn parse(input: Symbol, input_span: Span, ctx: &Ctx<'_>) -> Result> { let s = input.as_str(); @@ -126,92 +140,34 @@ impl FormatString { } } - pub fn format<'tcx>( - &self, - tcx: TyCtxt<'tcx>, - trait_ref: ty::TraitRef<'tcx>, - options: &FxHashMap, - long_ty_file: &mut Option, - ) -> String { - let generics = tcx.generics_of(trait_ref.def_id); - let generic_map = generics - .own_params - .iter() - .filter_map(|param| { - let value = match param.kind { - GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => { - if let Some(ty) = trait_ref.args[param.index as usize].as_type() { - tcx.short_string(ty, long_ty_file) - } else { - trait_ref.args[param.index as usize].to_string() - } - } - GenericParamDefKind::Lifetime => return None, - }; - let name = param.name; - Some((name, value)) - }) - .collect::>(); - + pub fn format(&self, args: &FormatArgs) -> String { let mut ret = String::new(); for piece in &self.pieces { match piece { Piece::Lit(s) | Piece::Arg(FormatArg::AsIs(s)) => ret.push_str(&s), // `A` if we have `trait Trait {}` and `note = "i'm the actual type of {A}"` - Piece::Arg(FormatArg::GenericParam { generic_param, span }) => { + Piece::Arg(FormatArg::GenericParam { generic_param, .. }) => { // Should always be some but we can't raise errors here - if let Some(value) = generic_map.get(&generic_param) { - ret.push_str(value); - } else if cfg!(debug_assertions) { - span_bug!(*span, "invalid generic parameter"); - } else { - let _ = ret.write_fmt(format_args!("{{{}}}", generic_param.as_str())); - } + let value = match args.generic_args.iter().find(|(p, _)| p == generic_param) { + Some((_, val)) => val.to_string(), + None => generic_param.to_string(), + }; + ret.push_str(&value); } // `{Self}` Piece::Arg(FormatArg::SelfUpper) => { - let Some(slf) = generic_map.get(&kw::SelfUpper) else { - span_bug!( - self.input_span, - "broken format string {:?} for {:?}: \ - no argument matching `Self`", - self.input, - trait_ref, - ) + let slf = match args.generic_args.iter().find(|(p, _)| *p == kw::SelfUpper) { + Some((_, val)) => val.to_string(), + None => "Self".to_string(), }; ret.push_str(&slf); } // It's only `rustc_onunimplemented` from here - Piece::Arg(FormatArg::This) => { - let Some(this) = options.get(&sym::This) else { - span_bug!( - self.input_span, - "broken format string {:?} for {:?}: \ - no argument matching This", - self.input, - trait_ref, - ) - }; - ret.push_str(this); - } - Piece::Arg(FormatArg::Trait) => { - let Some(this) = options.get(&sym::Trait) else { - span_bug!( - self.input_span, - "broken format string {:?} for {:?}: \ - no argument matching Trait", - self.input, - trait_ref, - ) - }; - ret.push_str(this); - } - Piece::Arg(FormatArg::ItemContext) => { - let itemcontext = options.get(&sym::ItemContext); - ret.push_str(itemcontext.unwrap_or(&String::new())); - } + Piece::Arg(FormatArg::This) => ret.push_str(&args.this), + Piece::Arg(FormatArg::Trait) => ret.push_str(&args.trait_sugared), + Piece::Arg(FormatArg::ItemContext) => ret.push_str(&args.item_context), } } ret From 3375264fa1c6e7fe95b05c7c369f1f884dee1c91 Mon Sep 17 00:00:00 2001 From: Alex Macleod Date: Thu, 10 Apr 2025 20:58:15 +0000 Subject: [PATCH 076/266] Fix `register_group_alias` for tools --- compiler/rustc_lint/src/context.rs | 97 ++++++++++++------------------ compiler/rustc_lint/src/levels.rs | 4 +- compiler/rustc_lint/src/lib.rs | 4 +- 3 files changed, 42 insertions(+), 63 deletions(-) diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 885a7308bdc6d..9005bc9292037 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -83,11 +83,6 @@ enum TargetLint { Ignored, } -pub enum FindLintError { - NotFound, - Removed, -} - struct LintAlias { name: &'static str, /// Whether deprecation warnings should be suppressed for this alias. @@ -231,13 +226,24 @@ impl LintStore { } } - pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) { - self.lint_groups.insert( + fn insert_group(&mut self, name: &'static str, group: LintGroup) { + let previous = self.lint_groups.insert(name, group); + if previous.is_some() { + bug!("group {name:?} already exists"); + } + } + + pub fn register_group_alias(&mut self, group_name: &'static str, alias: &'static str) { + let Some(LintGroup { lint_ids, .. }) = self.lint_groups.get(group_name) else { + bug!("group alias {alias:?} points to unregistered group {group_name:?}") + }; + + self.insert_group( alias, LintGroup { - lint_ids: vec![], + lint_ids: lint_ids.clone(), is_externally_loaded: false, - depr: Some(LintAlias { name: lint_name, silent: true }), + depr: Some(LintAlias { name: group_name, silent: true }), }, ); } @@ -249,24 +255,17 @@ impl LintStore { deprecated_name: Option<&'static str>, to: Vec, ) { - let new = self - .lint_groups - .insert(name, LintGroup { lint_ids: to, is_externally_loaded, depr: None }) - .is_none(); if let Some(deprecated) = deprecated_name { - self.lint_groups.insert( + self.insert_group( deprecated, LintGroup { - lint_ids: vec![], + lint_ids: to.clone(), is_externally_loaded, depr: Some(LintAlias { name, silent: false }), }, ); } - - if !new { - bug!("duplicate specification of lint group {}", name); - } + self.insert_group(name, LintGroup { lint_ids: to, is_externally_loaded, depr: None }); } /// This lint should give no warning and have no effect. @@ -292,23 +291,15 @@ impl LintStore { self.by_name.insert(name.into(), Removed(reason.into())); } - pub fn find_lints(&self, mut lint_name: &str) -> Result, FindLintError> { + pub fn find_lints(&self, lint_name: &str) -> Option<&[LintId]> { match self.by_name.get(lint_name) { - Some(&Id(lint_id)) => Ok(vec![lint_id]), - Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]), - Some(&Removed(_)) => Err(FindLintError::Removed), - Some(&Ignored) => Ok(vec![]), - None => loop { - return match self.lint_groups.get(lint_name) { - Some(LintGroup { lint_ids, depr, .. }) => { - if let Some(LintAlias { name, .. }) = depr { - lint_name = name; - continue; - } - Ok(lint_ids.clone()) - } - None => Err(FindLintError::Removed), - }; + Some(Id(lint_id)) => Some(slice::from_ref(lint_id)), + Some(Renamed(_, lint_id)) => Some(slice::from_ref(lint_id)), + Some(Removed(_)) => None, + Some(Ignored) => Some(&[]), + None => match self.lint_groups.get(lint_name) { + Some(LintGroup { lint_ids, .. }) => Some(lint_ids), + None => None, }, } } @@ -374,8 +365,12 @@ impl LintStore { CheckLintNameResult::MissingTool }; } - Some(LintGroup { lint_ids, .. }) => { - return CheckLintNameResult::Tool(lint_ids, None); + Some(LintGroup { lint_ids, depr, .. }) => { + return if let &Some(LintAlias { name, silent: false }) = depr { + CheckLintNameResult::Tool(lint_ids, Some(name.to_string())) + } else { + CheckLintNameResult::Tool(lint_ids, None) + }; } }, Some(Id(id)) => return CheckLintNameResult::Tool(slice::from_ref(id), None), @@ -393,15 +388,11 @@ impl LintStore { None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"), Some(LintGroup { lint_ids, depr, .. }) => { // Check if the lint group name is deprecated - if let Some(LintAlias { name, silent }) = depr { - let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap(); - return if *silent { - CheckLintNameResult::Ok(lint_ids) - } else { - CheckLintNameResult::Tool(lint_ids, Some((*name).to_string())) - }; + if let &Some(LintAlias { name, silent: false }) = depr { + CheckLintNameResult::Tool(lint_ids, Some(name.to_string())) + } else { + CheckLintNameResult::Ok(lint_ids) } - CheckLintNameResult::Ok(lint_ids) } }, Some(Id(id)) => CheckLintNameResult::Ok(slice::from_ref(id)), @@ -412,7 +403,7 @@ impl LintStore { fn no_lint_suggestion(&self, lint_name: &str, tool_name: &str) -> CheckLintNameResult<'_> { let name_lower = lint_name.to_lowercase(); - if lint_name.chars().any(char::is_uppercase) && self.find_lints(&name_lower).is_ok() { + if lint_name.chars().any(char::is_uppercase) && self.find_lints(&name_lower).is_some() { // First check if the lint name is (partly) in upper case instead of lower case... return CheckLintNameResult::NoLint(Some((Symbol::intern(&name_lower), false))); } @@ -455,18 +446,8 @@ impl LintStore { None => match self.lint_groups.get(&*complete_name) { // Now we are sure, that this lint exists nowhere None => self.no_lint_suggestion(lint_name, tool_name), - Some(LintGroup { lint_ids, depr, .. }) => { - // Reaching this would be weird, but let's cover this case anyway - if let Some(LintAlias { name, silent }) = depr { - let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap(); - if *silent { - CheckLintNameResult::Tool(lint_ids, Some(complete_name)) - } else { - CheckLintNameResult::Tool(lint_ids, Some((*name).to_string())) - } - } else { - CheckLintNameResult::Tool(lint_ids, Some(complete_name)) - } + Some(LintGroup { lint_ids, .. }) => { + CheckLintNameResult::Tool(lint_ids, Some(complete_name)) } }, Some(Id(id)) => CheckLintNameResult::Tool(slice::from_ref(id), Some(complete_name)), diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index d0b1e7bf25534..00775647ac61a 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -517,11 +517,11 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { let lint_flag_val = Symbol::intern(lint_name); - let Ok(ids) = self.store.find_lints(lint_name) else { + let Some(ids) = self.store.find_lints(lint_name) else { // errors already handled above continue; }; - for id in ids { + for &id in ids { // ForceWarn and Forbid cannot be overridden if let Some(LevelAndSource { level: Level::ForceWarn | Level::Forbid, .. }) = self.current_specs().get(&id) diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 9b5c564d3324b..e1afd8bacb099 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -125,9 +125,7 @@ use unused::*; #[rustfmt::skip] pub use builtin::{MissingDoc, SoftLints}; -pub use context::{ - CheckLintNameResult, EarlyContext, FindLintError, LateContext, LintContext, LintStore, -}; +pub use context::{CheckLintNameResult, EarlyContext, LateContext, LintContext, LintStore}; pub use early::{EarlyCheckNode, check_ast_node}; pub use late::{check_crate, late_lint_mod, unerased_lint_store}; pub use levels::LintLevelsBuilder; From 068a33245981765c3678434d5bcb71bd63d5598a Mon Sep 17 00:00:00 2001 From: Bastian Kersting Date: Fri, 11 Apr 2025 10:15:55 +0000 Subject: [PATCH 077/266] cfi: Remove #[no_sanitize(cfi)] for extern weak functions Previously (https://github.com/rust-lang/rust/pull/115200, https://github.com/rust-lang/rust/pull/138002), we added `#[no_sanitize(cfi)]` to all code paths that call to a weakly linked function. In https://github.com/rust-lang/rust/pull/138349 we fixed the root cause for this issue, which means we can now remove the corresponding attributes. --- library/std/src/sys/fd/unix.rs | 3 --- library/std/src/sys/fs/unix.rs | 14 -------------- library/std/src/sys/pal/unix/thread.rs | 3 --- library/std/src/sys/pal/unix/time.rs | 11 ----------- library/std/src/sys/pal/unix/weak.rs | 3 --- library/std/src/sys/process/unix/unix.rs | 3 --- .../src/sys/thread_local/destructors/linux_like.rs | 3 --- 7 files changed, 40 deletions(-) diff --git a/library/std/src/sys/fd/unix.rs b/library/std/src/sys/fd/unix.rs index 2042ea2c73d00..5765cb1386ab2 100644 --- a/library/std/src/sys/fd/unix.rs +++ b/library/std/src/sys/fd/unix.rs @@ -257,9 +257,6 @@ impl FileDesc { } #[cfg(all(target_os = "android", target_pointer_width = "32"))] - // FIXME(#115199): Rust currently omits weak function definitions - // and its metadata from LLVM IR. - #[no_sanitize(cfi)] pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result { weak!( fn preadv64( diff --git a/library/std/src/sys/fs/unix.rs b/library/std/src/sys/fs/unix.rs index 87865be0387d5..687fc322e598d 100644 --- a/library/std/src/sys/fs/unix.rs +++ b/library/std/src/sys/fs/unix.rs @@ -1463,20 +1463,6 @@ impl File { Ok(()) } - // FIXME(#115199): Rust currently omits weak function definitions - // and its metadata from LLVM IR. - #[cfg_attr( - any( - target_os = "android", - all( - target_os = "linux", - target_env = "gnu", - target_pointer_width = "32", - not(target_arch = "riscv32") - ) - ), - no_sanitize(cfi) - )] pub fn set_times(&self, times: FileTimes) -> io::Result<()> { #[cfg(not(any( target_os = "redox", diff --git a/library/std/src/sys/pal/unix/thread.rs b/library/std/src/sys/pal/unix/thread.rs index 9078dd1c23166..c0662600db1df 100644 --- a/library/std/src/sys/pal/unix/thread.rs +++ b/library/std/src/sys/pal/unix/thread.rs @@ -189,9 +189,6 @@ impl Thread { } #[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))] - // FIXME(#115199): Rust currently omits weak function definitions - // and its metadata from LLVM IR. - #[no_sanitize(cfi)] pub fn set_name(name: &CStr) { weak!( fn pthread_setname_np( diff --git a/library/std/src/sys/pal/unix/time.rs b/library/std/src/sys/pal/unix/time.rs index b8469b1681f03..0074d7674741b 100644 --- a/library/std/src/sys/pal/unix/time.rs +++ b/library/std/src/sys/pal/unix/time.rs @@ -96,17 +96,6 @@ impl Timespec { } } - // FIXME(#115199): Rust currently omits weak function definitions - // and its metadata from LLVM IR. - #[cfg_attr( - all( - target_os = "linux", - target_env = "gnu", - target_pointer_width = "32", - not(target_arch = "riscv32") - ), - no_sanitize(cfi) - )] pub fn now(clock: libc::clockid_t) -> Timespec { use crate::mem::MaybeUninit; use crate::sys::cvt; diff --git a/library/std/src/sys/pal/unix/weak.rs b/library/std/src/sys/pal/unix/weak.rs index e4c814fba8cef..a034995e6525d 100644 --- a/library/std/src/sys/pal/unix/weak.rs +++ b/library/std/src/sys/pal/unix/weak.rs @@ -155,9 +155,6 @@ unsafe fn fetch(name: &str) -> *mut libc::c_void { #[cfg(not(any(target_os = "linux", target_os = "android")))] pub(crate) macro syscall { (fn $name:ident($($param:ident : $t:ty),* $(,)?) -> $ret:ty;) => ( - // FIXME(#115199): Rust currently omits weak function definitions - // and its metadata from LLVM IR. - #[no_sanitize(cfi)] unsafe fn $name($($param: $t),*) -> $ret { weak!(fn $name($($param: $t),*) -> $ret;); diff --git a/library/std/src/sys/process/unix/unix.rs b/library/std/src/sys/process/unix/unix.rs index 191a09c8da913..3b04ec50db30e 100644 --- a/library/std/src/sys/process/unix/unix.rs +++ b/library/std/src/sys/process/unix/unix.rs @@ -434,9 +434,6 @@ impl Command { target_os = "nto", target_vendor = "apple", ))] - // FIXME(#115199): Rust currently omits weak function definitions - // and its metadata from LLVM IR. - #[cfg_attr(target_os = "linux", no_sanitize(cfi))] fn posix_spawn( &mut self, stdio: &ChildPipes, diff --git a/library/std/src/sys/thread_local/destructors/linux_like.rs b/library/std/src/sys/thread_local/destructors/linux_like.rs index 817941229eefe..d7cbaeb89f42e 100644 --- a/library/std/src/sys/thread_local/destructors/linux_like.rs +++ b/library/std/src/sys/thread_local/destructors/linux_like.rs @@ -12,9 +12,6 @@ use crate::mem::transmute; -// FIXME: The Rust compiler currently omits weakly function definitions (i.e., -// __cxa_thread_atexit_impl) and its metadata from LLVM IR. -#[no_sanitize(cfi, kcfi)] pub unsafe fn register(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { /// This is necessary because the __cxa_thread_atexit_impl implementation /// std links to by default may be a C or C++ implementation that was not From 830bd8b6f4feb8665c8865beb20ffb424e8d8ee6 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Sun, 6 Apr 2025 07:06:10 +0000 Subject: [PATCH 078/266] Implement Default for raw pointers --- library/core/src/ptr/const_ptr.rs | 8 ++++++++ library/core/src/ptr/mut_ptr.rs | 8 ++++++++ library/coretests/tests/ptr.rs | 17 +++++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 0854e31c19979..2d869958b85cc 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -1739,3 +1739,11 @@ impl PartialOrd for *const T { *self >= *other } } + +#[stable(feature = "raw_ptr_default", since = "CURRENT_RUSTC_VERSION")] +impl Default for *const T { + /// Returns the default value of [`null()`][crate::ptr::null]. + fn default() -> Self { + crate::ptr::null() + } +} diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index e29774963db00..df49eedb35096 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -2156,3 +2156,11 @@ impl PartialOrd for *mut T { *self >= *other } } + +#[stable(feature = "raw_ptr_default", since = "CURRENT_RUSTC_VERSION")] +impl Default for *mut T { + /// Returns the default value of [`null_mut()`][crate::ptr::null_mut]. + fn default() -> Self { + crate::ptr::null_mut() + } +} diff --git a/library/coretests/tests/ptr.rs b/library/coretests/tests/ptr.rs index cc5f7946863a6..7d6e4eac1e21e 100644 --- a/library/coretests/tests/ptr.rs +++ b/library/coretests/tests/ptr.rs @@ -1020,3 +1020,20 @@ fn test_ptr_swap_nonoverlapping_is_untyped() { ptr_swap_nonoverlapping_is_untyped_inner(); const { ptr_swap_nonoverlapping_is_untyped_inner() }; } + +#[test] +fn test_ptr_default() { + #[derive(Default)] + struct PtrDefaultTest { + ptr: *const u64, + } + let default = PtrDefaultTest::default(); + assert!(default.ptr.is_null()); + + #[derive(Default)] + struct PtrMutDefaultTest { + ptr: *mut u64, + } + let default = PtrMutDefaultTest::default(); + assert!(default.ptr.is_null()); +} From 9eb6a5446a4e35f48ad22a5b70a74a8badb9fa0d Mon Sep 17 00:00:00 2001 From: Petros Angelatos Date: Thu, 10 Apr 2025 11:09:31 +0300 Subject: [PATCH 079/266] sync::mpsc: add miri reproducer of double free Signed-off-by: Petros Angelatos --- library/std/src/sync/mpmc/list.rs | 5 +++ .../miri/tests/pass/issues/issue-139553.rs | 45 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/tools/miri/tests/pass/issues/issue-139553.rs diff --git a/library/std/src/sync/mpmc/list.rs b/library/std/src/sync/mpmc/list.rs index d88914f529142..2dd8f41226d63 100644 --- a/library/std/src/sync/mpmc/list.rs +++ b/library/std/src/sync/mpmc/list.rs @@ -213,6 +213,11 @@ impl Channel { .compare_exchange(block, new, Ordering::Release, Ordering::Relaxed) .is_ok() { + // This yield point leaves the channel in a half-initialized state where the + // tail.block pointer is set but the head.block is not. This is used to + // facilitate the test in src/tools/miri/tests/pass/issues/issue-139553.rs + #[cfg(miri)] + crate::thread::yield_now(); self.head.block.store(new, Ordering::Release); block = new; } else { diff --git a/src/tools/miri/tests/pass/issues/issue-139553.rs b/src/tools/miri/tests/pass/issues/issue-139553.rs new file mode 100644 index 0000000000000..97cb9e1a8057c --- /dev/null +++ b/src/tools/miri/tests/pass/issues/issue-139553.rs @@ -0,0 +1,45 @@ +//@compile-flags: -Zmiri-preemption-rate=0 -Zmiri-compare-exchange-weak-failure-rate=0 +use std::sync::mpsc::channel; +use std::thread; + +/// This test aims to trigger a race condition that causes a double free in the unbounded channel +/// implementation. The test relies on a particular thread scheduling to happen as annotated by the +/// comments below. +fn main() { + let (s1, r) = channel::(); + let s2 = s1.clone(); + + let t1 = thread::spawn(move || { + // 1. The first action executed is an attempt to send the first value in the channel. This + // will begin to initialize the channel but will stop at a critical momement as + // indicated by the `yield_now()` call in the `start_send` method of the implementation. + let _ = s1.send(42); + // 4. The sender is re-scheduled and it finishes the initialization of the channel by + // setting head.block to the same value as tail.block. It then proceeds to publish its + // value but observes that the channel has already disconnected (due to the concurrent + // call of `discard_all_messages`) and aborts the send. + }); + std::thread::yield_now(); + + // 2. A second sender attempts to send a value while the channel is in a half-initialized + // state. Here, half-initialized means that the `tail.block` pointer points to a valid block + // but `head.block` is still null. This condition is ensured by the yield of step 1. When + // this call returns the channel state has tail.index != head.index, tail.block != NULL, and + // head.block = NULL. + s2.send(42).unwrap(); + // 3. This thread continues with dropping the one and only receiver. When all receivers are + // gone `discard_all_messages` will attempt to drop all currently sent values and + // de-allocate all the blocks. If `tail.block != NULL` but `head.block = NULL` the + // implementation waits for the initializing sender to finish by spinning/yielding. + drop(r); + // 5. This thread is rescheduled and `discard_all_messages` observes the head.block pointer set + // by step 4 and proceeds with deallocation. In the problematic version of the code + // `head.block` is simply read via an `Acquire` load and not swapped with NULL. After this + // call returns the channel state has tail.index = head.index, tail.block = NULL, and + // head.block != NULL. + t1.join().unwrap(); + // 6. The last sender (s1) is dropped here which also attempts to cleanup any data in the + // channel. It observes `tail.index = head.index` and so it doesn't attempt to cleanup any + // messages but it also observes that `head.block != NULL` and attempts to deallocate it. + // This is however already deallocated by `discard_all_messages`, leading to a double free. +} From b9e2ac5c7b1d6bb3b6f5fdfe0819eaf7e95bf7ff Mon Sep 17 00:00:00 2001 From: Petros Angelatos Date: Tue, 8 Apr 2025 22:37:25 +0300 Subject: [PATCH 080/266] sync::mpsc: prevent double free on `Drop` This PR is fixing a regression introduced by #121646 that can lead to a double free when dropping the channel. The details of the bug can be found in the corresponding crossbeam PR https://github.com/crossbeam-rs/crossbeam/pull/1187 Signed-off-by: Petros Angelatos --- library/std/src/sync/mpmc/list.rs | 8 +++++++- src/tools/miri/tests/pass/issues/issue-139553.rs | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/library/std/src/sync/mpmc/list.rs b/library/std/src/sync/mpmc/list.rs index 2dd8f41226d63..1c6acb29e375f 100644 --- a/library/std/src/sync/mpmc/list.rs +++ b/library/std/src/sync/mpmc/list.rs @@ -569,9 +569,15 @@ impl Channel { // In that case, just wait until it gets initialized. while block.is_null() { backoff.spin_heavy(); - block = self.head.block.load(Ordering::Acquire); + block = self.head.block.swap(ptr::null_mut(), Ordering::AcqRel); } } + // After this point `head.block` is not modified again and it will be deallocated if it's + // non-null. The `Drop` code of the channel, which runs after this function, also attempts + // to deallocate `head.block` if it's non-null. Therefore this function must maintain the + // invariant that if a deallocation of head.block is attemped then it must also be set to + // NULL. Failing to do so will lead to the Drop code attempting a double free. For this + // reason both reads above do an atomic swap instead of a simple atomic load. unsafe { // Drop all messages between head and tail and deallocate the heap-allocated blocks. diff --git a/src/tools/miri/tests/pass/issues/issue-139553.rs b/src/tools/miri/tests/pass/issues/issue-139553.rs index 97cb9e1a8057c..119d589d1eada 100644 --- a/src/tools/miri/tests/pass/issues/issue-139553.rs +++ b/src/tools/miri/tests/pass/issues/issue-139553.rs @@ -38,7 +38,7 @@ fn main() { // call returns the channel state has tail.index = head.index, tail.block = NULL, and // head.block != NULL. t1.join().unwrap(); - // 6. The last sender (s1) is dropped here which also attempts to cleanup any data in the + // 6. The last sender (s2) is dropped here which also attempts to cleanup any data in the // channel. It observes `tail.index = head.index` and so it doesn't attempt to cleanup any // messages but it also observes that `head.block != NULL` and attempts to deallocate it. // This is however already deallocated by `discard_all_messages`, leading to a double free. From f35eae780b492cca74d6ada59dc857959d937cd4 Mon Sep 17 00:00:00 2001 From: dianne Date: Fri, 14 Mar 2025 18:56:15 -0700 Subject: [PATCH 081/266] store the kind of pattern adjustments in `pat_adjustments` This allows us to better distinguish builtin and overloaded implicit dereferences. --- .../rustc_hir_typeck/src/expr_use_visitor.rs | 6 ++--- compiler/rustc_hir_typeck/src/pat.rs | 3 ++- compiler/rustc_middle/src/ty/adjustment.rs | 22 +++++++++++++++++++ .../rustc_middle/src/ty/structural_impls.rs | 6 +++++ .../rustc_middle/src/ty/typeck_results.rs | 10 ++++++--- .../src/thir/pattern/migration.rs | 8 +++---- .../rustc_mir_build/src/thir/pattern/mod.rs | 9 ++++---- .../clippy_lints/src/pattern_type_mismatch.rs | 2 +- 8 files changed, 50 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index 27df8f0e98a13..f43f9b5187b63 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -1227,9 +1227,9 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx // actually this is somewhat "disjoint" from the code below // that aims to account for `ref x`. if let Some(vec) = self.cx.typeck_results().pat_adjustments().get(pat.hir_id) { - if let Some(first_ty) = vec.first() { - debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty); - return Ok(*first_ty); + if let Some(first_adjust) = vec.first() { + debug!("pat_ty(pat={:?}) found adjustment `{:?}`", pat, first_adjust); + return Ok(first_adjust.source); } } else if let PatKind::Ref(subpat, _) = pat.kind && self.cx.typeck_results().skipped_ref_pats().contains(pat.hir_id) diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index fbc783c050904..c19d8cf6dc546 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -29,6 +29,7 @@ use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode}; use tracing::{debug, instrument, trace}; use ty::VariantDef; +use ty::adjustment::{PatAdjust, PatAdjustment}; use super::report_unexpected_variant_res; use crate::expectation::Expectation; @@ -415,7 +416,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .pat_adjustments_mut() .entry(pat.hir_id) .or_default() - .push(expected); + .push(PatAdjustment { kind: PatAdjust::BuiltinDeref, source: expected }); let mut binding_mode = ByRef::Yes(match pat_info.binding_mode { // If default binding mode is by value, make it `ref` or `ref mut` diff --git a/compiler/rustc_middle/src/ty/adjustment.rs b/compiler/rustc_middle/src/ty/adjustment.rs index f8ab555305f05..981d67e58d4be 100644 --- a/compiler/rustc_middle/src/ty/adjustment.rs +++ b/compiler/rustc_middle/src/ty/adjustment.rs @@ -214,3 +214,25 @@ pub enum CustomCoerceUnsized { /// Records the index of the field being coerced. Struct(FieldIdx), } + +/// Represents an implicit coercion applied to the scrutinee of a match before testing a pattern +/// against it. Currently, this is used only for implicit dereferences. +#[derive(Clone, Copy, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)] +pub struct PatAdjustment<'tcx> { + pub kind: PatAdjust, + /// The type of the scrutinee before the adjustment is applied, or the "adjusted type" of the + /// pattern. + pub source: Ty<'tcx>, +} + +/// Represents implicit coercions of patterns' types, rather than values' types. +#[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)] +#[derive(TypeFoldable, TypeVisitable)] +pub enum PatAdjust { + /// An implicit dereference before matching, such as when matching the pattern `0` against a + /// scrutinee of type `&u8` or `&mut u8`. + BuiltinDeref, + /// An implicit call to `Deref(Mut)::deref(_mut)` before matching, such as when matching the + /// pattern `[..]` against a scrutinee of type `Vec`. + OverloadedDeref, +} diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 798ef352c4082..6434e1a1ad9af 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -61,6 +61,12 @@ impl<'tcx> fmt::Debug for ty::adjustment::Adjustment<'tcx> { } } +impl<'tcx> fmt::Debug for ty::adjustment::PatAdjustment<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} -> {:?}", self.source, self.kind) + } +} + impl fmt::Debug for ty::BoundRegionKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index 90c6ef67fb88e..ee8113b0f7627 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -90,7 +90,7 @@ pub struct TypeckResults<'tcx> { /// /// See: /// - pat_adjustments: ItemLocalMap>>, + pat_adjustments: ItemLocalMap>>, /// Set of reference patterns that match against a match-ergonomics inserted reference /// (as opposed to against a reference in the scrutinee type). @@ -403,11 +403,15 @@ impl<'tcx> TypeckResults<'tcx> { LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes } } - pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec>> { + pub fn pat_adjustments( + &self, + ) -> LocalTableInContext<'_, Vec>> { LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments } } - pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { + pub fn pat_adjustments_mut( + &mut self, + ) -> LocalTableInContextMut<'_, Vec>> { LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments } } diff --git a/compiler/rustc_mir_build/src/thir/pattern/migration.rs b/compiler/rustc_mir_build/src/thir/pattern/migration.rs index bd7787b643d57..c688b6f2848c4 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/migration.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/migration.rs @@ -5,7 +5,7 @@ use rustc_errors::MultiSpan; use rustc_hir::{BindingMode, ByRef, HirId, Mutability}; use rustc_lint as lint; use rustc_middle::span_bug; -use rustc_middle::ty::{self, Rust2024IncompatiblePatInfo, Ty, TyCtxt}; +use rustc_middle::ty::{self, Rust2024IncompatiblePatInfo, TyCtxt}; use rustc_span::{Ident, Span}; use crate::errors::{Rust2024IncompatiblePat, Rust2024IncompatiblePatSugg}; @@ -93,10 +93,10 @@ impl<'a> PatMigration<'a> { pub(super) fn visit_implicit_derefs<'tcx>( &mut self, pat_span: Span, - adjustments: &[Ty<'tcx>], + adjustments: &[ty::adjustment::PatAdjustment<'tcx>], ) -> Option<(Span, Mutability)> { - let implicit_deref_mutbls = adjustments.iter().map(|ref_ty| { - let &ty::Ref(_, _, mutbl) = ref_ty.kind() else { + let implicit_deref_mutbls = adjustments.iter().map(|adjust| { + let &ty::Ref(_, _, mutbl) = adjust.source.kind() else { span_bug!(pat_span, "pattern implicitly dereferences a non-ref type"); }; mutbl diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 73d60cf444237..f682581d763be 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -18,6 +18,7 @@ use rustc_middle::mir::interpret::LitToConstInput; use rustc_middle::thir::{ Ascription, FieldPat, LocalVarId, Pat, PatKind, PatRange, PatRangeBoundary, }; +use rustc_middle::ty::adjustment::PatAdjustment; use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt, TypingMode}; use rustc_middle::{bug, span_bug}; @@ -63,7 +64,7 @@ pub(super) fn pat_from_hir<'a, 'tcx>( impl<'a, 'tcx> PatCtxt<'a, 'tcx> { fn lower_pattern(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Box> { - let adjustments: &[Ty<'tcx>] = + let adjustments: &[PatAdjustment<'tcx>] = self.typeck_results.pat_adjustments().get(pat.hir_id).map_or(&[], |v| &**v); // Track the default binding mode for the Rust 2024 migration suggestion. @@ -102,11 +103,11 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { _ => self.lower_pattern_unadjusted(pat), }; - let adjusted_pat = adjustments.iter().rev().fold(unadjusted_pat, |thir_pat, ref_ty| { - debug!("{:?}: wrapping pattern with type {:?}", thir_pat, ref_ty); + let adjusted_pat = adjustments.iter().rev().fold(unadjusted_pat, |thir_pat, adjust| { + debug!("{:?}: wrapping pattern with type {:?}", thir_pat, adjust); Box::new(Pat { span: thir_pat.span, - ty: *ref_ty, + ty: adjust.source, kind: PatKind::Deref { subpattern: thir_pat }, }) }); diff --git a/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs b/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs index 8f1a1ee76c6a6..96d3f7196c0cb 100644 --- a/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs +++ b/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs @@ -179,7 +179,7 @@ fn find_first_mismatch(cx: &LateContext<'_>, pat: &Pat<'_>) -> Option<(Span, Mut }; if let Some(adjustments) = cx.typeck_results().pat_adjustments().get(adjust_pat.hir_id) { if let [first, ..] = **adjustments { - if let ty::Ref(.., mutability) = *first.kind() { + if let ty::Ref(.., mutability) = *first.source.kind() { let level = if p.hir_id == pat.hir_id { Level::Top } else { From 8586cad77c175a0c2ce11c0579c537aa195e6da2 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Sat, 29 Mar 2025 02:04:10 +0100 Subject: [PATCH 082/266] Documentation and finishing touches --- compiler/rustc_span/src/hygiene.rs | 19 +++ .../traits/on_unimplemented.rs | 76 ++++++++-- .../traits/on_unimplemented_condition.rs | 69 +++++++--- .../traits/on_unimplemented_format.rs | 130 +++++++++++------- 4 files changed, 215 insertions(+), 79 deletions(-) diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index 9be16f8ce0c91..f6d69da9951f5 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -1270,6 +1270,25 @@ impl DesugaringKind { DesugaringKind::PatTyRange => "pattern type", } } + + /// For use with `rustc_unimplemented` to support conditions + /// like `from_desugaring = "QuestionMark"` + pub fn matches(&self, value: &str) -> bool { + match self { + DesugaringKind::CondTemporary => value == "CondTemporary", + DesugaringKind::Async => value == "Async", + DesugaringKind::Await => value == "Await", + DesugaringKind::QuestionMark => value == "QuestionMark", + DesugaringKind::TryBlock => value == "TryBlock", + DesugaringKind::YeetExpr => value == "YeetExpr", + DesugaringKind::OpaqueTy => value == "OpaqueTy", + DesugaringKind::ForLoop => value == "ForLoop", + DesugaringKind::WhileLoop => value == "WhileLoop", + DesugaringKind::BoundModifier => value == "BoundModifier", + DesugaringKind::Contract => value == "Contract", + DesugaringKind::PatTyRange => value == "PatTyRange", + } + } } #[derive(Default)] diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs index 7d8ecba3b2e09..0478f3a7f1127 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs @@ -6,6 +6,7 @@ use rustc_errors::codes::*; use rustc_errors::{ErrorGuaranteed, struct_span_code_err}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{AttrArgs, Attribute}; +use rustc_macros::LintDiagnostic; use rustc_middle::bug; use rustc_middle::ty::print::PrintTraitRefExt; use rustc_middle::ty::{self, GenericArgsRef, GenericParamDef, GenericParamDefKind, TyCtxt}; @@ -17,7 +18,6 @@ use {rustc_attr_parsing as attr, rustc_hir as hir}; use super::{ObligationCauseCode, PredicateObligation}; use crate::error_reporting::TypeErrCtxt; use crate::error_reporting::traits::on_unimplemented_condition::{Condition, ConditionOptions}; -use crate::error_reporting::traits::on_unimplemented_format::errors::*; use crate::error_reporting::traits::on_unimplemented_format::{Ctx, FormatArgs, FormatString}; use crate::errors::{ EmptyOnClauseInOnUnimplemented, InvalidOnClauseInOnUnimplemented, NoValueInOnUnimplemented, @@ -112,10 +112,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { // FIXME(-Zlower-impl-trait-in-trait-to-assoc-ty): HIR is not present for RPITITs, // but I guess we could synthesize one here. We don't see any errors that rely on // that yet, though. - let item_context = self - .describe_enclosure(obligation.cause.body_id) - .map(|t| t.to_owned()) - .unwrap_or(String::new()); + let item_context = self.describe_enclosure(obligation.cause.body_id).unwrap_or(""); let direct = match obligation.cause.code() { ObligationCauseCode::BuiltinDerived(..) @@ -128,7 +125,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } }; - let from_desugaring = obligation.cause.span.desugaring_kind().map(|k| format!("{k:?}")); + let from_desugaring = obligation.cause.span.desugaring_kind(); let cause = if let ObligationCauseCode::MainFunctionType = obligation.cause.code() { Some("MainFunctionType".to_string()) @@ -253,8 +250,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } })); - let this = self.tcx.def_path_str(trait_pred.trait_ref.def_id).to_string(); - let trait_sugared = trait_pred.trait_ref.print_trait_sugared().to_string(); + let this = self.tcx.def_path_str(trait_pred.trait_ref.def_id); + let trait_sugared = trait_pred.trait_ref.print_trait_sugared(); let condition_options = ConditionOptions { self_types, @@ -268,6 +265,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { // Unlike the generic_args earlier, // this one is *not* collected under `with_no_trimmed_paths!` // for printing the type to the user + // + // This includes `Self`, as it is the first parameter in `own_params`. let generic_args = self .tcx .generics_of(trait_pred.trait_ref.def_id) @@ -341,6 +340,63 @@ pub enum AppendConstMessage { Custom(Symbol, Span), } +#[derive(LintDiagnostic)] +#[diag(trait_selection_malformed_on_unimplemented_attr)] +#[help] +pub struct MalformedOnUnimplementedAttrLint { + #[label] + pub span: Span, +} + +impl MalformedOnUnimplementedAttrLint { + pub fn new(span: Span) -> Self { + Self { span } + } +} + +#[derive(LintDiagnostic)] +#[diag(trait_selection_missing_options_for_on_unimplemented_attr)] +#[help] +pub struct MissingOptionsForOnUnimplementedAttr; + +#[derive(LintDiagnostic)] +#[diag(trait_selection_ignored_diagnostic_option)] +pub struct IgnoredDiagnosticOption { + pub option_name: &'static str, + #[label] + pub span: Span, + #[label(trait_selection_other_label)] + pub prev_span: Span, +} + +impl IgnoredDiagnosticOption { + pub fn maybe_emit_warning<'tcx>( + tcx: TyCtxt<'tcx>, + item_def_id: DefId, + new: Option, + old: Option, + option_name: &'static str, + ) { + if let (Some(new_item), Some(old_item)) = (new, old) { + if let Some(item_def_id) = item_def_id.as_local() { + tcx.emit_node_span_lint( + UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, + tcx.local_def_id_to_hir_id(item_def_id), + new_item, + IgnoredDiagnosticOption { span: new_item, prev_span: old_item, option_name }, + ); + } + } + } +} + +#[derive(LintDiagnostic)] +#[diag(trait_selection_wrapped_parser_error)] +pub struct WrappedParserError { + pub description: String, + pub label: String, +} + impl<'tcx> OnUnimplementedDirective { fn parse( tcx: TyCtxt<'tcx>, @@ -664,7 +720,7 @@ impl<'tcx> OnUnimplementedDirective { tcx: TyCtxt<'tcx>, trait_ref: ty::TraitRef<'tcx>, condition_options: &ConditionOptions, - args: &FormatArgs, + args: &FormatArgs<'tcx>, ) -> OnUnimplementedNote { let mut message = None; let mut label = None; @@ -784,7 +840,7 @@ impl<'tcx> OnUnimplementedFormatString { &self, tcx: TyCtxt<'tcx>, trait_ref: ty::TraitRef<'tcx>, - args: &FormatArgs, + args: &FormatArgs<'tcx>, ) -> String { let trait_def_id = trait_ref.def_id; let ctx = if self.is_diagnostic_namespace_variant { diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_condition.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_condition.rs index 491ba6d7ffc08..116cfb01cb631 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_condition.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_condition.rs @@ -2,19 +2,10 @@ use rustc_ast::MetaItemInner; use rustc_attr_parsing as attr; use rustc_middle::ty::{self, TyCtxt}; use rustc_parse_format::{ParseMode, Parser, Piece, Position}; -use rustc_span::{Span, Symbol, kw, sym}; - -pub static ALLOWED_CONDITION_SYMBOLS: &[Symbol] = &[ - sym::from_desugaring, - sym::direct, - sym::cause, - sym::integral, - sym::integer_, - sym::float, - sym::_Self, - sym::crate_local, -]; +use rustc_span::{DesugaringKind, Span, Symbol, kw, sym}; +/// A predicate in an attribute using on, all, any, +/// similar to a cfg predicate. #[derive(Debug)] pub struct Condition { pub inner: MetaItemInner, @@ -31,8 +22,7 @@ impl Condition { // `with_no_visible_paths` is also used when generating the options, // so we need to match it here. ty::print::with_no_visible_paths!({ - let mut parser = Parser::new(v.as_str(), None, None, false, ParseMode::Format); - let constructed_message = (&mut parser) + Parser::new(v.as_str(), None, None, false, ParseMode::Format) .map(|p| match p { Piece::Lit(s) => s.to_owned(), Piece::NextArgument(a) => match a.position { @@ -47,8 +37,7 @@ impl Condition { Position::ArgumentIs(idx) => format!("{{{idx}}}"), }, }) - .collect(); - constructed_message + .collect() }) }); @@ -57,13 +46,57 @@ impl Condition { } } +/// Used with `Condition::matches_predicate` to test whether the condition applies +/// +/// For example, given a +/// ```rust,ignore (just an example) +/// #[rustc_on_unimplemented( +/// on(all(from_desugaring = "QuestionMark"), +/// message = "the `?` operator can only be used in {ItemContext} \ +/// that returns `Result` or `Option` \ +/// (or another type that implements `{FromResidual}`)", +/// label = "cannot use the `?` operator in {ItemContext} that returns `{Self}`", +/// parent_label = "this function should return `Result` or `Option` to accept `?`" +/// ), +/// )] +/// pub trait FromResidual::Residual> { +/// ... +/// } +/// +/// async fn an_async_function() -> u32 { +/// let x: Option = None; +/// x?; //~ ERROR the `?` operator +/// 22 +/// } +/// ``` +/// it will look like this: +/// +/// ```rust,ignore (just an example) +/// ConditionOptions { +/// self_types: ["u32", "{integral}"], +/// from_desugaring: Some("QuestionMark"), +/// cause: None, +/// crate_local: false, +/// direct: true, +/// generic_args: [("Self","u32"), +/// ("R", "core::option::Option"), +/// ("R", "core::option::Option" ), +/// ], +/// } +/// ``` #[derive(Debug)] pub struct ConditionOptions { + /// All the self types that may apply. + /// for example pub self_types: Vec, - pub from_desugaring: Option, + // The kind of compiler desugaring. + pub from_desugaring: Option, + /// Match on a variant of [rustc_infer::traits::ObligationCauseCode] pub cause: Option, pub crate_local: bool, + /// Is the obligation "directly" user-specified, rather than derived? pub direct: bool, + // A list of the generic arguments and their reified types pub generic_args: Vec<(Symbol, String)>, } @@ -74,7 +107,7 @@ impl ConditionOptions { // from_desugaring as a flag (sym::from_desugaring, None) => self.from_desugaring.is_some(), // from_desugaring as key == value - (sym::from_desugaring, v) => *v == self.from_desugaring, + (sym::from_desugaring, Some(v)) if let Some(ds) = self.from_desugaring => ds.matches(v), (sym::cause, Some(value)) => self.cause.as_deref() == Some(value), (sym::crate_local, None) => self.crate_local, (sym::direct, None) => self.direct, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs index 1bf15a3450947..f835406122b8b 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented_format.rs @@ -1,5 +1,8 @@ +use std::fmt; + use errors::*; use rustc_middle::ty::TyCtxt; +use rustc_middle::ty::print::TraitRefPrintSugared; use rustc_parse_format::{ Alignment, Argument, Count, FormatSpec, InnerSpan, ParseError, ParseMode, Parser, Piece as RpfPiece, Position, @@ -8,28 +11,39 @@ use rustc_session::lint::builtin::UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES; use rustc_span::def_id::DefId; use rustc_span::{BytePos, Pos, Span, Symbol, kw, sym}; -#[allow(dead_code)] +/// Like [std::fmt::Arguments] this is a string that has been parsed into "pieces", +/// either as string pieces or dynamic arguments. +#[derive(Debug)] pub struct FormatString { + #[allow(dead_code, reason = "Debug impl")] input: Symbol, - input_span: Span, + span: Span, pieces: Vec, - // the formatting string was parsed succesfully but with warnings + /// The formatting string was parsed succesfully but with warnings pub warnings: Vec, } +#[derive(Debug)] enum Piece { Lit(String), Arg(FormatArg), } -pub enum FormatArg { +#[derive(Debug)] +enum FormatArg { // A generic parameter, like `{T}` if we're on the `From` trait. - GenericParam { generic_param: Symbol, span: Span }, + GenericParam { + generic_param: Symbol, + }, // `{Self}` SelfUpper, + /// `{This}` or `{TraitName}` This, + /// The sugared form of the trait Trait, + /// what we're in, like a function, method, closure etc. ItemContext, + /// What the user typed, if it doesn't match anything we can use. AsIs(String), } @@ -40,6 +54,7 @@ pub enum Ctx<'tcx> { DiagnosticOnUnimplemented { tcx: TyCtxt<'tcx>, trait_def_id: DefId }, } +#[derive(Debug)] pub enum FormatWarning { UnknownParam { argument_name: Symbol, span: Span }, PositionalArgument { span: Span, help: String }, @@ -95,26 +110,58 @@ impl FormatWarning { } } +/// Arguments to fill a [FormatString] with. +/// +/// For example, given a +/// ```rust,ignore (just an example) +/// +/// #[rustc_on_unimplemented( +/// on(all(from_desugaring = "QuestionMark"), +/// message = "the `?` operator can only be used in {ItemContext} \ +/// that returns `Result` or `Option` \ +/// (or another type that implements `{FromResidual}`)", +/// label = "cannot use the `?` operator in {ItemContext} that returns `{Self}`", +/// parent_label = "this function should return `Result` or `Option` to accept `?`" +/// ), +/// )] +/// pub trait FromResidual::Residual> { +/// ... +/// } +/// +/// async fn an_async_function() -> u32 { +/// let x: Option = None; +/// x?; //~ ERROR the `?` operator +/// 22 +/// } +/// ``` +/// it will look like this: +/// +/// ```rust,ignore (just an example) +/// FormatArgs { +/// this: "FromResidual", +/// trait_sugared: "FromResidual>", +/// item_context: "an async function", +/// generic_args: [("Self", "u32"), ("R", "Option")], +/// } +/// ``` #[derive(Debug)] -pub struct ConditionOptions { - pub self_types: Vec, - pub from_desugaring: Option, - pub cause: Option, - pub crate_local: bool, - pub direct: bool, - pub generic_args: Vec<(Symbol, String)>, -} - -#[derive(Debug)] -pub struct FormatArgs { +pub struct FormatArgs<'tcx> { pub this: String, - pub trait_sugared: String, - pub item_context: String, + pub trait_sugared: TraitRefPrintSugared<'tcx>, + pub item_context: &'static str, pub generic_args: Vec<(Symbol, String)>, } impl FormatString { - pub fn parse(input: Symbol, input_span: Span, ctx: &Ctx<'_>) -> Result> { + pub fn span(&self) -> Span { + self.span + } + + pub fn parse<'tcx>( + input: Symbol, + span: Span, + ctx: &Ctx<'tcx>, + ) -> Result> { let s = input.as_str(); let mut parser = Parser::new(s, None, None, false, ParseMode::Format); let mut pieces = Vec::new(); @@ -126,28 +173,28 @@ impl FormatString { pieces.push(Piece::Lit(lit.into())); } RpfPiece::NextArgument(arg) => { - warn_on_format_spec(arg.format, &mut warnings, input_span); - let arg = parse_arg(&arg, ctx, &mut warnings, input_span); + warn_on_format_spec(arg.format, &mut warnings, span); + let arg = parse_arg(&arg, ctx, &mut warnings, span); pieces.push(Piece::Arg(arg)); } } } if parser.errors.is_empty() { - Ok(FormatString { input, input_span, pieces, warnings }) + Ok(FormatString { input, pieces, span, warnings }) } else { Err(parser.errors) } } - pub fn format(&self, args: &FormatArgs) -> String { + pub fn format(&self, args: &FormatArgs<'_>) -> String { let mut ret = String::new(); for piece in &self.pieces { match piece { Piece::Lit(s) | Piece::Arg(FormatArg::AsIs(s)) => ret.push_str(&s), // `A` if we have `trait Trait {}` and `note = "i'm the actual type of {A}"` - Piece::Arg(FormatArg::GenericParam { generic_param, .. }) => { + Piece::Arg(FormatArg::GenericParam { generic_param }) => { // Should always be some but we can't raise errors here let value = match args.generic_args.iter().find(|(p, _)| p == generic_param) { Some((_, val)) => val.to_string(), @@ -166,17 +213,19 @@ impl FormatString { // It's only `rustc_onunimplemented` from here Piece::Arg(FormatArg::This) => ret.push_str(&args.this), - Piece::Arg(FormatArg::Trait) => ret.push_str(&args.trait_sugared), - Piece::Arg(FormatArg::ItemContext) => ret.push_str(&args.item_context), + Piece::Arg(FormatArg::Trait) => { + let _ = fmt::write(&mut ret, format_args!("{}", &args.trait_sugared)); + } + Piece::Arg(FormatArg::ItemContext) => ret.push_str(args.item_context), } } ret } } -fn parse_arg( +fn parse_arg<'tcx>( arg: &Argument<'_>, - ctx: &Ctx<'_>, + ctx: &Ctx<'tcx>, warnings: &mut Vec, input_span: Span, ) -> FormatArg { @@ -233,7 +282,7 @@ fn parse_arg( Ctx::RustcOnUnimplemented { .. } | Ctx::DiagnosticOnUnimplemented { .. }, generic_param, ) if generics.own_params.iter().any(|param| param.name == generic_param) => { - FormatArg::GenericParam { generic_param, span } + FormatArg::GenericParam { generic_param } } (_, argument_name) => { @@ -286,6 +335,7 @@ fn warn_on_format_spec(spec: FormatSpec<'_>, warnings: &mut Vec, } } +/// Helper function because `Span` and `rustc_parse_format::InnerSpan` don't know about each other fn slice_span(input: Span, inner: InnerSpan) -> Span { let InnerSpan { start, end } = inner; let span = input.data(); @@ -300,8 +350,6 @@ fn slice_span(input: Span, inner: InnerSpan) -> Span { pub mod errors { use rustc_macros::LintDiagnostic; - use rustc_middle::ty::TyCtxt; - use rustc_session::lint::builtin::UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES; use rustc_span::Ident; use super::*; @@ -324,26 +372,6 @@ pub mod errors { #[help] pub struct InvalidFormatSpecifier; - #[derive(LintDiagnostic)] - #[diag(trait_selection_wrapped_parser_error)] - pub struct WrappedParserError { - pub description: String, - pub label: String, - } - #[derive(LintDiagnostic)] - #[diag(trait_selection_malformed_on_unimplemented_attr)] - #[help] - pub struct MalformedOnUnimplementedAttrLint { - #[label] - pub span: Span, - } - - impl MalformedOnUnimplementedAttrLint { - pub fn new(span: Span) -> Self { - Self { span } - } - } - #[derive(LintDiagnostic)] #[diag(trait_selection_missing_options_for_on_unimplemented_attr)] #[help] From 9abaa9d4dffeb897a1dbff97d32d3b6ac190be21 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Sat, 29 Mar 2025 11:46:03 +0100 Subject: [PATCH 083/266] Disable usage on trait impls and aliases --- .../traits/on_unimplemented.rs | 17 +++++++--- tests/crashes/130627.rs | 20 ------------ .../ui/diagnostic_namespace/on_impl_trait.rs | 17 ++++++++++ .../diagnostic_namespace/on_impl_trait.stderr | 31 +++++++++++++++++++ tests/ui/on-unimplemented/impl-substs.stderr | 2 +- .../ui/on-unimplemented/multiple-impls.stderr | 12 +++---- tests/ui/on-unimplemented/on-impl.stderr | 4 +-- 7 files changed, 68 insertions(+), 35 deletions(-) delete mode 100644 tests/crashes/130627.rs create mode 100644 tests/ui/diagnostic_namespace/on_impl_trait.rs create mode 100644 tests/ui/diagnostic_namespace/on_impl_trait.stderr diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs index 0478f3a7f1127..ca51f177f964b 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs @@ -553,6 +553,13 @@ impl<'tcx> OnUnimplementedDirective { } pub fn of_item(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> Result, ErrorGuaranteed> { + if !tcx.is_trait(item_def_id) { + // It could be a trait_alias (`trait MyTrait = SomeOtherTrait`) + // or an implementation (`impl MyTrait for Foo {}`) + // + // We don't support those. + return Ok(None); + } if let Some(attr) = tcx.get_attr(item_def_id, sym::rustc_on_unimplemented) { return Self::parse_attribute(attr, false, tcx, item_def_id); } else { @@ -782,8 +789,10 @@ impl<'tcx> OnUnimplementedFormatString { Ok(result) } - fn verify(&self, tcx: TyCtxt<'tcx>, item_def_id: DefId) -> Result<(), ErrorGuaranteed> { - let trait_def_id = if tcx.is_trait(item_def_id) { item_def_id } else { return Ok(()) }; + fn verify(&self, tcx: TyCtxt<'tcx>, trait_def_id: DefId) -> Result<(), ErrorGuaranteed> { + if !tcx.is_trait(trait_def_id) { + return Ok(()); + }; let ctx = if self.is_diagnostic_namespace_variant { Ctx::DiagnosticOnUnimplemented { tcx, trait_def_id } @@ -810,10 +819,10 @@ impl<'tcx> OnUnimplementedFormatString { // so that users are aware that something is not correct for e in errors { if self.is_diagnostic_namespace_variant { - if let Some(item_def_id) = item_def_id.as_local() { + if let Some(trait_def_id) = trait_def_id.as_local() { tcx.emit_node_span_lint( UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, - tcx.local_def_id_to_hir_id(item_def_id), + tcx.local_def_id_to_hir_id(trait_def_id), self.span, WrappedParserError { description: e.description, label: e.label }, ); diff --git a/tests/crashes/130627.rs b/tests/crashes/130627.rs deleted file mode 100644 index 59d3606592bf1..0000000000000 --- a/tests/crashes/130627.rs +++ /dev/null @@ -1,20 +0,0 @@ -//@ known-bug: #130627 - -#![feature(trait_alias)] - -trait Test {} - -#[diagnostic::on_unimplemented( - message="message", - label="label", - note="note" -)] -trait Alias = Test; - -// Use trait alias as bound on type parameter. -fn foo(v: &T) { -} - -pub fn main() { - foo(&1); -} diff --git a/tests/ui/diagnostic_namespace/on_impl_trait.rs b/tests/ui/diagnostic_namespace/on_impl_trait.rs new file mode 100644 index 0000000000000..32a492c53a950 --- /dev/null +++ b/tests/ui/diagnostic_namespace/on_impl_trait.rs @@ -0,0 +1,17 @@ +// used to ICE, see +// Instead it should just ignore the diagnostic attribute +#![feature(trait_alias)] + +trait Test {} + +#[diagnostic::on_unimplemented(message = "blah", label = "blah", note = "blah")] +//~^ WARN `#[diagnostic::on_unimplemented]` can only be applied to trait definitions +trait Alias = Test; + +// Use trait alias as bound on type parameter. +fn foo(v: &T) {} + +pub fn main() { + foo(&1); + //~^ ERROR the trait bound `{integer}: Alias` is not satisfied +} diff --git a/tests/ui/diagnostic_namespace/on_impl_trait.stderr b/tests/ui/diagnostic_namespace/on_impl_trait.stderr new file mode 100644 index 0000000000000..59b9c31bc53ea --- /dev/null +++ b/tests/ui/diagnostic_namespace/on_impl_trait.stderr @@ -0,0 +1,31 @@ +warning: `#[diagnostic::on_unimplemented]` can only be applied to trait definitions + --> $DIR/on_impl_trait.rs:7:1 + | +LL | #[diagnostic::on_unimplemented(message = "blah", label = "blah", note = "blah")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: `#[warn(unknown_or_malformed_diagnostic_attributes)]` on by default + +error[E0277]: the trait bound `{integer}: Alias` is not satisfied + --> $DIR/on_impl_trait.rs:15:9 + | +LL | foo(&1); + | --- ^^ the trait `Test` is not implemented for `{integer}` + | | + | required by a bound introduced by this call + | +help: this trait has no implementations, consider adding one + --> $DIR/on_impl_trait.rs:5:1 + | +LL | trait Test {} + | ^^^^^^^^^^ + = note: required for `{integer}` to implement `Alias` +note: required by a bound in `foo` + --> $DIR/on_impl_trait.rs:12:11 + | +LL | fn foo(v: &T) {} + | ^^^^^ required by this bound in `foo` + +error: aborting due to 1 previous error; 1 warning emitted + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/on-unimplemented/impl-substs.stderr b/tests/ui/on-unimplemented/impl-substs.stderr index 0eabe9714922c..2d83845ecb822 100644 --- a/tests/ui/on-unimplemented/impl-substs.stderr +++ b/tests/ui/on-unimplemented/impl-substs.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `(i32, i32, i32): Foo` is not satisfied --> $DIR/impl-substs.rs:13:23 | LL | Foo::::foo((1i32, 1i32, 1i32)); - | ----------------- ^^^^^^^^^^^^^^^^^^ an impl did not match: usize {B} {C} + | ----------------- ^^^^^^^^^^^^^^^^^^ the trait `Foo` is not implemented for `(i32, i32, i32)` | | | required by a bound introduced by this call | diff --git a/tests/ui/on-unimplemented/multiple-impls.stderr b/tests/ui/on-unimplemented/multiple-impls.stderr index ba4e43ff3594f..2afc9b1bf3b8a 100644 --- a/tests/ui/on-unimplemented/multiple-impls.stderr +++ b/tests/ui/on-unimplemented/multiple-impls.stderr @@ -15,11 +15,10 @@ error[E0277]: the trait bound `[i32]: Index>` is not satisfied --> $DIR/multiple-impls.rs:36:33 | LL | Index::index(&[] as &[i32], Foo(2u32)); - | ------------ ^^^^^^^^^ on impl for Foo + | ------------ ^^^^^^^^^ the trait `Index>` is not implemented for `[i32]` | | | required by a bound introduced by this call | - = help: the trait `Index>` is not implemented for `[i32]` = help: the following other types implement trait `Index`: `[i32]` implements `Index>` `[i32]` implements `Index>` @@ -28,11 +27,10 @@ error[E0277]: the trait bound `[i32]: Index>` is not satisfied --> $DIR/multiple-impls.rs:39:33 | LL | Index::index(&[] as &[i32], Bar(2u32)); - | ------------ ^^^^^^^^^ on impl for Bar + | ------------ ^^^^^^^^^ the trait `Index>` is not implemented for `[i32]` | | | required by a bound introduced by this call | - = help: the trait `Index>` is not implemented for `[i32]` = help: the following other types implement trait `Index`: `[i32]` implements `Index>` `[i32]` implements `Index>` @@ -52,9 +50,8 @@ error[E0277]: the trait bound `[i32]: Index>` is not satisfied --> $DIR/multiple-impls.rs:36:5 | LL | Index::index(&[] as &[i32], Foo(2u32)); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ on impl for Foo + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Index>` is not implemented for `[i32]` | - = help: the trait `Index>` is not implemented for `[i32]` = help: the following other types implement trait `Index`: `[i32]` implements `Index>` `[i32]` implements `Index>` @@ -63,9 +60,8 @@ error[E0277]: the trait bound `[i32]: Index>` is not satisfied --> $DIR/multiple-impls.rs:39:5 | LL | Index::index(&[] as &[i32], Bar(2u32)); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ on impl for Bar + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Index>` is not implemented for `[i32]` | - = help: the trait `Index>` is not implemented for `[i32]` = help: the following other types implement trait `Index`: `[i32]` implements `Index>` `[i32]` implements `Index>` diff --git a/tests/ui/on-unimplemented/on-impl.stderr b/tests/ui/on-unimplemented/on-impl.stderr index 5e7e2c4ea7744..922db9db116ee 100644 --- a/tests/ui/on-unimplemented/on-impl.stderr +++ b/tests/ui/on-unimplemented/on-impl.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `[i32]: Index` is not satisfied --> $DIR/on-impl.rs:22:47 | LL | Index::::index(&[1, 2, 3] as &[i32], 2u32); - | ------------------- ^^^^ a usize is required to index into a slice + | ------------------- ^^^^ the trait `Index` is not implemented for `[i32]` | | | required by a bound introduced by this call | @@ -14,7 +14,7 @@ error[E0277]: the trait bound `[i32]: Index` is not satisfied --> $DIR/on-impl.rs:22:5 | LL | Index::::index(&[1, 2, 3] as &[i32], 2u32); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ a usize is required to index into a slice + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Index` is not implemented for `[i32]` | = help: the trait `Index` is not implemented for `[i32]` but trait `Index` is implemented for it From 10ec5cbe96b8b1ba96fbacc207d6a2f0d19ca9e2 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Sat, 29 Mar 2025 13:48:14 +0100 Subject: [PATCH 084/266] Raise errors on bad rustc_on_unimplemented format strings again --- .../traits/on_unimplemented.rs | 38 +++++++++++++++++-- tests/ui/on-unimplemented/bad-annotation.rs | 2 +- .../ui/on-unimplemented/bad-annotation.stderr | 14 +++---- 3 files changed, 41 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs index ca51f177f964b..4c4491269b757 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs @@ -18,7 +18,9 @@ use {rustc_attr_parsing as attr, rustc_hir as hir}; use super::{ObligationCauseCode, PredicateObligation}; use crate::error_reporting::TypeErrCtxt; use crate::error_reporting::traits::on_unimplemented_condition::{Condition, ConditionOptions}; -use crate::error_reporting::traits::on_unimplemented_format::{Ctx, FormatArgs, FormatString}; +use crate::error_reporting::traits::on_unimplemented_format::{ + Ctx, FormatArgs, FormatString, FormatWarning, +}; use crate::errors::{ EmptyOnClauseInOnUnimplemented, InvalidOnClauseInOnUnimplemented, NoValueInOnUnimplemented, }; @@ -806,8 +808,38 @@ impl<'tcx> OnUnimplementedFormatString { // Warnings about format specifiers, deprecated parameters, wrong parameters etc. // In other words we'd like to let the author know, but we can still try to format the string later Ok(FormatString { warnings, .. }) => { - for w in warnings { - w.emit_warning(tcx, trait_def_id) + if self.is_diagnostic_namespace_variant { + for w in warnings { + w.emit_warning(tcx, trait_def_id) + } + } else { + for w in warnings { + match w { + FormatWarning::UnknownParam { argument_name, span } => { + let reported = struct_span_code_err!( + tcx.dcx(), + span, + E0230, + "cannot find parameter {} on this trait", + argument_name, + ) + .emit(); + result = Err(reported); + } + FormatWarning::PositionalArgument { span, .. } => { + let reported = struct_span_code_err!( + tcx.dcx(), + span, + E0231, + "positional format arguments are not allowed here" + ) + .emit(); + result = Err(reported); + } + FormatWarning::InvalidSpecifier { .. } + | FormatWarning::FutureIncompat { .. } => {} + } + } } } // Errors from the underlying `rustc_parse_format::Parser` diff --git a/tests/ui/on-unimplemented/bad-annotation.rs b/tests/ui/on-unimplemented/bad-annotation.rs index 0936b25847c4c..f2b978657597a 100644 --- a/tests/ui/on-unimplemented/bad-annotation.rs +++ b/tests/ui/on-unimplemented/bad-annotation.rs @@ -20,7 +20,7 @@ trait BadAnnotation1 {} #[rustc_on_unimplemented = "Unimplemented trait error on `{Self}` with params `<{A},{B},{C}>`"] -//~^ WARNING there is no parameter `C` on trait `BadAnnotation2` +//~^ ERROR cannot find parameter C on this trait trait BadAnnotation2 {} diff --git a/tests/ui/on-unimplemented/bad-annotation.stderr b/tests/ui/on-unimplemented/bad-annotation.stderr index 1fefd93aa7ecb..afd737dc85e69 100644 --- a/tests/ui/on-unimplemented/bad-annotation.stderr +++ b/tests/ui/on-unimplemented/bad-annotation.stderr @@ -11,22 +11,17 @@ LL | #[rustc_on_unimplemented = "message"] LL | #[rustc_on_unimplemented(/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...")] | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -warning: there is no parameter `C` on trait `BadAnnotation2` +error[E0230]: cannot find parameter C on this trait --> $DIR/bad-annotation.rs:22:90 | LL | #[rustc_on_unimplemented = "Unimplemented trait error on `{Self}` with params `<{A},{B},{C}>`"] | ^ - | - = help: expect either a generic argument name or `{Self}` as format argument - = note: `#[warn(unknown_or_malformed_diagnostic_attributes)]` on by default -warning: positional format arguments are not allowed here +error[E0231]: positional format arguments are not allowed here --> $DIR/bad-annotation.rs:27:90 | LL | #[rustc_on_unimplemented = "Unimplemented trait error on `{Self}` with params `<{A},{B},{}>`"] | ^ - | - = help: only named format arguments with the name of one of the generic types are allowed in this context error[E0232]: this attribute must have a valid value --> $DIR/bad-annotation.rs:32:26 @@ -82,6 +77,7 @@ LL | #[rustc_on_unimplemented(on(desugared, on(desugared, message="x")), message | = note: eg `#[rustc_on_unimplemented(message="foo")]` -error: aborting due to 8 previous errors; 2 warnings emitted +error: aborting due to 10 previous errors -For more information about this error, try `rustc --explain E0232`. +Some errors have detailed explanations: E0230, E0231, E0232. +For more information about an error, try `rustc --explain E0230`. From 40e76c157548442fce755ec9cc2274aef11454ba Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Tue, 1 Apr 2025 02:47:12 +0200 Subject: [PATCH 085/266] Test that `Self` properly works in filters --- .../ui/on-unimplemented/use_self_no_underscore.rs | 14 ++++++++++++++ .../use_self_no_underscore.stderr | 15 +++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 tests/ui/on-unimplemented/use_self_no_underscore.rs create mode 100644 tests/ui/on-unimplemented/use_self_no_underscore.stderr diff --git a/tests/ui/on-unimplemented/use_self_no_underscore.rs b/tests/ui/on-unimplemented/use_self_no_underscore.rs new file mode 100644 index 0000000000000..045ef1a5d3ff0 --- /dev/null +++ b/tests/ui/on-unimplemented/use_self_no_underscore.rs @@ -0,0 +1,14 @@ +#![feature(rustc_attrs)] + +#[rustc_on_unimplemented(on( + all(A = "{integer}", any(Self = "[{integral}; _]",)), + message = "an array of type `{Self}` cannot be built directly from an iterator", +))] +pub trait FromIterator: Sized { + fn from_iter>(iter: T) -> Self; +} +fn main() { + let iter = 0..42_8; + let x: [u8; 8] = FromIterator::from_iter(iter); + //~^ ERROR an array of type `[u8; 8]` cannot be built directly from an iterator +} diff --git a/tests/ui/on-unimplemented/use_self_no_underscore.stderr b/tests/ui/on-unimplemented/use_self_no_underscore.stderr new file mode 100644 index 0000000000000..d01aee3485f4c --- /dev/null +++ b/tests/ui/on-unimplemented/use_self_no_underscore.stderr @@ -0,0 +1,15 @@ +error[E0277]: an array of type `[u8; 8]` cannot be built directly from an iterator + --> $DIR/use_self_no_underscore.rs:12:22 + | +LL | let x: [u8; 8] = FromIterator::from_iter(iter); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromIterator<{integer}>` is not implemented for `[u8; 8]` + | +help: this trait has no implementations, consider adding one + --> $DIR/use_self_no_underscore.rs:7:1 + | +LL | pub trait FromIterator: Sized { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. From 4a5369b476fb17aa2db05b5b551eca0cfa6b2c6b Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 10 Apr 2025 16:06:59 +0200 Subject: [PATCH 086/266] Remove rustc_on_unimplemented on impl tests --- src/tools/tidy/src/issues.txt | 1 - tests/ui/on-unimplemented/impl-substs.rs | 15 ---- tests/ui/on-unimplemented/impl-substs.stderr | 15 ---- tests/ui/on-unimplemented/issue-104140.rs | 8 --- tests/ui/on-unimplemented/issue-104140.stderr | 15 ---- tests/ui/on-unimplemented/multiple-impls.rs | 42 ----------- .../ui/on-unimplemented/multiple-impls.stderr | 71 ------------------- tests/ui/on-unimplemented/on-impl.rs | 25 ------- tests/ui/on-unimplemented/on-impl.stderr | 25 ------- 9 files changed, 217 deletions(-) delete mode 100644 tests/ui/on-unimplemented/impl-substs.rs delete mode 100644 tests/ui/on-unimplemented/impl-substs.stderr delete mode 100644 tests/ui/on-unimplemented/issue-104140.rs delete mode 100644 tests/ui/on-unimplemented/issue-104140.stderr delete mode 100644 tests/ui/on-unimplemented/multiple-impls.rs delete mode 100644 tests/ui/on-unimplemented/multiple-impls.stderr delete mode 100644 tests/ui/on-unimplemented/on-impl.rs delete mode 100644 tests/ui/on-unimplemented/on-impl.stderr diff --git a/src/tools/tidy/src/issues.txt b/src/tools/tidy/src/issues.txt index d2ae9b1f6ef89..5fa4a9fc2e36e 100644 --- a/src/tools/tidy/src/issues.txt +++ b/src/tools/tidy/src/issues.txt @@ -3138,7 +3138,6 @@ ui/nll/user-annotations/issue-55241.rs ui/nll/user-annotations/issue-55748-pat-types-constrain-bindings.rs ui/nll/user-annotations/issue-57731-ascibed-coupled-types.rs ui/numbers-arithmetic/issue-8460.rs -ui/on-unimplemented/issue-104140.rs ui/or-patterns/issue-64879-trailing-before-guard.rs ui/or-patterns/issue-67514-irrefutable-param.rs ui/or-patterns/issue-68785-irrefutable-param-with-at.rs diff --git a/tests/ui/on-unimplemented/impl-substs.rs b/tests/ui/on-unimplemented/impl-substs.rs deleted file mode 100644 index fe9c50ec3d4a2..0000000000000 --- a/tests/ui/on-unimplemented/impl-substs.rs +++ /dev/null @@ -1,15 +0,0 @@ -#![feature(rustc_attrs)] - -trait Foo { - fn foo(self); -} - -#[rustc_on_unimplemented = "an impl did not match: {A} {B} {C}"] -impl Foo for (A, B, C) { - fn foo(self) {} -} - -fn main() { - Foo::::foo((1i32, 1i32, 1i32)); - //~^ ERROR the trait bound `(i32, i32, i32): Foo` is not satisfied -} diff --git a/tests/ui/on-unimplemented/impl-substs.stderr b/tests/ui/on-unimplemented/impl-substs.stderr deleted file mode 100644 index 2d83845ecb822..0000000000000 --- a/tests/ui/on-unimplemented/impl-substs.stderr +++ /dev/null @@ -1,15 +0,0 @@ -error[E0277]: the trait bound `(i32, i32, i32): Foo` is not satisfied - --> $DIR/impl-substs.rs:13:23 - | -LL | Foo::::foo((1i32, 1i32, 1i32)); - | ----------------- ^^^^^^^^^^^^^^^^^^ the trait `Foo` is not implemented for `(i32, i32, i32)` - | | - | required by a bound introduced by this call - | - = help: the trait `Foo` is not implemented for `(i32, i32, i32)` - but trait `Foo` is implemented for it - = help: for that trait implementation, expected `i32`, found `usize` - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/on-unimplemented/issue-104140.rs b/tests/ui/on-unimplemented/issue-104140.rs deleted file mode 100644 index ade3f727004ab..0000000000000 --- a/tests/ui/on-unimplemented/issue-104140.rs +++ /dev/null @@ -1,8 +0,0 @@ -#![feature(rustc_attrs)] - -trait Foo {} - -#[rustc_on_unimplemented] //~ ERROR malformed `rustc_on_unimplemented` attribute input -impl Foo for u32 {} - -fn main() {} diff --git a/tests/ui/on-unimplemented/issue-104140.stderr b/tests/ui/on-unimplemented/issue-104140.stderr deleted file mode 100644 index 3c317135dd43a..0000000000000 --- a/tests/ui/on-unimplemented/issue-104140.stderr +++ /dev/null @@ -1,15 +0,0 @@ -error: malformed `rustc_on_unimplemented` attribute input - --> $DIR/issue-104140.rs:5:1 - | -LL | #[rustc_on_unimplemented] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | -help: the following are the possible correct uses - | -LL | #[rustc_on_unimplemented = "message"] - | +++++++++++ -LL | #[rustc_on_unimplemented(/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...")] - | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -error: aborting due to 1 previous error - diff --git a/tests/ui/on-unimplemented/multiple-impls.rs b/tests/ui/on-unimplemented/multiple-impls.rs deleted file mode 100644 index b74957ebcd406..0000000000000 --- a/tests/ui/on-unimplemented/multiple-impls.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Test if the on_unimplemented message override works - -#![feature(rustc_attrs)] - - -struct Foo(T); -struct Bar(T); - -#[rustc_on_unimplemented = "trait message"] -trait Index { - type Output: ?Sized; - fn index(&self, index: Idx) -> &Self::Output; -} - -#[rustc_on_unimplemented = "on impl for Foo"] -impl Index> for [i32] { - type Output = i32; - fn index(&self, _index: Foo) -> &i32 { - loop {} - } -} - -#[rustc_on_unimplemented = "on impl for Bar"] -impl Index> for [i32] { - type Output = i32; - fn index(&self, _index: Bar) -> &i32 { - loop {} - } -} - - -fn main() { - Index::index(&[] as &[i32], 2u32); - //~^ ERROR E0277 - //~| ERROR E0277 - Index::index(&[] as &[i32], Foo(2u32)); - //~^ ERROR E0277 - //~| ERROR E0277 - Index::index(&[] as &[i32], Bar(2u32)); - //~^ ERROR E0277 - //~| ERROR E0277 -} diff --git a/tests/ui/on-unimplemented/multiple-impls.stderr b/tests/ui/on-unimplemented/multiple-impls.stderr deleted file mode 100644 index 2afc9b1bf3b8a..0000000000000 --- a/tests/ui/on-unimplemented/multiple-impls.stderr +++ /dev/null @@ -1,71 +0,0 @@ -error[E0277]: the trait bound `[i32]: Index` is not satisfied - --> $DIR/multiple-impls.rs:33:33 - | -LL | Index::index(&[] as &[i32], 2u32); - | ------------ ^^^^ trait message - | | - | required by a bound introduced by this call - | - = help: the trait `Index` is not implemented for `[i32]` - = help: the following other types implement trait `Index`: - `[i32]` implements `Index>` - `[i32]` implements `Index>` - -error[E0277]: the trait bound `[i32]: Index>` is not satisfied - --> $DIR/multiple-impls.rs:36:33 - | -LL | Index::index(&[] as &[i32], Foo(2u32)); - | ------------ ^^^^^^^^^ the trait `Index>` is not implemented for `[i32]` - | | - | required by a bound introduced by this call - | - = help: the following other types implement trait `Index`: - `[i32]` implements `Index>` - `[i32]` implements `Index>` - -error[E0277]: the trait bound `[i32]: Index>` is not satisfied - --> $DIR/multiple-impls.rs:39:33 - | -LL | Index::index(&[] as &[i32], Bar(2u32)); - | ------------ ^^^^^^^^^ the trait `Index>` is not implemented for `[i32]` - | | - | required by a bound introduced by this call - | - = help: the following other types implement trait `Index`: - `[i32]` implements `Index>` - `[i32]` implements `Index>` - -error[E0277]: the trait bound `[i32]: Index` is not satisfied - --> $DIR/multiple-impls.rs:33:5 - | -LL | Index::index(&[] as &[i32], 2u32); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ trait message - | - = help: the trait `Index` is not implemented for `[i32]` - = help: the following other types implement trait `Index`: - `[i32]` implements `Index>` - `[i32]` implements `Index>` - -error[E0277]: the trait bound `[i32]: Index>` is not satisfied - --> $DIR/multiple-impls.rs:36:5 - | -LL | Index::index(&[] as &[i32], Foo(2u32)); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Index>` is not implemented for `[i32]` - | - = help: the following other types implement trait `Index`: - `[i32]` implements `Index>` - `[i32]` implements `Index>` - -error[E0277]: the trait bound `[i32]: Index>` is not satisfied - --> $DIR/multiple-impls.rs:39:5 - | -LL | Index::index(&[] as &[i32], Bar(2u32)); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Index>` is not implemented for `[i32]` - | - = help: the following other types implement trait `Index`: - `[i32]` implements `Index>` - `[i32]` implements `Index>` - -error: aborting due to 6 previous errors - -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/on-unimplemented/on-impl.rs b/tests/ui/on-unimplemented/on-impl.rs deleted file mode 100644 index ab3e67d01fe44..0000000000000 --- a/tests/ui/on-unimplemented/on-impl.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Test if the on_unimplemented message override works - -#![feature(rustc_attrs)] - - -#[rustc_on_unimplemented = "invalid"] -trait Index { - type Output: ?Sized; - fn index(&self, index: Idx) -> &Self::Output; -} - -#[rustc_on_unimplemented = "a usize is required to index into a slice"] -impl Index for [i32] { - type Output = i32; - fn index(&self, index: usize) -> &i32 { - &self[index] - } -} - - -fn main() { - Index::::index(&[1, 2, 3] as &[i32], 2u32); - //~^ ERROR E0277 - //~| ERROR E0277 -} diff --git a/tests/ui/on-unimplemented/on-impl.stderr b/tests/ui/on-unimplemented/on-impl.stderr deleted file mode 100644 index 922db9db116ee..0000000000000 --- a/tests/ui/on-unimplemented/on-impl.stderr +++ /dev/null @@ -1,25 +0,0 @@ -error[E0277]: the trait bound `[i32]: Index` is not satisfied - --> $DIR/on-impl.rs:22:47 - | -LL | Index::::index(&[1, 2, 3] as &[i32], 2u32); - | ------------------- ^^^^ the trait `Index` is not implemented for `[i32]` - | | - | required by a bound introduced by this call - | - = help: the trait `Index` is not implemented for `[i32]` - but trait `Index` is implemented for it - = help: for that trait implementation, expected `usize`, found `u32` - -error[E0277]: the trait bound `[i32]: Index` is not satisfied - --> $DIR/on-impl.rs:22:5 - | -LL | Index::::index(&[1, 2, 3] as &[i32], 2u32); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Index` is not implemented for `[i32]` - | - = help: the trait `Index` is not implemented for `[i32]` - but trait `Index` is implemented for it - = help: for that trait implementation, expected `usize`, found `u32` - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0277`. From edfdb9205c9f507628d957b048420a8d3a29a0d2 Mon Sep 17 00:00:00 2001 From: xizheyin Date: Mon, 14 Apr 2025 14:00:04 +0800 Subject: [PATCH 087/266] Add ui test unreachable-by-call-arguments-issue-139627.rs Signed-off-by: xizheyin --- ...eachable-by-call-arguments-issue-139627.rs | 15 ++++++++ ...able-by-call-arguments-issue-139627.stderr | 36 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 tests/ui/reachable/unreachable-by-call-arguments-issue-139627.rs create mode 100644 tests/ui/reachable/unreachable-by-call-arguments-issue-139627.stderr diff --git a/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.rs b/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.rs new file mode 100644 index 0000000000000..422ae95e8b720 --- /dev/null +++ b/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.rs @@ -0,0 +1,15 @@ +#![deny(unreachable_code)] +#![deny(unused)] + +pub enum Void {} + +pub struct S(T); + +pub fn foo(void: Void, void1: Void) { //~ ERROR unused variable: `void1` + let s = S(void); //~ ERROR unused variable: `s` + drop(s); //~ ERROR unreachable expression + let s1 = S { 0: void1 }; + drop(s1); +} + +fn main() {} diff --git a/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.stderr b/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.stderr new file mode 100644 index 0000000000000..ce24705324e52 --- /dev/null +++ b/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.stderr @@ -0,0 +1,36 @@ +error: unreachable expression + --> $DIR/unreachable-by-call-arguments-issue-139627.rs:10:10 + | +LL | let s = S(void); + | ------- any code following this expression is unreachable +LL | drop(s); + | ^ unreachable expression + | +note: this expression has type `S`, which is uninhabited + --> $DIR/unreachable-by-call-arguments-issue-139627.rs:9:13 + | +LL | let s = S(void); + | ^^^^^^^ +note: the lint level is defined here + --> $DIR/unreachable-by-call-arguments-issue-139627.rs:2:9 + | +LL | #![deny(unused)] + | ^^^^^^ + = note: `#[deny(unreachable_code)]` implied by `#[deny(unused)]` + +error: unused variable: `s` + --> $DIR/unreachable-by-call-arguments-issue-139627.rs:9:9 + | +LL | let s = S(void); + | ^ help: if this is intentional, prefix it with an underscore: `_s` + | + = note: `#[deny(unused_variables)]` implied by `#[deny(unused)]` + +error: unused variable: `void1` + --> $DIR/unreachable-by-call-arguments-issue-139627.rs:8:24 + | +LL | pub fn foo(void: Void, void1: Void) { + | ^^^^^ help: if this is intentional, prefix it with an underscore: `_void1` + +error: aborting due to 3 previous errors + From 8c8212ef12b13ccb635c81aa9e29915dd1c189e5 Mon Sep 17 00:00:00 2001 From: xizheyin Date: Mon, 14 Apr 2025 14:29:14 +0800 Subject: [PATCH 088/266] Consistent with treating Ctor Call as Struct in liveness analysis Signed-off-by: xizheyin --- compiler/rustc_passes/src/liveness.rs | 5 ++- ...eachable-by-call-arguments-issue-139627.rs | 7 ++-- ...able-by-call-arguments-issue-139627.stderr | 36 ------------------- 3 files changed, 8 insertions(+), 40 deletions(-) delete mode 100644 tests/ui/reachable/unreachable-by-call-arguments-issue-139627.stderr diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index 06eb76c30c5fb..24fac19991113 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -1021,7 +1021,10 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { } hir::ExprKind::Call(ref f, args) => { - let succ = self.check_is_ty_uninhabited(expr, succ); + let is_ctor = |f: &Expr<'_>| matches!(f.kind, hir::ExprKind::Path(hir::QPath::Resolved(_, path)) if matches!(path.res, rustc_hir::def::Res::Def(rustc_hir::def::DefKind::Ctor(_, _), _))); + let succ = + if !is_ctor(f) { self.check_is_ty_uninhabited(expr, succ) } else { succ }; + let succ = self.propagate_through_exprs(args, succ); self.propagate_through_expr(f, succ) } diff --git a/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.rs b/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.rs index 422ae95e8b720..b3310ac1c754c 100644 --- a/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.rs +++ b/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.rs @@ -1,3 +1,4 @@ +//@ check-pass #![deny(unreachable_code)] #![deny(unused)] @@ -5,9 +6,9 @@ pub enum Void {} pub struct S(T); -pub fn foo(void: Void, void1: Void) { //~ ERROR unused variable: `void1` - let s = S(void); //~ ERROR unused variable: `s` - drop(s); //~ ERROR unreachable expression +pub fn foo(void: Void, void1: Void) { + let s = S(void); + drop(s); let s1 = S { 0: void1 }; drop(s1); } diff --git a/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.stderr b/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.stderr deleted file mode 100644 index ce24705324e52..0000000000000 --- a/tests/ui/reachable/unreachable-by-call-arguments-issue-139627.stderr +++ /dev/null @@ -1,36 +0,0 @@ -error: unreachable expression - --> $DIR/unreachable-by-call-arguments-issue-139627.rs:10:10 - | -LL | let s = S(void); - | ------- any code following this expression is unreachable -LL | drop(s); - | ^ unreachable expression - | -note: this expression has type `S`, which is uninhabited - --> $DIR/unreachable-by-call-arguments-issue-139627.rs:9:13 - | -LL | let s = S(void); - | ^^^^^^^ -note: the lint level is defined here - --> $DIR/unreachable-by-call-arguments-issue-139627.rs:2:9 - | -LL | #![deny(unused)] - | ^^^^^^ - = note: `#[deny(unreachable_code)]` implied by `#[deny(unused)]` - -error: unused variable: `s` - --> $DIR/unreachable-by-call-arguments-issue-139627.rs:9:9 - | -LL | let s = S(void); - | ^ help: if this is intentional, prefix it with an underscore: `_s` - | - = note: `#[deny(unused_variables)]` implied by `#[deny(unused)]` - -error: unused variable: `void1` - --> $DIR/unreachable-by-call-arguments-issue-139627.rs:8:24 - | -LL | pub fn foo(void: Void, void1: Void) { - | ^^^^^ help: if this is intentional, prefix it with an underscore: `_void1` - -error: aborting due to 3 previous errors - From e53f2a01cea46bd7f9181e76353bde190255ea20 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 15 Apr 2025 12:26:37 +1000 Subject: [PATCH 089/266] Remove some `kw::Empty` uses in rustdoc. Some `unwrap` uses here, but they are on paths involving item kinds that are known to have an identifier. --- src/librustdoc/clean/mod.rs | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 45a915719e9f2..736dd3a1d8652 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -117,7 +117,7 @@ pub(crate) fn clean_doc_module<'tcx>(doc: &DocModule<'tcx>, cx: &mut DocContext< hir::ItemKind::Use(path, kind) => { let hir::UsePath { segments, span, .. } = *path; let path = hir::Path { segments, res: *res, span }; - clean_use_statement_inner(import, name, &path, kind, cx, &mut Default::default()) + clean_use_statement_inner(import, Some(name), &path, kind, cx, &mut Default::default()) } _ => unreachable!(), } @@ -125,8 +125,7 @@ pub(crate) fn clean_doc_module<'tcx>(doc: &DocModule<'tcx>, cx: &mut DocContext< items.extend(doc.items.values().flat_map(|(item, renamed, _)| { // Now we actually lower the imports, skipping everything else. if let hir::ItemKind::Use(path, hir::UseKind::Glob) = item.kind { - let name = renamed.unwrap_or(kw::Empty); // using kw::Empty is a bit of a hack - clean_use_statement(item, name, path, hir::UseKind::Glob, cx, &mut inserted) + clean_use_statement(item, *renamed, path, hir::UseKind::Glob, cx, &mut inserted) } else { // skip everything else Vec::new() @@ -2792,10 +2791,11 @@ fn clean_maybe_renamed_item<'tcx>( use hir::ItemKind; let def_id = item.owner_id.to_def_id(); - let mut name = renamed.unwrap_or_else(|| { - // FIXME: using kw::Empty is a bit of a hack - cx.tcx.hir_opt_name(item.hir_id()).unwrap_or(kw::Empty) - }); + let mut name = if renamed.is_some() { + renamed + } else { + cx.tcx.hir_opt_name(item.hir_id()) + }; cx.with_param_env(def_id, |cx| { let kind = match item.kind { @@ -2836,7 +2836,7 @@ fn clean_maybe_renamed_item<'tcx>( item_type: Some(type_), })), item.owner_id.def_id.to_def_id(), - name, + name.unwrap(), import_id, renamed, )); @@ -2861,13 +2861,15 @@ fn clean_maybe_renamed_item<'tcx>( }), ItemKind::Impl(impl_) => return clean_impl(impl_, item.owner_id.def_id, cx), ItemKind::Macro(_, macro_def, MacroKind::Bang) => MacroItem(Macro { - source: display_macro_source(cx, name, macro_def), + source: display_macro_source(cx, name.unwrap(), macro_def), macro_rules: macro_def.macro_rules, }), - ItemKind::Macro(_, _, macro_kind) => clean_proc_macro(item, &mut name, macro_kind, cx), + ItemKind::Macro(_, _, macro_kind) => { + clean_proc_macro(item, name.as_mut().unwrap(), macro_kind, cx) + } // proc macros can have a name set by attributes ItemKind::Fn { ref sig, generics, body: body_id, .. } => { - clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx) + clean_fn_or_proc_macro(item, sig, generics, body_id, name.as_mut().unwrap(), cx) } ItemKind::Trait(_, _, _, generics, bounds, item_ids) => { let items = item_ids @@ -2883,7 +2885,7 @@ fn clean_maybe_renamed_item<'tcx>( })) } ItemKind::ExternCrate(orig_name, _) => { - return clean_extern_crate(item, name, orig_name, cx); + return clean_extern_crate(item, name.unwrap(), orig_name, cx); } ItemKind::Use(path, kind) => { return clean_use_statement(item, name, path, kind, cx, &mut FxHashSet::default()); @@ -2895,7 +2897,7 @@ fn clean_maybe_renamed_item<'tcx>( cx, kind, item.owner_id.def_id.to_def_id(), - name, + name.unwrap(), import_id, renamed, )] @@ -3006,7 +3008,7 @@ fn clean_extern_crate<'tcx>( fn clean_use_statement<'tcx>( import: &hir::Item<'tcx>, - name: Symbol, + name: Option, path: &hir::UsePath<'tcx>, kind: hir::UseKind, cx: &mut DocContext<'tcx>, @@ -3023,7 +3025,7 @@ fn clean_use_statement<'tcx>( fn clean_use_statement_inner<'tcx>( import: &hir::Item<'tcx>, - name: Symbol, + name: Option, path: &hir::Path<'tcx>, kind: hir::UseKind, cx: &mut DocContext<'tcx>, @@ -3042,7 +3044,7 @@ fn clean_use_statement_inner<'tcx>( let visibility = cx.tcx.visibility(import.owner_id); let attrs = cx.tcx.hir_attrs(import.hir_id()); let inline_attr = hir_attr_lists(attrs, sym::doc).get_word_attr(sym::inline); - let pub_underscore = visibility.is_public() && name == kw::Underscore; + let pub_underscore = visibility.is_public() && name == Some(kw::Underscore); let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id); let import_def_id = import.owner_id.def_id; @@ -3108,6 +3110,7 @@ fn clean_use_statement_inner<'tcx>( } Import::new_glob(resolve_use_source(cx, path), true) } else { + let name = name.unwrap(); if inline_attr.is_none() && let Res::Def(DefKind::Mod, did) = path.res && !did.is_local() From 31320a925f53264a1905c5228392de9638bf2d52 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 15 Apr 2025 12:28:18 +1000 Subject: [PATCH 090/266] Remove another `kw::Empty` use in rustdoc. Again by using `Option` to represent "no name". --- src/librustdoc/clean/mod.rs | 35 ++++++++++++++++-------------- src/librustdoc/clean/types.rs | 4 ++-- src/librustdoc/html/format.rs | 8 ++++--- src/librustdoc/json/conversions.rs | 7 ++++-- 4 files changed, 31 insertions(+), 23 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 736dd3a1d8652..1bba43cc45fd2 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -117,7 +117,14 @@ pub(crate) fn clean_doc_module<'tcx>(doc: &DocModule<'tcx>, cx: &mut DocContext< hir::ItemKind::Use(path, kind) => { let hir::UsePath { segments, span, .. } = *path; let path = hir::Path { segments, res: *res, span }; - clean_use_statement_inner(import, Some(name), &path, kind, cx, &mut Default::default()) + clean_use_statement_inner( + import, + Some(name), + &path, + kind, + cx, + &mut Default::default(), + ) } _ => unreachable!(), } @@ -1071,10 +1078,10 @@ fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[hir::Attrib .. } = param { - func.decl - .inputs - .values - .insert(a.get() as _, Argument { name, type_: *ty, is_const: true }); + func.decl.inputs.values.insert( + a.get() as _, + Argument { name: Some(name), type_: *ty, is_const: true }, + ); } else { panic!("unexpected non const in position {pos}"); } @@ -1131,9 +1138,9 @@ fn clean_args_from_types_and_names<'tcx>( // If at least one argument has a name, use `_` as the name of unnamed // arguments. Otherwise omit argument names. let default_name = if idents.iter().any(|ident| nonempty_name(ident).is_some()) { - kw::Underscore + Some(kw::Underscore) } else { - kw::Empty + None }; Arguments { @@ -1142,7 +1149,7 @@ fn clean_args_from_types_and_names<'tcx>( .enumerate() .map(|(i, ty)| Argument { type_: clean_ty(ty, cx), - name: idents.get(i).and_then(nonempty_name).unwrap_or(default_name), + name: idents.get(i).and_then(nonempty_name).or(default_name), is_const: false, }) .collect(), @@ -1161,7 +1168,7 @@ fn clean_args_from_types_and_body_id<'tcx>( .iter() .zip(body.params) .map(|(ty, param)| Argument { - name: name_from_pat(param.pat), + name: Some(name_from_pat(param.pat)), type_: clean_ty(ty, cx), is_const: false, }) @@ -1217,11 +1224,11 @@ fn clean_poly_fn_sig<'tcx>( .iter() .map(|t| Argument { type_: clean_middle_ty(t.map_bound(|t| *t), cx, None, None), - name: if let Some(Some(ident)) = names.next() { + name: Some(if let Some(Some(ident)) = names.next() { ident.name } else { kw::Underscore - }, + }), is_const: false, }) .collect(), @@ -2791,11 +2798,7 @@ fn clean_maybe_renamed_item<'tcx>( use hir::ItemKind; let def_id = item.owner_id.to_def_id(); - let mut name = if renamed.is_some() { - renamed - } else { - cx.tcx.hir_opt_name(item.hir_id()) - }; + let mut name = if renamed.is_some() { renamed } else { cx.tcx.hir_opt_name(item.hir_id()) }; cx.with_param_env(def_id, |cx| { let kind = match item.kind { diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 06e75fe1764e0..1d398a6458fd2 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -1426,7 +1426,7 @@ pub(crate) struct Arguments { #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub(crate) struct Argument { pub(crate) type_: Type, - pub(crate) name: Symbol, + pub(crate) name: Option, /// This field is used to represent "const" arguments from the `rustc_legacy_const_generics` /// feature. More information in . pub(crate) is_const: bool, @@ -1434,7 +1434,7 @@ pub(crate) struct Argument { impl Argument { pub(crate) fn to_receiver(&self) -> Option<&Type> { - if self.name == kw::SelfLower { Some(&self.type_) } else { None } + if self.name == Some(kw::SelfLower) { Some(&self.type_) } else { None } } } diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 41e9a5a665169..4d55df71a910f 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -1238,8 +1238,8 @@ impl clean::Arguments { .iter() .map(|input| { fmt::from_fn(|f| { - if !input.name.is_empty() { - write!(f, "{}: ", input.name)?; + if let Some(name) = input.name { + write!(f, "{}: ", name)?; } input.type_.print(cx).fmt(f) }) @@ -1361,7 +1361,9 @@ impl clean::FnDecl { if input.is_const { write!(f, "const ")?; } - write!(f, "{}: ", input.name)?; + if let Some(name) = input.name { + write!(f, "{}: ", name)?; + } input.type_.print(cx).fmt(f)?; } match (line_wrapping_indent, last_input_index) { diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 9d8eb70fbe071..5d85a4676b7e9 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -11,7 +11,7 @@ use rustc_hir::def::CtorKind; use rustc_hir::def_id::DefId; use rustc_metadata::rendered_const; use rustc_middle::{bug, ty}; -use rustc_span::{Pos, Symbol}; +use rustc_span::{Pos, Symbol, kw}; use rustdoc_json_types::*; use crate::clean::{self, ItemId}; @@ -611,7 +611,10 @@ impl FromClean for FunctionSignature { inputs: inputs .values .into_iter() - .map(|arg| (arg.name.to_string(), arg.type_.into_json(renderer))) + // `_` is the most sensible name for missing param names. + .map(|arg| { + (arg.name.unwrap_or(kw::Underscore).to_string(), arg.type_.into_json(renderer)) + }) .collect(), output: if output.is_unit() { None } else { Some(output.into_json(renderer)) }, is_c_variadic: c_variadic, From 5fb0f570f5d4b63db0bde517432b76099a2d683d Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 15 Apr 2025 13:26:19 +1000 Subject: [PATCH 091/266] Avoid another `kw::Empty` use. `sym::dummy` also appears to work. --- src/librustdoc/clean/utils.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index afcca81a485ff..8ee08edec1996 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -234,7 +234,7 @@ pub(super) fn clean_middle_path<'tcx>( args: ty::Binder<'tcx, GenericArgsRef<'tcx>>, ) -> Path { let def_kind = cx.tcx.def_kind(did); - let name = cx.tcx.opt_item_name(did).unwrap_or(kw::Empty); + let name = cx.tcx.opt_item_name(did).unwrap_or(sym::dummy); Path { res: Res::Def(def_kind, did), segments: thin_vec![PathSegment { From 40978580ec3c4d6d32245e578979a745f310e9c3 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 15 Apr 2025 13:31:17 +1000 Subject: [PATCH 092/266] Avoid using `kw::Empty` when comparing names. --- src/librustdoc/html/render/print_item.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index 96847f13f655c..45cb0adecf3bf 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -11,7 +11,7 @@ use rustc_hir::def_id::DefId; use rustc_index::IndexVec; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::hygiene::MacroKind; -use rustc_span::symbol::{Symbol, kw, sym}; +use rustc_span::symbol::{Symbol, sym}; use tracing::{debug, info}; use super::type_layout::document_type_layout; @@ -347,9 +347,12 @@ fn item_module(cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) -> i // but we actually want stable items to come first return is_stable2.cmp(&is_stable1); } - let lhs = i1.name.unwrap_or(kw::Empty); - let rhs = i2.name.unwrap_or(kw::Empty); - compare_names(lhs.as_str(), rhs.as_str()) + match (i1.name, i2.name) { + (Some(name1), Some(name2)) => compare_names(name1.as_str(), name2.as_str()), + (Some(_), None) => Ordering::Greater, + (None, Some(_)) => Ordering::Less, + (None, None) => Ordering::Equal, + } } let tcx = cx.tcx(); From 65942d19cdb722db4544c4fcdcc0f054ff048701 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 15 Apr 2025 15:01:48 +1000 Subject: [PATCH 093/266] Avoid using `kw::Empty` for param names in rustdoc. --- src/librustdoc/html/render/mod.rs | 2 +- src/librustdoc/html/render/search_index.rs | 17 ++++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 21c823f49d15f..adf15018ad2dc 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -208,7 +208,7 @@ pub(crate) struct IndexItemFunctionType { inputs: Vec, output: Vec, where_clause: Vec>, - param_names: Vec, + param_names: Vec>, } impl IndexItemFunctionType { diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index b39701fae1d6a..1360ab94cb1ce 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -709,8 +709,11 @@ pub(crate) fn build_index( let mut result = Vec::new(); for (index, item) in self.items.iter().enumerate() { if let Some(ty) = &item.search_type - && let my = - ty.param_names.iter().map(|sym| sym.as_str()).collect::>() + && let my = ty + .param_names + .iter() + .filter_map(|sym| sym.map(|sym| sym.to_string())) + .collect::>() && my != prev { result.push((index, my.join(","))); @@ -1372,7 +1375,7 @@ fn simplify_fn_constraint<'a>( /// Used to allow type-based search on constants and statics. fn make_nullary_fn( clean_type: &clean::Type, -) -> (Vec, Vec, Vec, Vec>) { +) -> (Vec, Vec, Vec>, Vec>) { let mut rgen: FxIndexMap)> = Default::default(); let output = get_index_type(clean_type, vec![], &mut rgen); (vec![], vec![output], vec![], vec![]) @@ -1387,7 +1390,7 @@ fn get_fn_inputs_and_outputs( tcx: TyCtxt<'_>, impl_or_trait_generics: Option<&(clean::Type, clean::Generics)>, cache: &Cache, -) -> (Vec, Vec, Vec, Vec>) { +) -> (Vec, Vec, Vec>, Vec>) { let decl = &func.decl; let mut rgen: FxIndexMap)> = Default::default(); @@ -1441,10 +1444,10 @@ fn get_fn_inputs_and_outputs( simplified_params .iter() .map(|(name, (_idx, _traits))| match name { - SimplifiedParam::Symbol(name) => *name, - SimplifiedParam::Anonymous(_) => kw::Empty, + SimplifiedParam::Symbol(name) => Some(*name), + SimplifiedParam::Anonymous(_) => None, SimplifiedParam::AssociatedType(def_id, name) => { - Symbol::intern(&format!("{}::{}", tcx.item_name(*def_id), name)) + Some(Symbol::intern(&format!("{}::{}", tcx.item_name(*def_id), name))) } }) .collect(), From d1e82ba37c3dd1998808665971bbee4e1ae028b8 Mon Sep 17 00:00:00 2001 From: Thalia Archibald Date: Mon, 14 Apr 2025 21:43:53 -0700 Subject: [PATCH 094/266] Setup editor file associations for non-rs extensions .gitattributes lists *.fixed, *.pp, and *.mir as file extensions which should be treated as Rust source code. Do the same for VS Code and Zed. This only does syntax highlighting, which is appropriate, as MIR isn't really Rust code. At the same time, consistently order `rust-analyzer.linkedProjects` between editors. For some reason, Eglot didn't include library/Cargo.toml. --- src/bootstrap/src/core/build_steps/setup.rs | 3 +++ src/etc/rust_analyzer_eglot.el | 7 ++++--- src/etc/rust_analyzer_settings.json | 11 ++++++++--- src/etc/rust_analyzer_zed.json | 13 ++++++++----- 4 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/setup.rs b/src/bootstrap/src/core/build_steps/setup.rs index 80d92135dd378..83083e12ef1fc 100644 --- a/src/bootstrap/src/core/build_steps/setup.rs +++ b/src/bootstrap/src/core/build_steps/setup.rs @@ -584,6 +584,7 @@ Select which editor you would like to set up [default: None]: "; "51068d4747a13732440d1a8b8f432603badb1864fa431d83d0fd4f8fa57039e0", "d29af4d949bbe2371eac928a3c31cf9496b1701aa1c45f11cd6c759865ad5c45", "b5dd299b93dca3ceeb9b335f929293cb3d4bf4977866fbe7ceeac2a8a9f99088", + "631c837b0e98ae35fd48b0e5f743b1ca60adadf2d0a2b23566ba25df372cf1a9", ], EditorKind::Helix => &[ "2d3069b8cf1b977e5d4023965eb6199597755e6c96c185ed5f2854f98b83d233", @@ -602,10 +603,12 @@ Select which editor you would like to set up [default: None]: "; "4eecb58a2168b252077369da446c30ed0e658301efe69691979d1ef0443928f4", "c394386e6133bbf29ffd32c8af0bb3d4aac354cba9ee051f29612aa9350f8f8d", "e53e9129ca5ee5dcbd6ec8b68c2d87376474eb154992deba3c6d9ab1703e0717", + "f954316090936c7e590c253ca9d524008375882fa13c5b41d7e2547a896ff893", ], EditorKind::Zed => &[ "bbce727c269d1bd0c98afef4d612eb4ce27aea3c3a8968c5f10b31affbc40b6c", "a5380cf5dd9328731aecc5dfb240d16dac46ed272126b9728006151ef42f5909", + "2e96bf0d443852b12f016c8fc9840ab3d0a2b4fe0b0fb3a157e8d74d5e7e0e26", ], } } diff --git a/src/etc/rust_analyzer_eglot.el b/src/etc/rust_analyzer_eglot.el index 6b40371d9af11..90bd38aa89477 100644 --- a/src/etc/rust_analyzer_eglot.el +++ b/src/etc/rust_analyzer_eglot.el @@ -8,10 +8,11 @@ "check" "--json-output"]) :linkedProjects ["Cargo.toml" - "src/bootstrap/Cargo.toml" - "src/tools/rust-analyzer/Cargo.toml" "compiler/rustc_codegen_cranelift/Cargo.toml" - "compiler/rustc_codegen_gcc/Cargo.toml"] + "compiler/rustc_codegen_gcc/Cargo.toml" + "library/Cargo.toml" + "src/bootstrap/Cargo.toml" + "src/tools/rust-analyzer/Cargo.toml"] :rustfmt ( :overrideCommand ["build/host/rustfmt/bin/rustfmt" "--edition=2021"]) :procMacro ( :server "build/host/stage0/libexec/rust-analyzer-proc-macro-srv" diff --git a/src/etc/rust_analyzer_settings.json b/src/etc/rust_analyzer_settings.json index da7d326a512cc..5ce886a9b6594 100644 --- a/src/etc/rust_analyzer_settings.json +++ b/src/etc/rust_analyzer_settings.json @@ -9,11 +9,11 @@ ], "rust-analyzer.linkedProjects": [ "Cargo.toml", + "compiler/rustc_codegen_cranelift/Cargo.toml", + "compiler/rustc_codegen_gcc/Cargo.toml", "library/Cargo.toml", "src/bootstrap/Cargo.toml", - "src/tools/rust-analyzer/Cargo.toml", - "compiler/rustc_codegen_cranelift/Cargo.toml", - "compiler/rustc_codegen_gcc/Cargo.toml" + "src/tools/rust-analyzer/Cargo.toml" ], "rust-analyzer.rustfmt.overrideCommand": [ "${workspaceFolder}/build/host/rustfmt/bin/rustfmt", @@ -36,5 +36,10 @@ }, "rust-analyzer.server.extraEnv": { "RUSTUP_TOOLCHAIN": "nightly" + }, + "files.associations": { + "*.fixed": "rust", + "*.pp": "rust", + "*.mir": "rust" } } diff --git a/src/etc/rust_analyzer_zed.json b/src/etc/rust_analyzer_zed.json index abc6ddbc213c4..3461ff887d9b4 100644 --- a/src/etc/rust_analyzer_zed.json +++ b/src/etc/rust_analyzer_zed.json @@ -21,15 +21,15 @@ }, "linkedProjects": [ "Cargo.toml", + "compiler/rustc_codegen_cranelift/Cargo.toml", + "compiler/rustc_codegen_gcc/Cargo.toml", "library/Cargo.toml", "src/bootstrap/Cargo.toml", - "src/tools/rust-analyzer/Cargo.toml", - "compiler/rustc_codegen_cranelift/Cargo.toml", - "compiler/rustc_codegen_gcc/Cargo.toml" + "src/tools/rust-analyzer/Cargo.toml" ], "procMacro": { - "enable": true, - "server": "${workspaceFolder}/build/host/stage0/libexec/rust-analyzer-proc-macro-srv" + "enable": true, + "server": "${workspaceFolder}/build/host/stage0/libexec/rust-analyzer-proc-macro-srv" }, "rustc": { "source": "./Cargo.toml" @@ -47,5 +47,8 @@ } } } + }, + "file_types": { + "Rust": ["fixed", "pp", "mir"] } } From 4ac3877521084501c44d3bea1251398448cb7ecd Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Tue, 15 Apr 2025 09:28:04 +0200 Subject: [PATCH 095/266] unstable book; document `macro_metavar_expr_concat` --- .../macro-metavar-expr-concat.md | 133 ++++++++++++++++++ .../language-features/macro-metavar-expr.md | 10 ++ .../src/library-features/concat-idents.md | 2 + 3 files changed, 145 insertions(+) create mode 100644 src/doc/unstable-book/src/language-features/macro-metavar-expr-concat.md create mode 100644 src/doc/unstable-book/src/language-features/macro-metavar-expr.md diff --git a/src/doc/unstable-book/src/language-features/macro-metavar-expr-concat.md b/src/doc/unstable-book/src/language-features/macro-metavar-expr-concat.md new file mode 100644 index 0000000000000..b6dbdb1440774 --- /dev/null +++ b/src/doc/unstable-book/src/language-features/macro-metavar-expr-concat.md @@ -0,0 +1,133 @@ +# `macro_metavar_expr_concat` + +The tracking issue for this feature is: [#124225] + +------------------------ + +In stable Rust, there is no way to create new identifiers by joining identifiers to literals or other identifiers without using procedural macros such as [`paste`]. + `#![feature(macro_metavar_expr_concat)]` introduces a way to do this, using the concat metavariable expression. + +> This feature uses the syntax from [`macro_metavar_expr`] but is otherwise +> independent. It replaces the old unstable feature [`concat_idents`]. + +> This is an experimental feature; it and its syntax will require a RFC before stabilization. + + +### Overview + +`#![feature(macro_metavar_expr_concat)]` provides the `concat` metavariable expression for creating new identifiers: + +```rust +#![feature(macro_metavar_expr_concat)] + +macro_rules! create_some_structs { + ($name:ident) => { + pub struct ${ concat(First, $name) }; + pub struct ${ concat(Second, $name) }; + pub struct ${ concat(Third, $name) }; + } +} + +create_some_structs!(Thing); +``` + +This macro invocation expands to: + +```rust +pub struct FirstThing; +pub struct SecondThing; +pub struct ThirdThing; +``` + +### Syntax + +This feature builds upon the metavariable expression syntax `${ .. }` as specified in [RFC 3086] ([`macro_metavar_expr`]). + `concat` is available like `${ concat(items) }`, where `items` is a comma separated sequence of idents and/or literals. + +### Examples + +#### Create a function or method with a concatenated name + +```rust +#![feature(macro_metavar_expr_concat)] + +macro_rules! make_getter { + ($name:ident, $field: ident, $ret:ty) => { + impl $name { + pub fn ${ concat(get_, $field) }(&self) -> &$ret { + &self.$field + } + } + } +} + +pub struct Thing { + description: String, +} + +make_getter!(Thing, description, String); +``` + +This expands to: + +```rust +pub struct Thing { + description: String, +} + +impl Thing { + pub fn get_description(&self) -> &String { + &self.description + } +} +``` + +#### Create names for macro generated tests + +```rust +#![feature(macro_metavar_expr_concat)] + +macro_rules! test_math { + ($integer:ident) => { + #[test] + fn ${ concat(test_, $integer, _, addition) } () { + let a: $integer = 73; + let b: $integer = 42; + assert_eq!(a + b, 115) + } + + #[test] + fn ${ concat(test_, $integer, _, subtraction) } () { + let a: $integer = 73; + let b: $integer = 42; + assert_eq!(a - b, 31) + } + } +} + +test_math!(i32); +test_math!(u64); +test_math!(u128); +``` + +Running this returns the following output: + +```text +running 6 tests +test test_i32_subtraction ... ok +test test_i32_addition ... ok +test test_u128_addition ... ok +test test_u128_subtraction ... ok +test test_u64_addition ... ok +test test_u64_subtraction ... ok + +test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s +``` + +[`paste`]: https://crates.io/crates/paste +[RFC 3086]: https://rust-lang.github.io/rfcs/3086-macro-metavar-expr.html +[`concat_idents!`]: https://doc.rust-lang.org/nightly/std/macro.concat_idents.html +[`macro_metavar_expr`]: ../language-features/macro-metavar-expr.md +[`concat_idents`]: ../library-features/concat-idents.md +[#124225]: https://github.com/rust-lang/rust/issues/124225 +[declarative macros]: https://doc.rust-lang.org/stable/reference/macros-by-example.html diff --git a/src/doc/unstable-book/src/language-features/macro-metavar-expr.md b/src/doc/unstable-book/src/language-features/macro-metavar-expr.md new file mode 100644 index 0000000000000..7ce64c1a3549a --- /dev/null +++ b/src/doc/unstable-book/src/language-features/macro-metavar-expr.md @@ -0,0 +1,10 @@ +# `macro_metavar_expr` + +The tracking issue for this feature is: [#83527] + +------------------------ + +> This feature is not to be confused with [`macro_metavar_expr_concat`]. + +[`macro_metavar_expr_concat`]: ./macro-metavar-expr-concat.md +[#83527]: https://github.com/rust-lang/rust/issues/83527 diff --git a/src/doc/unstable-book/src/library-features/concat-idents.md b/src/doc/unstable-book/src/library-features/concat-idents.md index 73f6cfa21787e..4366172fb9965 100644 --- a/src/doc/unstable-book/src/library-features/concat-idents.md +++ b/src/doc/unstable-book/src/library-features/concat-idents.md @@ -6,6 +6,8 @@ The tracking issue for this feature is: [#29599] ------------------------ +> This feature is expected to be superseded by [`macro_metavar_expr_concat`](../language-features/macro-metavar-expr-concat.md). + The `concat_idents` feature adds a macro for concatenating multiple identifiers into one identifier. From fc8df06f4feb6cc051e15e6596821d276b0797bb Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Mon, 14 Apr 2025 18:24:30 +0200 Subject: [PATCH 096/266] update submodules if the directory doesn't exist --- src/bootstrap/src/core/config/config.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 25ec64f90b53d..2266e61bf6088 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -2888,6 +2888,13 @@ impl Config { let absolute_path = self.src.join(relative_path); + // NOTE: This check is required because `jj git clone` doesn't create directories for + // submodules, they are completely ignored. The code below assumes this directory exists, + // so create it here. + if !absolute_path.exists() { + t!(fs::create_dir_all(&absolute_path)); + } + // NOTE: The check for the empty directory is here because when running x.py the first time, // the submodule won't be checked out. Check it out now so we can build it. if !GitInfo::new(false, &absolute_path).is_managed_git_subrepository() From 1397dabd1ec2e58f0cea27fd281dac7104083cca Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Mon, 14 Apr 2025 19:04:34 +0200 Subject: [PATCH 097/266] fix typo --- 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 24fc2ddb74104..093dc7fa56caa 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -2383,7 +2383,7 @@ impl<'test> TestCx<'test> { if json { // escaped newlines in json strings should be readable - // in the stderr files. There's no point int being correct, + // in the stderr files. There's no point in being correct, // since only humans process the stderr files. // Thus we just turn escaped newlines back into newlines. normalized = normalized.replace("\\n", "\n"); From 6c441cc7a53e3c9ca0dd1957b8055ccdd851b488 Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Mon, 14 Apr 2025 19:04:34 +0200 Subject: [PATCH 098/266] canonicalize test build dir before normalizing it Fix fixes failures of the following tests when build directory is a symlink: - `tests/ui/error-codes/E{0464,0523}.rs` - `tests/ui/crate-loading/crateresolve{1,2}.rs` (those are the same tests) --- src/tools/compiletest/src/runtest.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 093dc7fa56caa..fc83ea420430b 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -2375,9 +2375,13 @@ impl<'test> TestCx<'test> { let rust_src_dir = rust_src_dir.read_link_utf8().unwrap_or(rust_src_dir.to_path_buf()); normalize_path(&rust_src_dir.join("library"), "$SRC_DIR_REAL"); + // Canonicalize test build directory path. + // Without this some tests fail if build directory is a symlink. + let output_base_dir = self.output_base_dir().canonicalize_utf8().unwrap(); + // eg. // /home/user/rust/build/x86_64-unknown-linux-gnu/test/ui//$name.$revision.$mode/ - normalize_path(&self.output_base_dir(), "$TEST_BUILD_DIR"); + normalize_path(&output_base_dir, "$TEST_BUILD_DIR"); // eg. /home/user/rust/build normalize_path(&self.config.build_root, "$BUILD_DIR"); From 8887af72a0b1f37a34b02d488ca3278576e2d73d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Mon, 14 Apr 2025 20:48:51 +0200 Subject: [PATCH 099/266] Improve parse errors for lifetimes in type position --- compiler/rustc_parse/messages.ftl | 4 +- compiler/rustc_parse/src/errors.rs | 2 + compiler/rustc_parse/src/parser/ty.rs | 63 +++++++++++++++++-- .../gat-trait-path-parenthesised-args.rs | 2 +- .../gat-trait-path-parenthesised-args.stderr | 7 ++- .../trait-object-macro-matcher.e2015.stderr | 32 ++++++++++ .../trait-object-macro-matcher.e2021.stderr | 16 +++++ .../macro/trait-object-macro-matcher.rs | 12 +++- .../macro/trait-object-macro-matcher.stderr | 23 ------- .../recover/recover-ampersand-less-ref-ty.rs | 13 ++++ .../recover-ampersand-less-ref-ty.stderr | 24 +++++++ ...trait-object-lifetime-parens.e2015.stderr} | 13 ++-- .../trait-object-lifetime-parens.e2021.stderr | 51 +++++++++++++++ .../ui/parser/trait-object-lifetime-parens.rs | 14 ++++- 14 files changed, 234 insertions(+), 42 deletions(-) create mode 100644 tests/ui/parser/macro/trait-object-macro-matcher.e2015.stderr create mode 100644 tests/ui/parser/macro/trait-object-macro-matcher.e2021.stderr delete mode 100644 tests/ui/parser/macro/trait-object-macro-matcher.stderr create mode 100644 tests/ui/parser/recover/recover-ampersand-less-ref-ty.rs create mode 100644 tests/ui/parser/recover/recover-ampersand-less-ref-ty.stderr rename tests/ui/parser/{trait-object-lifetime-parens.stderr => trait-object-lifetime-parens.e2015.stderr} (60%) create mode 100644 tests/ui/parser/trait-object-lifetime-parens.e2021.stderr diff --git a/compiler/rustc_parse/messages.ftl b/compiler/rustc_parse/messages.ftl index 93fa89b68b97a..e2b5e1cdd0ad6 100644 --- a/compiler/rustc_parse/messages.ftl +++ b/compiler/rustc_parse/messages.ftl @@ -642,7 +642,9 @@ parse_mut_on_nested_ident_pattern = `mut` must be attached to each individual bi .suggestion = add `mut` to each binding parse_mut_on_non_ident_pattern = `mut` must be followed by a named binding .suggestion = remove the `mut` prefix -parse_need_plus_after_trait_object_lifetime = lifetime in trait object type must be followed by `+` + +parse_need_plus_after_trait_object_lifetime = lifetimes must be followed by `+` to form a trait object type + .suggestion = consider adding a trait bound after the potential lifetime bound parse_nested_adt = `{$kw_str}` definition cannot be nested inside `{$keyword}` .suggestion = consider creating a new `{$kw_str}` definition instead of nesting diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index dfdef018bc374..b28939e062af9 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -2806,6 +2806,8 @@ pub(crate) struct ReturnTypesUseThinArrow { pub(crate) struct NeedPlusAfterTraitObjectLifetime { #[primary_span] pub span: Span, + #[suggestion(code = " + /* Trait */", applicability = "has-placeholders")] + pub suggestion: Span, } #[derive(Diagnostic)] diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index 93705da22c459..f468d5433d936 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -7,7 +7,7 @@ use rustc_ast::{ Pinnedness, PolyTraitRef, PreciseCapturingArg, TraitBoundModifiers, TraitObjectSyntax, Ty, TyKind, UnsafeBinderTy, }; -use rustc_errors::{Applicability, PResult}; +use rustc_errors::{Applicability, Diag, PResult}; use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym}; use thin_vec::{ThinVec, thin_vec}; @@ -411,6 +411,9 @@ impl<'a> Parser<'a> { TyKind::Path(None, path) if maybe_bounds => { self.parse_remaining_bounds_path(ThinVec::new(), path, lo, true) } + // For `('a) + …`, we know that `'a` in type position already lead to an error being + // emitted. To reduce output, let's indirectly suppress E0178 (bad `+` in type) and + // other irrelevant consequential errors. TyKind::TraitObject(bounds, TraitObjectSyntax::None) if maybe_bounds && bounds.len() == 1 && !trailing_plus => { @@ -425,12 +428,60 @@ impl<'a> Parser<'a> { } fn parse_bare_trait_object(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> { - let lt_no_plus = self.check_lifetime() && !self.look_ahead(1, |t| t.is_like_plus()); - let bounds = self.parse_generic_bounds_common(allow_plus)?; - if lt_no_plus { - self.dcx().emit_err(NeedPlusAfterTraitObjectLifetime { span: lo }); + // A lifetime only begins a bare trait object type if it is followed by `+`! + if self.token.is_lifetime() && !self.look_ahead(1, |t| t.is_like_plus()) { + // In Rust 2021 and beyond, we assume that the user didn't intend to write a bare trait + // object type with a leading lifetime bound since that seems very unlikely given the + // fact that `dyn`-less trait objects are *semantically* invalid. + if self.psess.edition.at_least_rust_2021() { + let lt = self.expect_lifetime(); + let mut err = self.dcx().struct_span_err(lo, "expected type, found lifetime"); + err.span_label(lo, "expected type"); + return Ok(match self.maybe_recover_ref_ty_no_leading_ampersand(lt, lo, err) { + Ok(ref_ty) => ref_ty, + Err(err) => TyKind::Err(err.emit()), + }); + } + + self.dcx().emit_err(NeedPlusAfterTraitObjectLifetime { + span: lo, + suggestion: lo.shrink_to_hi(), + }); + } + Ok(TyKind::TraitObject( + self.parse_generic_bounds_common(allow_plus)?, + TraitObjectSyntax::None, + )) + } + + fn maybe_recover_ref_ty_no_leading_ampersand<'cx>( + &mut self, + lt: Lifetime, + lo: Span, + mut err: Diag<'cx>, + ) -> Result> { + if !self.may_recover() { + return Err(err); + } + let snapshot = self.create_snapshot_for_diagnostic(); + let mutbl = self.parse_mutability(); + match self.parse_ty_no_plus() { + Ok(ty) => { + err.span_suggestion_verbose( + lo.shrink_to_lo(), + "you might have meant to write a reference type here", + "&", + Applicability::MaybeIncorrect, + ); + err.emit(); + Ok(TyKind::Ref(Some(lt), MutTy { ty, mutbl })) + } + Err(diag) => { + diag.cancel(); + self.restore_snapshot(snapshot); + Err(err) + } } - Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None)) } fn parse_remaining_bounds_path( diff --git a/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.rs b/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.rs index 85661c1b84480..294fb6743fbcd 100644 --- a/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.rs +++ b/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.rs @@ -3,7 +3,7 @@ trait X { } fn foo<'a>(arg: Box>) {} - //~^ ERROR: lifetime in trait object type must be followed by `+` + //~^ ERROR: lifetimes must be followed by `+` to form a trait object type //~| ERROR: parenthesized generic arguments cannot be used //~| ERROR associated type takes 0 generic arguments but 1 generic argument //~| ERROR associated type takes 1 lifetime argument but 0 lifetime arguments diff --git a/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr b/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr index 99300ea1cb7f1..e18d8198c9455 100644 --- a/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr +++ b/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr @@ -1,8 +1,13 @@ -error: lifetime in trait object type must be followed by `+` +error: lifetimes must be followed by `+` to form a trait object type --> $DIR/gat-trait-path-parenthesised-args.rs:5:29 | LL | fn foo<'a>(arg: Box>) {} | ^^ + | +help: consider adding a trait bound after the potential lifetime bound + | +LL | fn foo<'a>(arg: Box>) {} + | +++++++++++++ error: parenthesized generic arguments cannot be used in associated type constraints --> $DIR/gat-trait-path-parenthesised-args.rs:5:27 diff --git a/tests/ui/parser/macro/trait-object-macro-matcher.e2015.stderr b/tests/ui/parser/macro/trait-object-macro-matcher.e2015.stderr new file mode 100644 index 0000000000000..f2db351de4a7f --- /dev/null +++ b/tests/ui/parser/macro/trait-object-macro-matcher.e2015.stderr @@ -0,0 +1,32 @@ +error: lifetimes must be followed by `+` to form a trait object type + --> $DIR/trait-object-macro-matcher.rs:17:8 + | +LL | m!('static); + | ^^^^^^^ + | +help: consider adding a trait bound after the potential lifetime bound + | +LL | m!('static + /* Trait */); + | +++++++++++++ + +error: lifetimes must be followed by `+` to form a trait object type + --> $DIR/trait-object-macro-matcher.rs:17:8 + | +LL | m!('static); + | ^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +help: consider adding a trait bound after the potential lifetime bound + | +LL | m!('static + /* Trait */); + | +++++++++++++ + +error[E0224]: at least one trait is required for an object type + --> $DIR/trait-object-macro-matcher.rs:17:8 + | +LL | m!('static); + | ^^^^^^^ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0224`. diff --git a/tests/ui/parser/macro/trait-object-macro-matcher.e2021.stderr b/tests/ui/parser/macro/trait-object-macro-matcher.e2021.stderr new file mode 100644 index 0000000000000..7d9e8d795d18a --- /dev/null +++ b/tests/ui/parser/macro/trait-object-macro-matcher.e2021.stderr @@ -0,0 +1,16 @@ +error: expected type, found lifetime + --> $DIR/trait-object-macro-matcher.rs:17:8 + | +LL | m!('static); + | ^^^^^^^ expected type + +error: expected type, found lifetime + --> $DIR/trait-object-macro-matcher.rs:17:8 + | +LL | m!('static); + | ^^^^^^^ expected type + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: aborting due to 2 previous errors + diff --git a/tests/ui/parser/macro/trait-object-macro-matcher.rs b/tests/ui/parser/macro/trait-object-macro-matcher.rs index d4ec199070e7c..ba61752fe4024 100644 --- a/tests/ui/parser/macro/trait-object-macro-matcher.rs +++ b/tests/ui/parser/macro/trait-object-macro-matcher.rs @@ -1,6 +1,10 @@ // A single lifetime is not parsed as a type. // `ty` matcher in particular doesn't accept a single lifetime +//@ revisions: e2015 e2021 +//@[e2015] edition: 2015 +//@[e2021] edition: 2021 + macro_rules! m { ($t: ty) => { let _: $t; @@ -8,8 +12,10 @@ macro_rules! m { } fn main() { + //[e2021]~vv ERROR expected type, found lifetime + //[e2021]~v ERROR expected type, found lifetime m!('static); - //~^ ERROR lifetime in trait object type must be followed by `+` - //~| ERROR lifetime in trait object type must be followed by `+` - //~| ERROR at least one trait is required for an object type + //[e2015]~^ ERROR lifetimes must be followed by `+` to form a trait object type + //[e2015]~| ERROR lifetimes must be followed by `+` to form a trait object type + //[e2015]~| ERROR at least one trait is required for an object type } diff --git a/tests/ui/parser/macro/trait-object-macro-matcher.stderr b/tests/ui/parser/macro/trait-object-macro-matcher.stderr deleted file mode 100644 index 81dca6f71c436..0000000000000 --- a/tests/ui/parser/macro/trait-object-macro-matcher.stderr +++ /dev/null @@ -1,23 +0,0 @@ -error: lifetime in trait object type must be followed by `+` - --> $DIR/trait-object-macro-matcher.rs:11:8 - | -LL | m!('static); - | ^^^^^^^ - -error: lifetime in trait object type must be followed by `+` - --> $DIR/trait-object-macro-matcher.rs:11:8 - | -LL | m!('static); - | ^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0224]: at least one trait is required for an object type - --> $DIR/trait-object-macro-matcher.rs:11:8 - | -LL | m!('static); - | ^^^^^^^ - -error: aborting due to 3 previous errors - -For more information about this error, try `rustc --explain E0224`. diff --git a/tests/ui/parser/recover/recover-ampersand-less-ref-ty.rs b/tests/ui/parser/recover/recover-ampersand-less-ref-ty.rs new file mode 100644 index 0000000000000..8f1a42473b5a6 --- /dev/null +++ b/tests/ui/parser/recover/recover-ampersand-less-ref-ty.rs @@ -0,0 +1,13 @@ +//@ edition: 2021 + +struct Entity<'a> { + name: 'a str, //~ ERROR expected type, found lifetime + //~^ HELP you might have meant to write a reference type here +} + +struct Buffer<'buf> { + bytes: 'buf mut [u8], //~ ERROR expected type, found lifetime + //~^ HELP you might have meant to write a reference type here +} + +fn main() {} diff --git a/tests/ui/parser/recover/recover-ampersand-less-ref-ty.stderr b/tests/ui/parser/recover/recover-ampersand-less-ref-ty.stderr new file mode 100644 index 0000000000000..033348b2c4058 --- /dev/null +++ b/tests/ui/parser/recover/recover-ampersand-less-ref-ty.stderr @@ -0,0 +1,24 @@ +error: expected type, found lifetime + --> $DIR/recover-ampersand-less-ref-ty.rs:4:11 + | +LL | name: 'a str, + | ^^ expected type + | +help: you might have meant to write a reference type here + | +LL | name: &'a str, + | + + +error: expected type, found lifetime + --> $DIR/recover-ampersand-less-ref-ty.rs:9:12 + | +LL | bytes: 'buf mut [u8], + | ^^^^ expected type + | +help: you might have meant to write a reference type here + | +LL | bytes: &'buf mut [u8], + | + + +error: aborting due to 2 previous errors + diff --git a/tests/ui/parser/trait-object-lifetime-parens.stderr b/tests/ui/parser/trait-object-lifetime-parens.e2015.stderr similarity index 60% rename from tests/ui/parser/trait-object-lifetime-parens.stderr rename to tests/ui/parser/trait-object-lifetime-parens.e2015.stderr index 280c0e40c6408..cf0b3d77f5b5a 100644 --- a/tests/ui/parser/trait-object-lifetime-parens.stderr +++ b/tests/ui/parser/trait-object-lifetime-parens.e2015.stderr @@ -1,5 +1,5 @@ error: parenthesized lifetime bounds are not supported - --> $DIR/trait-object-lifetime-parens.rs:5:21 + --> $DIR/trait-object-lifetime-parens.rs:9:21 | LL | fn f<'a, T: Trait + ('a)>() {} | ^^^^ @@ -11,7 +11,7 @@ LL + fn f<'a, T: Trait + 'a>() {} | error: parenthesized lifetime bounds are not supported - --> $DIR/trait-object-lifetime-parens.rs:8:24 + --> $DIR/trait-object-lifetime-parens.rs:12:24 | LL | let _: Box; | ^^^^ @@ -22,11 +22,16 @@ LL - let _: Box; LL + let _: Box; | -error: lifetime in trait object type must be followed by `+` - --> $DIR/trait-object-lifetime-parens.rs:10:17 +error: lifetimes must be followed by `+` to form a trait object type + --> $DIR/trait-object-lifetime-parens.rs:16:17 | LL | let _: Box<('a) + Trait>; | ^^ + | +help: consider adding a trait bound after the potential lifetime bound + | +LL | let _: Box<('a + /* Trait */) + Trait>; + | +++++++++++++ error: aborting due to 3 previous errors diff --git a/tests/ui/parser/trait-object-lifetime-parens.e2021.stderr b/tests/ui/parser/trait-object-lifetime-parens.e2021.stderr new file mode 100644 index 0000000000000..3518321ea201d --- /dev/null +++ b/tests/ui/parser/trait-object-lifetime-parens.e2021.stderr @@ -0,0 +1,51 @@ +error: parenthesized lifetime bounds are not supported + --> $DIR/trait-object-lifetime-parens.rs:9:21 + | +LL | fn f<'a, T: Trait + ('a)>() {} + | ^^^^ + | +help: remove the parentheses + | +LL - fn f<'a, T: Trait + ('a)>() {} +LL + fn f<'a, T: Trait + 'a>() {} + | + +error: parenthesized lifetime bounds are not supported + --> $DIR/trait-object-lifetime-parens.rs:12:24 + | +LL | let _: Box; + | ^^^^ + | +help: remove the parentheses + | +LL - let _: Box; +LL + let _: Box; + | + +error: expected type, found lifetime + --> $DIR/trait-object-lifetime-parens.rs:16:17 + | +LL | let _: Box<('a) + Trait>; + | ^^ expected type + +error[E0178]: expected a path on the left-hand side of `+`, not `((/*ERROR*/))` + --> $DIR/trait-object-lifetime-parens.rs:16:16 + | +LL | let _: Box<('a) + Trait>; + | ^^^^^^^^^^^^ expected a path + +error[E0782]: expected a type, found a trait + --> $DIR/trait-object-lifetime-parens.rs:12:16 + | +LL | let _: Box; + | ^^^^^^^^^^^^ + | +help: you can add the `dyn` keyword if you want a trait object + | +LL | let _: Box; + | +++ + +error: aborting due to 5 previous errors + +Some errors have detailed explanations: E0178, E0782. +For more information about an error, try `rustc --explain E0178`. diff --git a/tests/ui/parser/trait-object-lifetime-parens.rs b/tests/ui/parser/trait-object-lifetime-parens.rs index f44ebe5ba5bf2..0ff4660bb0d58 100644 --- a/tests/ui/parser/trait-object-lifetime-parens.rs +++ b/tests/ui/parser/trait-object-lifetime-parens.rs @@ -1,4 +1,8 @@ -#![allow(bare_trait_objects)] +//@ revisions: e2015 e2021 +//@[e2015] edition: 2015 +//@[e2021] edition: 2021 + +#![cfg_attr(e2015, allow(bare_trait_objects))] trait Trait {} @@ -6,8 +10,12 @@ fn f<'a, T: Trait + ('a)>() {} //~ ERROR parenthesized lifetime bounds are not s fn check<'a>() { let _: Box; //~ ERROR parenthesized lifetime bounds are not supported - // FIXME: It'd be great if we could add suggestion to the following case. - let _: Box<('a) + Trait>; //~ ERROR lifetime in trait object type must be followed by `+` + //[e2021]~^ ERROR expected a type, found a trait + // FIXME: It'd be great if we could suggest removing the parentheses here too. + //[e2015]~v ERROR lifetimes must be followed by `+` to form a trait object type + let _: Box<('a) + Trait>; + //[e2021]~^ ERROR expected type, found lifetime + //[e2021]~| ERROR expected a path on the left-hand side of `+` } fn main() {} From 6242335fdb7444876abf1c3669b6aab1649a0a64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Tue, 15 Apr 2025 07:44:24 +0200 Subject: [PATCH 100/266] Improve diagnostic for E0178 (bad `+` in type) Namely, use a more sensical primary span. Don't pretty-print AST nodes for the diagnostic message. Why: * It's lossy (e.g., it doesn't replicate trailing `+`s in trait objects. * It's prone to leak error nodes (printed as `(/*ERROR*/)`) since the LHS can easily represent recovered code (e.g., `fn(i32?) + T`). --- compiler/rustc_parse/messages.ftl | 2 +- compiler/rustc_parse/src/errors.rs | 1 - .../rustc_parse/src/parser/diagnostics.rs | 10 ++++----- tests/ui/did_you_mean/E0178.stderr | 18 ++++++++------- ...reference-without-parens-suggestion.stderr | 8 +++---- .../ui/impl-trait/impl-trait-plus-priority.rs | 4 ++-- .../impl-trait-plus-priority.stderr | 10 +++++---- .../issues/issue-73568-lifetime-after-mut.rs | 2 +- .../issue-73568-lifetime-after-mut.stderr | 4 ++-- tests/ui/parser/trait-object-bad-parens.rs | 12 ++++------ .../ui/parser/trait-object-bad-parens.stderr | 22 +++++++++---------- .../trait-object-lifetime-parens.e2021.stderr | 4 ++-- .../parser/trait-object-polytrait-priority.rs | 2 +- .../trait-object-polytrait-priority.stderr | 4 ++-- 14 files changed, 51 insertions(+), 52 deletions(-) diff --git a/compiler/rustc_parse/messages.ftl b/compiler/rustc_parse/messages.ftl index e2b5e1cdd0ad6..80cd87a69f78e 100644 --- a/compiler/rustc_parse/messages.ftl +++ b/compiler/rustc_parse/messages.ftl @@ -543,7 +543,7 @@ parse_maybe_recover_from_bad_qpath_stage_2 = .suggestion = types that don't start with an identifier need to be surrounded with angle brackets in qualified paths parse_maybe_recover_from_bad_type_plus = - expected a path on the left-hand side of `+`, not `{$ty}` + expected a path on the left-hand side of `+` parse_maybe_report_ambiguous_plus = ambiguous `+` in a type diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index b28939e062af9..aad8a8bc20527 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -30,7 +30,6 @@ pub(crate) struct AmbiguousPlus { #[derive(Diagnostic)] #[diag(parse_maybe_recover_from_bad_type_plus, code = E0178)] pub(crate) struct BadTypePlus { - pub ty: String, #[primary_span] pub span: Span, #[subdiagnostic] diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index ef044fe9d6385..40246ed78be3e 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -1636,19 +1636,19 @@ impl<'a> Parser<'a> { self.bump(); // `+` let _bounds = self.parse_generic_bounds()?; - let sum_span = ty.span.to(self.prev_token.span); - let sub = match &ty.kind { TyKind::Ref(_lifetime, mut_ty) => { let lo = mut_ty.ty.span.shrink_to_lo(); let hi = self.prev_token.span.shrink_to_hi(); BadTypePlusSub::AddParen { suggestion: AddParen { lo, hi } } } - TyKind::Ptr(..) | TyKind::BareFn(..) => BadTypePlusSub::ForgotParen { span: sum_span }, - _ => BadTypePlusSub::ExpectPath { span: sum_span }, + TyKind::Ptr(..) | TyKind::BareFn(..) => { + BadTypePlusSub::ForgotParen { span: ty.span.to(self.prev_token.span) } + } + _ => BadTypePlusSub::ExpectPath { span: ty.span }, }; - self.dcx().emit_err(BadTypePlus { ty: pprust::ty_to_string(ty), span: sum_span, sub }); + self.dcx().emit_err(BadTypePlus { span: ty.span, sub }); Ok(()) } diff --git a/tests/ui/did_you_mean/E0178.stderr b/tests/ui/did_you_mean/E0178.stderr index 5f289da8a6c30..36e4dbdf7c45d 100644 --- a/tests/ui/did_you_mean/E0178.stderr +++ b/tests/ui/did_you_mean/E0178.stderr @@ -1,41 +1,43 @@ -error[E0178]: expected a path on the left-hand side of `+`, not `&'a Foo` +error[E0178]: expected a path on the left-hand side of `+` --> $DIR/E0178.rs:6:8 | LL | w: &'a Foo + Copy, - | ^^^^^^^^^^^^^^ + | ^^^^^^^ | help: try adding parentheses | LL | w: &'a (Foo + Copy), | + + -error[E0178]: expected a path on the left-hand side of `+`, not `&'a Foo` +error[E0178]: expected a path on the left-hand side of `+` --> $DIR/E0178.rs:7:8 | LL | x: &'a Foo + 'a, - | ^^^^^^^^^^^^ + | ^^^^^^^ | help: try adding parentheses | LL | x: &'a (Foo + 'a), | + + -error[E0178]: expected a path on the left-hand side of `+`, not `&'a mut Foo` +error[E0178]: expected a path on the left-hand side of `+` --> $DIR/E0178.rs:8:8 | LL | y: &'a mut Foo + 'a, - | ^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | help: try adding parentheses | LL | y: &'a mut (Foo + 'a), | + + -error[E0178]: expected a path on the left-hand side of `+`, not `fn() -> Foo` +error[E0178]: expected a path on the left-hand side of `+` --> $DIR/E0178.rs:9:8 | LL | z: fn() -> Foo + 'a, - | ^^^^^^^^^^^^^^^^ perhaps you forgot parentheses? + | ^^^^^^^^^^^----- + | | + | perhaps you forgot parentheses? error: aborting due to 4 previous errors diff --git a/tests/ui/did_you_mean/trait-object-reference-without-parens-suggestion.stderr b/tests/ui/did_you_mean/trait-object-reference-without-parens-suggestion.stderr index 4fee6cc9a2227..762b37b9e9d69 100644 --- a/tests/ui/did_you_mean/trait-object-reference-without-parens-suggestion.stderr +++ b/tests/ui/did_you_mean/trait-object-reference-without-parens-suggestion.stderr @@ -1,19 +1,19 @@ -error[E0178]: expected a path on the left-hand side of `+`, not `&Copy` +error[E0178]: expected a path on the left-hand side of `+` --> $DIR/trait-object-reference-without-parens-suggestion.rs:4:12 | LL | let _: &Copy + 'static; - | ^^^^^^^^^^^^^^^ + | ^^^^^ | help: try adding parentheses | LL | let _: &(Copy + 'static); | + + -error[E0178]: expected a path on the left-hand side of `+`, not `&'static Copy` +error[E0178]: expected a path on the left-hand side of `+` --> $DIR/trait-object-reference-without-parens-suggestion.rs:6:12 | LL | let _: &'static Copy + 'static; - | ^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^ | help: try adding parentheses | diff --git a/tests/ui/impl-trait/impl-trait-plus-priority.rs b/tests/ui/impl-trait/impl-trait-plus-priority.rs index 5575493a17d36..8f76d41266222 100644 --- a/tests/ui/impl-trait/impl-trait-plus-priority.rs +++ b/tests/ui/impl-trait/impl-trait-plus-priority.rs @@ -27,7 +27,7 @@ type A = fn() -> impl A + B; type A = fn() -> dyn A + B; //~^ ERROR ambiguous `+` in a type type A = fn() -> A + B; -//~^ ERROR expected a path on the left-hand side of `+`, not `fn() -> A` +//~^ ERROR expected a path on the left-hand side of `+` type A = Fn() -> impl A +; //~^ ERROR ambiguous `+` in a type @@ -44,6 +44,6 @@ type A = &impl A + B; type A = &dyn A + B; //~^ ERROR ambiguous `+` in a type type A = &A + B; -//~^ ERROR expected a path on the left-hand side of `+`, not `&A` +//~^ ERROR expected a path on the left-hand side of `+` fn main() {} diff --git a/tests/ui/impl-trait/impl-trait-plus-priority.stderr b/tests/ui/impl-trait/impl-trait-plus-priority.stderr index 03e7910095a90..1612065796031 100644 --- a/tests/ui/impl-trait/impl-trait-plus-priority.stderr +++ b/tests/ui/impl-trait/impl-trait-plus-priority.stderr @@ -31,11 +31,13 @@ help: try adding parentheses LL | type A = fn() -> (dyn A + B); | + + -error[E0178]: expected a path on the left-hand side of `+`, not `fn() -> A` +error[E0178]: expected a path on the left-hand side of `+` --> $DIR/impl-trait-plus-priority.rs:29:10 | LL | type A = fn() -> A + B; - | ^^^^^^^^^^^^^ perhaps you forgot parentheses? + | ^^^^^^^^^---- + | | + | perhaps you forgot parentheses? error: ambiguous `+` in a type --> $DIR/impl-trait-plus-priority.rs:32:18 @@ -103,11 +105,11 @@ help: try adding parentheses LL | type A = &(dyn A + B); | + + -error[E0178]: expected a path on the left-hand side of `+`, not `&A` +error[E0178]: expected a path on the left-hand side of `+` --> $DIR/impl-trait-plus-priority.rs:46:10 | LL | type A = &A + B; - | ^^^^^^ + | ^^ | help: try adding parentheses | diff --git a/tests/ui/parser/issues/issue-73568-lifetime-after-mut.rs b/tests/ui/parser/issues/issue-73568-lifetime-after-mut.rs index cf754a6854ecf..782a46ab060e0 100644 --- a/tests/ui/parser/issues/issue-73568-lifetime-after-mut.rs +++ b/tests/ui/parser/issues/issue-73568-lifetime-after-mut.rs @@ -12,7 +12,7 @@ mac!('a); // avoid false positives fn y<'a>(y: &mut 'a + Send) { - //~^ ERROR expected a path on the left-hand side of `+`, not `&mut 'a` + //~^ ERROR expected a path on the left-hand side of `+` //~| ERROR at least one trait is required for an object type let z = y as &mut 'a + Send; //~^ ERROR expected value, found trait `Send` diff --git a/tests/ui/parser/issues/issue-73568-lifetime-after-mut.stderr b/tests/ui/parser/issues/issue-73568-lifetime-after-mut.stderr index 6b8f8e4fe4ee3..ae1ed72853de3 100644 --- a/tests/ui/parser/issues/issue-73568-lifetime-after-mut.stderr +++ b/tests/ui/parser/issues/issue-73568-lifetime-after-mut.stderr @@ -10,11 +10,11 @@ LL - fn x<'a>(x: &mut 'a i32){} LL + fn x<'a>(x: &'a mut i32){} | -error[E0178]: expected a path on the left-hand side of `+`, not `&mut 'a` +error[E0178]: expected a path on the left-hand side of `+` --> $DIR/issue-73568-lifetime-after-mut.rs:14:13 | LL | fn y<'a>(y: &mut 'a + Send) { - | ^^^^^^^^^^^^^^ + | ^^^^^^^ | help: try adding parentheses | diff --git a/tests/ui/parser/trait-object-bad-parens.rs b/tests/ui/parser/trait-object-bad-parens.rs index 8e267c7448feb..bb047a4b43142 100644 --- a/tests/ui/parser/trait-object-bad-parens.rs +++ b/tests/ui/parser/trait-object-bad-parens.rs @@ -5,12 +5,8 @@ auto trait Auto {} fn main() { - let _: Box<((Auto)) + Auto>; - //~^ ERROR expected a path on the left-hand side of `+`, not `((Auto))` - let _: Box<(Auto + Auto) + Auto>; - //~^ ERROR expected a path on the left-hand side of `+`, not `(Auto + Auto)` - let _: Box<(Auto +) + Auto>; - //~^ ERROR expected a path on the left-hand side of `+`, not `(Auto)` - let _: Box<(dyn Auto) + Auto>; - //~^ ERROR expected a path on the left-hand side of `+`, not `(dyn Auto)` + let _: Box<((Auto)) + Auto>; //~ ERROR expected a path on the left-hand side of `+` + let _: Box<(Auto + Auto) + Auto>; //~ ERROR expected a path on the left-hand side of `+` + let _: Box<(Auto +) + Auto>; //~ ERROR expected a path on the left-hand side of `+` + let _: Box<(dyn Auto) + Auto>; //~ ERROR expected a path on the left-hand side of `+` } diff --git a/tests/ui/parser/trait-object-bad-parens.stderr b/tests/ui/parser/trait-object-bad-parens.stderr index 74e484eebee1f..7c2559ce89fd1 100644 --- a/tests/ui/parser/trait-object-bad-parens.stderr +++ b/tests/ui/parser/trait-object-bad-parens.stderr @@ -1,26 +1,26 @@ -error[E0178]: expected a path on the left-hand side of `+`, not `((Auto))` +error[E0178]: expected a path on the left-hand side of `+` --> $DIR/trait-object-bad-parens.rs:8:16 | LL | let _: Box<((Auto)) + Auto>; - | ^^^^^^^^^^^^^^^ expected a path + | ^^^^^^^^ expected a path -error[E0178]: expected a path on the left-hand side of `+`, not `(Auto + Auto)` - --> $DIR/trait-object-bad-parens.rs:10:16 +error[E0178]: expected a path on the left-hand side of `+` + --> $DIR/trait-object-bad-parens.rs:9:16 | LL | let _: Box<(Auto + Auto) + Auto>; - | ^^^^^^^^^^^^^^^^^^^^ expected a path + | ^^^^^^^^^^^^^ expected a path -error[E0178]: expected a path on the left-hand side of `+`, not `(Auto)` - --> $DIR/trait-object-bad-parens.rs:12:16 +error[E0178]: expected a path on the left-hand side of `+` + --> $DIR/trait-object-bad-parens.rs:10:16 | LL | let _: Box<(Auto +) + Auto>; - | ^^^^^^^^^^^^^^^ expected a path + | ^^^^^^^^ expected a path -error[E0178]: expected a path on the left-hand side of `+`, not `(dyn Auto)` - --> $DIR/trait-object-bad-parens.rs:14:16 +error[E0178]: expected a path on the left-hand side of `+` + --> $DIR/trait-object-bad-parens.rs:11:16 | LL | let _: Box<(dyn Auto) + Auto>; - | ^^^^^^^^^^^^^^^^^ expected a path + | ^^^^^^^^^^ expected a path error: aborting due to 4 previous errors diff --git a/tests/ui/parser/trait-object-lifetime-parens.e2021.stderr b/tests/ui/parser/trait-object-lifetime-parens.e2021.stderr index 3518321ea201d..b65c079788a9c 100644 --- a/tests/ui/parser/trait-object-lifetime-parens.e2021.stderr +++ b/tests/ui/parser/trait-object-lifetime-parens.e2021.stderr @@ -28,11 +28,11 @@ error: expected type, found lifetime LL | let _: Box<('a) + Trait>; | ^^ expected type -error[E0178]: expected a path on the left-hand side of `+`, not `((/*ERROR*/))` +error[E0178]: expected a path on the left-hand side of `+` --> $DIR/trait-object-lifetime-parens.rs:16:16 | LL | let _: Box<('a) + Trait>; - | ^^^^^^^^^^^^ expected a path + | ^^^^ expected a path error[E0782]: expected a type, found a trait --> $DIR/trait-object-lifetime-parens.rs:12:16 diff --git a/tests/ui/parser/trait-object-polytrait-priority.rs b/tests/ui/parser/trait-object-polytrait-priority.rs index e7f085104ae9b..85568f0fe1b18 100644 --- a/tests/ui/parser/trait-object-polytrait-priority.rs +++ b/tests/ui/parser/trait-object-polytrait-priority.rs @@ -4,6 +4,6 @@ trait Trait<'a> {} fn main() { let _: &for<'a> Trait<'a> + 'static; - //~^ ERROR expected a path on the left-hand side of `+`, not `&for<'a> Trait<'a>` + //~^ ERROR expected a path on the left-hand side of `+` //~| HELP try adding parentheses } diff --git a/tests/ui/parser/trait-object-polytrait-priority.stderr b/tests/ui/parser/trait-object-polytrait-priority.stderr index 8cb564e79300e..a291a8e229c4b 100644 --- a/tests/ui/parser/trait-object-polytrait-priority.stderr +++ b/tests/ui/parser/trait-object-polytrait-priority.stderr @@ -1,8 +1,8 @@ -error[E0178]: expected a path on the left-hand side of `+`, not `&for<'a> Trait<'a>` +error[E0178]: expected a path on the left-hand side of `+` --> $DIR/trait-object-polytrait-priority.rs:6:12 | LL | let _: &for<'a> Trait<'a> + 'static; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^ | help: try adding parentheses | From 1c1febc59db038876d7fe78a1f056bf324fdff6a Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Tue, 1 Apr 2025 11:19:57 +0300 Subject: [PATCH 101/266] add new config option: `include` Signed-off-by: onur-ozkan --- src/bootstrap/src/core/config/config.rs | 25 ++++++++++++++++++++++- src/bootstrap/src/utils/change_tracker.rs | 5 +++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 25ec64f90b53d..2e88108129010 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -701,6 +701,7 @@ pub(crate) struct TomlConfig { target: Option>, dist: Option, profile: Option, + include: Option>, } /// This enum is used for deserializing change IDs from TOML, allowing both numeric values and the string `"ignore"`. @@ -753,7 +754,7 @@ trait Merge { impl Merge for TomlConfig { fn merge( &mut self, - TomlConfig { build, install, llvm, gcc, rust, dist, target, profile, change_id }: Self, + TomlConfig { build, install, llvm, gcc, rust, dist, target, profile, change_id, include }: Self, replace: ReplaceOpt, ) { fn do_merge(x: &mut Option, y: Option, replace: ReplaceOpt) { @@ -766,6 +767,17 @@ impl Merge for TomlConfig { } } + for include_path in include.clone().unwrap_or_default() { + let included_toml = Config::get_toml(&include_path).unwrap_or_else(|e| { + eprintln!( + "ERROR: Failed to parse default config profile at '{}': {e}", + include_path.display() + ); + exit!(2); + }); + self.merge(included_toml, ReplaceOpt::Override); + } + self.change_id.inner.merge(change_id.inner, replace); self.profile.merge(profile, replace); @@ -1600,6 +1612,17 @@ impl Config { toml.merge(included_toml, ReplaceOpt::IgnoreDuplicate); } + for include_path in toml.include.clone().unwrap_or_default() { + let included_toml = get_toml(&include_path).unwrap_or_else(|e| { + eprintln!( + "ERROR: Failed to parse default config profile at '{}': {e}", + include_path.display() + ); + exit!(2); + }); + toml.merge(included_toml, ReplaceOpt::Override); + } + let mut override_toml = TomlConfig::default(); for option in flags.set.iter() { fn get_table(option: &str) -> Result { diff --git a/src/bootstrap/src/utils/change_tracker.rs b/src/bootstrap/src/utils/change_tracker.rs index 48b6f77e8a587..3f1885a425f83 100644 --- a/src/bootstrap/src/utils/change_tracker.rs +++ b/src/bootstrap/src/utils/change_tracker.rs @@ -396,4 +396,9 @@ pub const CONFIG_CHANGE_HISTORY: &[ChangeInfo] = &[ severity: ChangeSeverity::Info, summary: "Added a new option `build.compiletest-use-stage0-libtest` to force `compiletest` to use the stage 0 libtest.", }, + ChangeInfo { + change_id: 138934, + severity: ChangeSeverity::Info, + summary: "Added new option `include` to create config extensions.", + }, ]; From 89e3befe63f35b7556614d85ce63214f62a9a771 Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Tue, 25 Mar 2025 20:17:32 +0300 Subject: [PATCH 102/266] document config extensions Signed-off-by: onur-ozkan --- .../rustc-dev-guide/src/building/suggested.md | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/doc/rustc-dev-guide/src/building/suggested.md b/src/doc/rustc-dev-guide/src/building/suggested.md index 43ff2ba726f91..5d37a78af8855 100644 --- a/src/doc/rustc-dev-guide/src/building/suggested.md +++ b/src/doc/rustc-dev-guide/src/building/suggested.md @@ -20,6 +20,42 @@ your `.git/hooks` folder as `pre-push` (without the `.sh` extension!). You can also install the hook as a step of running `./x setup`! +## Config extensions + +When working on different tasks, you might need to switch between different bootstrap configurations. +Sometimes you may want to keep an old configuration for future use. But saving raw config values in +random files and manually copying and pasting them can quickly become messy, especially if you have a +long history of different configurations. + +To simplify managing multiple configurations, you can create config extensions. + +For example, you can create a simple config file named `cross.toml`: + +```toml +[build] +build = "x86_64-unknown-linux-gnu" +host = ["i686-unknown-linux-gnu"] +target = ["i686-unknown-linux-gnu"] + + +[llvm] +download-ci-llvm = false + +[target.x86_64-unknown-linux-gnu] +llvm-config = "/path/to/llvm-19/bin/llvm-config" +``` + +Then, include this in your `bootstrap.toml`: + +```toml +include = ["cross.toml"] +``` + +You can also include extensions within extensions recursively. + +**Note:** In the `include` field, the overriding logic follows a right-to-left order. Also, the outer +extension/config always overrides the inner ones. + ## Configuring `rust-analyzer` for `rustc` ### Project-local rust-analyzer setup From 4e80659b32a794513646b93890c9a6eeb103de17 Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Tue, 1 Apr 2025 11:44:33 +0300 Subject: [PATCH 103/266] implement cyclic inclusion handling Signed-off-by: onur-ozkan --- src/bootstrap/src/core/config/config.rs | 51 ++++++++++++++++++------- 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 2e88108129010..86566d0eee178 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -6,6 +6,7 @@ use std::cell::{Cell, RefCell}; use std::collections::{BTreeSet, HashMap, HashSet}; use std::fmt::{self, Display}; +use std::hash::Hash; use std::io::IsTerminal; use std::path::{Path, PathBuf, absolute}; use std::process::Command; @@ -748,19 +749,25 @@ enum ReplaceOpt { } trait Merge { - fn merge(&mut self, other: Self, replace: ReplaceOpt); + fn merge( + &mut self, + included_extensions: &mut HashSet, + other: Self, + replace: ReplaceOpt, + ); } impl Merge for TomlConfig { fn merge( &mut self, + included_extensions: &mut HashSet, TomlConfig { build, install, llvm, gcc, rust, dist, target, profile, change_id, include }: Self, replace: ReplaceOpt, ) { fn do_merge(x: &mut Option, y: Option, replace: ReplaceOpt) { if let Some(new) = y { if let Some(original) = x { - original.merge(new, replace); + original.merge(&mut Default::default(), new, replace); } else { *x = Some(new); } @@ -775,11 +782,20 @@ impl Merge for TomlConfig { ); exit!(2); }); - self.merge(included_toml, ReplaceOpt::Override); + + assert!( + included_extensions.insert(include_path.clone()), + "Cyclic inclusion detected: '{}' is being included again before its previous inclusion was fully processed.", + include_path.display() + ); + + self.merge(included_extensions, included_toml, ReplaceOpt::Override); + + included_extensions.remove(&include_path); } - self.change_id.inner.merge(change_id.inner, replace); - self.profile.merge(profile, replace); + self.change_id.inner.merge(&mut Default::default(), change_id.inner, replace); + self.profile.merge(&mut Default::default(), profile, replace); do_merge(&mut self.build, build, replace); do_merge(&mut self.install, install, replace); @@ -794,7 +810,7 @@ impl Merge for TomlConfig { (Some(original_target), Some(new_target)) => { for (triple, new) in new_target { if let Some(original) = original_target.get_mut(&triple) { - original.merge(new, replace); + original.merge(&mut Default::default(), new, replace); } else { original_target.insert(triple, new); } @@ -815,7 +831,7 @@ macro_rules! define_config { } impl Merge for $name { - fn merge(&mut self, other: Self, replace: ReplaceOpt) { + fn merge(&mut self, _included_extensions: &mut HashSet, other: Self, replace: ReplaceOpt) { $( match replace { ReplaceOpt::IgnoreDuplicate => { @@ -915,7 +931,12 @@ macro_rules! define_config { } impl Merge for Option { - fn merge(&mut self, other: Self, replace: ReplaceOpt) { + fn merge( + &mut self, + _included_extensions: &mut HashSet, + other: Self, + replace: ReplaceOpt, + ) { match replace { ReplaceOpt::IgnoreDuplicate => { if self.is_none() { @@ -1609,7 +1630,7 @@ impl Config { ); exit!(2); }); - toml.merge(included_toml, ReplaceOpt::IgnoreDuplicate); + toml.merge(&mut Default::default(), included_toml, ReplaceOpt::IgnoreDuplicate); } for include_path in toml.include.clone().unwrap_or_default() { @@ -1620,7 +1641,7 @@ impl Config { ); exit!(2); }); - toml.merge(included_toml, ReplaceOpt::Override); + toml.merge(&mut Default::default(), included_toml, ReplaceOpt::Override); } let mut override_toml = TomlConfig::default(); @@ -1631,7 +1652,7 @@ impl Config { let mut err = match get_table(option) { Ok(v) => { - override_toml.merge(v, ReplaceOpt::ErrorOnDuplicate); + override_toml.merge(&mut Default::default(), v, ReplaceOpt::ErrorOnDuplicate); continue; } Err(e) => e, @@ -1642,7 +1663,11 @@ impl Config { if !value.contains('"') { match get_table(&format!(r#"{key}="{value}""#)) { Ok(v) => { - override_toml.merge(v, ReplaceOpt::ErrorOnDuplicate); + override_toml.merge( + &mut Default::default(), + v, + ReplaceOpt::ErrorOnDuplicate, + ); continue; } Err(e) => err = e, @@ -1652,7 +1677,7 @@ impl Config { eprintln!("failed to parse override `{option}`: `{err}"); exit!(2) } - toml.merge(override_toml, ReplaceOpt::Override); + toml.merge(&mut Default::default(), override_toml, ReplaceOpt::Override); config.change_id = toml.change_id.inner; From 78cb4538ee203b08441382b5cd64b1989ed5b3b9 Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Tue, 1 Apr 2025 11:53:32 +0300 Subject: [PATCH 104/266] document `include` in `bootstrap.example.toml` Signed-off-by: onur-ozkan --- bootstrap.example.toml | 5 +++++ src/doc/rustc-dev-guide/src/building/suggested.md | 5 +++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/bootstrap.example.toml b/bootstrap.example.toml index 0927f648635ce..0a314f65ec229 100644 --- a/bootstrap.example.toml +++ b/bootstrap.example.toml @@ -19,6 +19,11 @@ # Note that this has no default value (x.py uses the defaults in `bootstrap.example.toml`). #profile = +# Inherits configuration values from different configuration files (a.k.a. config extensions). +# Supports absolute paths, and uses the current directory (where the bootstrap was invoked) +# as the base if the given path is not absolute. +#include = [] + # Keeps track of major changes made to this configuration. # # This value also represents ID of the PR that caused major changes. Meaning, diff --git a/src/doc/rustc-dev-guide/src/building/suggested.md b/src/doc/rustc-dev-guide/src/building/suggested.md index 5d37a78af8855..b2e258be079d5 100644 --- a/src/doc/rustc-dev-guide/src/building/suggested.md +++ b/src/doc/rustc-dev-guide/src/building/suggested.md @@ -53,8 +53,9 @@ include = ["cross.toml"] You can also include extensions within extensions recursively. -**Note:** In the `include` field, the overriding logic follows a right-to-left order. Also, the outer -extension/config always overrides the inner ones. +**Note:** In the `include` field, the overriding logic follows a right-to-left order. For example, +in `include = ["a.toml", "b.toml"]`, extension `b.toml` overrides `a.toml`. Also, parent extensions +always overrides the inner ones. ## Configuring `rust-analyzer` for `rustc` From 3f70f197f2d131a1f57912f202072b2447d3e326 Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Tue, 1 Apr 2025 21:56:58 +0000 Subject: [PATCH 105/266] apply nit notes Signed-off-by: onur-ozkan --- bootstrap.example.toml | 3 + src/bootstrap/src/core/config/config.rs | 95 ++++++++++++++++++------- 2 files changed, 72 insertions(+), 26 deletions(-) diff --git a/bootstrap.example.toml b/bootstrap.example.toml index 0a314f65ec229..72c4492d465d8 100644 --- a/bootstrap.example.toml +++ b/bootstrap.example.toml @@ -22,6 +22,9 @@ # Inherits configuration values from different configuration files (a.k.a. config extensions). # Supports absolute paths, and uses the current directory (where the bootstrap was invoked) # as the base if the given path is not absolute. +# +# The overriding logic follows a right-to-left order. For example, in `include = ["a.toml", "b.toml"]`, +# extension `b.toml` overrides `a.toml`. Also, parent extensions always overrides the inner ones. #include = [] # Keeps track of major changes made to this configuration. diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 86566d0eee178..e70ac74c7dae2 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -751,6 +751,7 @@ enum ReplaceOpt { trait Merge { fn merge( &mut self, + parent_config_path: Option, included_extensions: &mut HashSet, other: Self, replace: ReplaceOpt, @@ -760,6 +761,7 @@ trait Merge { impl Merge for TomlConfig { fn merge( &mut self, + parent_config_path: Option, included_extensions: &mut HashSet, TomlConfig { build, install, llvm, gcc, rust, dist, target, profile, change_id, include }: Self, replace: ReplaceOpt, @@ -767,19 +769,27 @@ impl Merge for TomlConfig { fn do_merge(x: &mut Option, y: Option, replace: ReplaceOpt) { if let Some(new) = y { if let Some(original) = x { - original.merge(&mut Default::default(), new, replace); + original.merge(None, &mut Default::default(), new, replace); } else { *x = Some(new); } } } - for include_path in include.clone().unwrap_or_default() { + let parent_dir = parent_config_path + .as_ref() + .and_then(|p| p.parent().map(ToOwned::to_owned)) + .unwrap_or_default(); + + for include_path in include.clone().unwrap_or_default().iter().rev() { + let include_path = parent_dir.join(include_path); + let include_path = include_path.canonicalize().unwrap_or_else(|e| { + eprintln!("ERROR: Failed to canonicalize '{}' path: {e}", include_path.display()); + exit!(2); + }); + let included_toml = Config::get_toml(&include_path).unwrap_or_else(|e| { - eprintln!( - "ERROR: Failed to parse default config profile at '{}': {e}", - include_path.display() - ); + eprintln!("ERROR: Failed to parse '{}': {e}", include_path.display()); exit!(2); }); @@ -789,13 +799,20 @@ impl Merge for TomlConfig { include_path.display() ); - self.merge(included_extensions, included_toml, ReplaceOpt::Override); + self.merge( + Some(include_path.clone()), + included_extensions, + included_toml, + // Ensures that parent configuration always takes precedence + // over child configurations. + ReplaceOpt::IgnoreDuplicate, + ); included_extensions.remove(&include_path); } - self.change_id.inner.merge(&mut Default::default(), change_id.inner, replace); - self.profile.merge(&mut Default::default(), profile, replace); + self.change_id.inner.merge(None, &mut Default::default(), change_id.inner, replace); + self.profile.merge(None, &mut Default::default(), profile, replace); do_merge(&mut self.build, build, replace); do_merge(&mut self.install, install, replace); @@ -810,7 +827,7 @@ impl Merge for TomlConfig { (Some(original_target), Some(new_target)) => { for (triple, new) in new_target { if let Some(original) = original_target.get_mut(&triple) { - original.merge(&mut Default::default(), new, replace); + original.merge(None, &mut Default::default(), new, replace); } else { original_target.insert(triple, new); } @@ -831,7 +848,13 @@ macro_rules! define_config { } impl Merge for $name { - fn merge(&mut self, _included_extensions: &mut HashSet, other: Self, replace: ReplaceOpt) { + fn merge( + &mut self, + _parent_config_path: Option, + _included_extensions: &mut HashSet, + other: Self, + replace: ReplaceOpt + ) { $( match replace { ReplaceOpt::IgnoreDuplicate => { @@ -933,6 +956,7 @@ macro_rules! define_config { impl Merge for Option { fn merge( &mut self, + _parent_config_path: Option, _included_extensions: &mut HashSet, other: Self, replace: ReplaceOpt, @@ -1581,7 +1605,8 @@ impl Config { // but not if `bootstrap.toml` hasn't been created. let mut toml = if !using_default_path || toml_path.exists() { config.config = Some(if cfg!(not(test)) { - toml_path.canonicalize().unwrap() + toml_path = toml_path.canonicalize().unwrap(); + toml_path.clone() } else { toml_path.clone() }); @@ -1609,6 +1634,24 @@ impl Config { toml.profile = Some("dist".into()); } + // Reverse the list to ensure the last added config extension remains the most dominant. + // For example, given ["a.toml", "b.toml"], "b.toml" should take precedence over "a.toml". + // + // This must be handled before applying the `profile` since `include`s should always take + // precedence over `profile`s. + for include_path in toml.include.clone().unwrap_or_default().iter().rev() { + let included_toml = get_toml(include_path).unwrap_or_else(|e| { + eprintln!("ERROR: Failed to parse '{}': {e}", include_path.display()); + exit!(2); + }); + toml.merge( + Some(toml_path.join(include_path)), + &mut Default::default(), + included_toml, + ReplaceOpt::IgnoreDuplicate, + ); + } + if let Some(include) = &toml.profile { // Allows creating alias for profile names, allowing // profiles to be renamed while maintaining back compatibility @@ -1630,18 +1673,12 @@ impl Config { ); exit!(2); }); - toml.merge(&mut Default::default(), included_toml, ReplaceOpt::IgnoreDuplicate); - } - - for include_path in toml.include.clone().unwrap_or_default() { - let included_toml = get_toml(&include_path).unwrap_or_else(|e| { - eprintln!( - "ERROR: Failed to parse default config profile at '{}': {e}", - include_path.display() - ); - exit!(2); - }); - toml.merge(&mut Default::default(), included_toml, ReplaceOpt::Override); + toml.merge( + Some(include_path), + &mut Default::default(), + included_toml, + ReplaceOpt::IgnoreDuplicate, + ); } let mut override_toml = TomlConfig::default(); @@ -1652,7 +1689,12 @@ impl Config { let mut err = match get_table(option) { Ok(v) => { - override_toml.merge(&mut Default::default(), v, ReplaceOpt::ErrorOnDuplicate); + override_toml.merge( + None, + &mut Default::default(), + v, + ReplaceOpt::ErrorOnDuplicate, + ); continue; } Err(e) => e, @@ -1664,6 +1706,7 @@ impl Config { match get_table(&format!(r#"{key}="{value}""#)) { Ok(v) => { override_toml.merge( + None, &mut Default::default(), v, ReplaceOpt::ErrorOnDuplicate, @@ -1677,7 +1720,7 @@ impl Config { eprintln!("failed to parse override `{option}`: `{err}"); exit!(2) } - toml.merge(&mut Default::default(), override_toml, ReplaceOpt::Override); + toml.merge(None, &mut Default::default(), override_toml, ReplaceOpt::Override); config.change_id = toml.change_id.inner; From 8e6f50bb4d30801d04619a4cd6406b320eb8919f Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Tue, 15 Apr 2025 10:44:19 +0300 Subject: [PATCH 106/266] fix path and the ordering logic Signed-off-by: onur-ozkan --- src/bootstrap/src/core/config/config.rs | 54 +++++++++++++------------ 1 file changed, 28 insertions(+), 26 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index e70ac74c7dae2..19ed442c500f9 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -776,6 +776,30 @@ impl Merge for TomlConfig { } } + self.change_id.inner.merge(None, &mut Default::default(), change_id.inner, replace); + self.profile.merge(None, &mut Default::default(), profile, replace); + + do_merge(&mut self.build, build, replace); + do_merge(&mut self.install, install, replace); + do_merge(&mut self.llvm, llvm, replace); + do_merge(&mut self.gcc, gcc, replace); + do_merge(&mut self.rust, rust, replace); + do_merge(&mut self.dist, dist, replace); + + match (self.target.as_mut(), target) { + (_, None) => {} + (None, Some(target)) => self.target = Some(target), + (Some(original_target), Some(new_target)) => { + for (triple, new) in new_target { + if let Some(original) = original_target.get_mut(&triple) { + original.merge(None, &mut Default::default(), new, replace); + } else { + original_target.insert(triple, new); + } + } + } + } + let parent_dir = parent_config_path .as_ref() .and_then(|p| p.parent().map(ToOwned::to_owned)) @@ -810,30 +834,6 @@ impl Merge for TomlConfig { included_extensions.remove(&include_path); } - - self.change_id.inner.merge(None, &mut Default::default(), change_id.inner, replace); - self.profile.merge(None, &mut Default::default(), profile, replace); - - do_merge(&mut self.build, build, replace); - do_merge(&mut self.install, install, replace); - do_merge(&mut self.llvm, llvm, replace); - do_merge(&mut self.gcc, gcc, replace); - do_merge(&mut self.rust, rust, replace); - do_merge(&mut self.dist, dist, replace); - - match (self.target.as_mut(), target) { - (_, None) => {} - (None, Some(target)) => self.target = Some(target), - (Some(original_target), Some(new_target)) => { - for (triple, new) in new_target { - if let Some(original) = original_target.get_mut(&triple) { - original.merge(None, &mut Default::default(), new, replace); - } else { - original_target.insert(triple, new); - } - } - } - } } } @@ -1640,12 +1640,14 @@ impl Config { // This must be handled before applying the `profile` since `include`s should always take // precedence over `profile`s. for include_path in toml.include.clone().unwrap_or_default().iter().rev() { - let included_toml = get_toml(include_path).unwrap_or_else(|e| { + let include_path = toml_path.parent().unwrap().join(include_path); + + let included_toml = get_toml(&include_path).unwrap_or_else(|e| { eprintln!("ERROR: Failed to parse '{}': {e}", include_path.display()); exit!(2); }); toml.merge( - Some(toml_path.join(include_path)), + Some(include_path), &mut Default::default(), included_toml, ReplaceOpt::IgnoreDuplicate, From 7dfb457745d7f873eb5db1c3fb39d58fa768740d Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Tue, 15 Apr 2025 11:53:21 +0300 Subject: [PATCH 107/266] add FIXME note in `TomlConfig::merge` Signed-off-by: onur-ozkan --- src/bootstrap/src/core/config/config.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 19ed442c500f9..b7afd81dfdb5b 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -812,6 +812,8 @@ impl Merge for TomlConfig { exit!(2); }); + // FIXME: Similar to `Config::parse_inner`, allow passing a custom `get_toml` from the caller to + // improve testability since `Config::get_toml` does nothing when `cfg(test)` is enabled. let included_toml = Config::get_toml(&include_path).unwrap_or_else(|e| { eprintln!("ERROR: Failed to parse '{}': {e}", include_path.display()); exit!(2); From 1dd77cd24acd5a960c4ddaa7a368d1518a995407 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 27 Mar 2025 18:30:51 +0100 Subject: [PATCH 108/266] Implement `pin!()` using `super let`. --- compiler/rustc_span/src/symbol.rs | 1 - library/core/src/pin.rs | 137 +++++------------- library/coretests/tests/pin_macro.rs | 1 + .../feature-gate-unsafe_pin_internals.rs | 16 -- .../feature-gate-unsafe_pin_internals.stderr | 15 -- tests/ui/pin-macro/cant_access_internals.rs | 12 -- .../ui/pin-macro/cant_access_internals.stderr | 12 -- 7 files changed, 36 insertions(+), 158 deletions(-) delete mode 100644 tests/ui/feature-gates/feature-gate-unsafe_pin_internals.rs delete mode 100644 tests/ui/feature-gates/feature-gate-unsafe_pin_internals.stderr delete mode 100644 tests/ui/pin-macro/cant_access_internals.rs delete mode 100644 tests/ui/pin-macro/cant_access_internals.stderr diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index d1f3eb16e4e4a..4f6e64dc12710 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -2215,7 +2215,6 @@ symbols! { unsafe_extern_blocks, unsafe_fields, unsafe_no_drop_flag, - unsafe_pin_internals, unsafe_pinned, unsafe_unpin, unsize, diff --git a/library/core/src/pin.rs b/library/core/src/pin.rs index 48ed5ae451e40..9e6acf04bf722 100644 --- a/library/core/src/pin.rs +++ b/library/core/src/pin.rs @@ -1092,24 +1092,15 @@ pub use self::unsafe_pinned::UnsafePinned; #[rustc_pub_transparent] #[derive(Copy, Clone)] pub struct Pin { - // FIXME(#93176): this field is made `#[unstable] #[doc(hidden)] pub` to: - // - deter downstream users from accessing it (which would be unsound!), - // - let the `pin!` macro access it (such a macro requires using struct - // literal syntax in order to benefit from lifetime extension). - // - // However, if the `Deref` impl exposes a field with the same name as this - // field, then the two will collide, resulting in a confusing error when the - // user attempts to access the field through a `Pin`. Therefore, the - // name `__pointer` is designed to be unlikely to collide with any other - // field. Long-term, macro hygiene is expected to offer a more robust - // alternative, alongside `unsafe` fields. - #[unstable(feature = "unsafe_pin_internals", issue = "none")] - #[doc(hidden)] - pub __pointer: Ptr, + /// Only public for bootstrap. + #[cfg(bootstrap)] + pub pointer: Ptr, + #[cfg(not(bootstrap))] + pointer: Ptr, } // The following implementations aren't derived in order to avoid soundness -// issues. `&self.__pointer` should not be accessible to untrusted trait +// issues. `&self.pointer` should not be accessible to untrusted trait // implementations. // // See for more details. @@ -1223,7 +1214,7 @@ impl> Pin { #[rustc_const_stable(feature = "const_pin", since = "1.84.0")] #[stable(feature = "pin_into_inner", since = "1.39.0")] pub const fn into_inner(pin: Pin) -> Ptr { - pin.__pointer + pin.pointer } } @@ -1360,7 +1351,7 @@ impl Pin { #[rustc_const_stable(feature = "const_pin", since = "1.84.0")] #[stable(feature = "pin", since = "1.33.0")] pub const unsafe fn new_unchecked(pointer: Ptr) -> Pin { - Pin { __pointer: pointer } + Pin { pointer } } /// Gets a shared reference to the pinned value this [`Pin`] points to. @@ -1374,7 +1365,7 @@ impl Pin { #[inline(always)] pub fn as_ref(&self) -> Pin<&Ptr::Target> { // SAFETY: see documentation on this function - unsafe { Pin::new_unchecked(&*self.__pointer) } + unsafe { Pin::new_unchecked(&*self.pointer) } } } @@ -1418,7 +1409,7 @@ impl Pin { #[inline(always)] pub fn as_mut(&mut self) -> Pin<&mut Ptr::Target> { // SAFETY: see documentation on this function - unsafe { Pin::new_unchecked(&mut *self.__pointer) } + unsafe { Pin::new_unchecked(&mut *self.pointer) } } /// Gets `Pin<&mut T>` to the underlying pinned value from this nested `Pin`-pointer. @@ -1485,7 +1476,7 @@ impl Pin { where Ptr::Target: Sized, { - *(self.__pointer) = value; + *(self.pointer) = value; } } @@ -1513,7 +1504,7 @@ impl Pin { #[rustc_const_stable(feature = "const_pin", since = "1.84.0")] #[stable(feature = "pin_into_inner", since = "1.39.0")] pub const unsafe fn into_inner_unchecked(pin: Pin) -> Ptr { - pin.__pointer + pin.pointer } } @@ -1539,7 +1530,7 @@ impl<'a, T: ?Sized> Pin<&'a T> { U: ?Sized, F: FnOnce(&T) -> &U, { - let pointer = &*self.__pointer; + let pointer = &*self.pointer; let new_pointer = func(pointer); // SAFETY: the safety contract for `new_unchecked` must be @@ -1569,7 +1560,7 @@ impl<'a, T: ?Sized> Pin<&'a T> { #[rustc_const_stable(feature = "const_pin", since = "1.84.0")] #[stable(feature = "pin", since = "1.33.0")] pub const fn get_ref(self) -> &'a T { - self.__pointer + self.pointer } } @@ -1580,7 +1571,7 @@ impl<'a, T: ?Sized> Pin<&'a mut T> { #[rustc_const_stable(feature = "const_pin", since = "1.84.0")] #[stable(feature = "pin", since = "1.33.0")] pub const fn into_ref(self) -> Pin<&'a T> { - Pin { __pointer: self.__pointer } + Pin { pointer: self.pointer } } /// Gets a mutable reference to the data inside of this `Pin`. @@ -1600,7 +1591,7 @@ impl<'a, T: ?Sized> Pin<&'a mut T> { where T: Unpin, { - self.__pointer + self.pointer } /// Gets a mutable reference to the data inside of this `Pin`. @@ -1618,7 +1609,7 @@ impl<'a, T: ?Sized> Pin<&'a mut T> { #[stable(feature = "pin", since = "1.33.0")] #[rustc_const_stable(feature = "const_pin", since = "1.84.0")] pub const unsafe fn get_unchecked_mut(self) -> &'a mut T { - self.__pointer + self.pointer } /// Constructs a new pin by mapping the interior value. @@ -1705,21 +1696,21 @@ impl LegacyReceiver for Pin {} #[stable(feature = "pin", since = "1.33.0")] impl fmt::Debug for Pin { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Debug::fmt(&self.__pointer, f) + fmt::Debug::fmt(&self.pointer, f) } } #[stable(feature = "pin", since = "1.33.0")] impl fmt::Display for Pin { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(&self.__pointer, f) + fmt::Display::fmt(&self.pointer, f) } } #[stable(feature = "pin", since = "1.33.0")] impl fmt::Pointer for Pin { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Pointer::fmt(&self.__pointer, f) + fmt::Pointer::fmt(&self.pointer, f) } } @@ -1945,80 +1936,22 @@ unsafe impl PinCoerceUnsized for *mut T {} /// constructor. /// /// [`Box::pin`]: ../../std/boxed/struct.Box.html#method.pin +#[cfg(not(bootstrap))] #[stable(feature = "pin_macro", since = "1.68.0")] #[rustc_macro_transparency = "semitransparent"] -#[allow_internal_unstable(unsafe_pin_internals)] -#[rustc_macro_edition_2021] +#[allow_internal_unstable(super_let)] pub macro pin($value:expr $(,)?) { - // This is `Pin::new_unchecked(&mut { $value })`, so, for starters, let's - // review such a hypothetical macro (that any user-code could define): - // - // ```rust - // macro_rules! pin {( $value:expr ) => ( - // match &mut { $value } { at_value => unsafe { // Do not wrap `$value` in an `unsafe` block. - // $crate::pin::Pin::<&mut _>::new_unchecked(at_value) - // }} - // )} - // ``` - // - // Safety: - // - `type P = &mut _`. There are thus no pathological `Deref{,Mut}` impls - // that would break `Pin`'s invariants. - // - `{ $value }` is braced, making it a _block expression_, thus **moving** - // the given `$value`, and making it _become an **anonymous** temporary_. - // By virtue of being anonymous, it can no longer be accessed, thus - // preventing any attempts to `mem::replace` it or `mem::forget` it, _etc._ - // - // This gives us a `pin!` definition that is sound, and which works, but only - // in certain scenarios: - // - If the `pin!(value)` expression is _directly_ fed to a function call: - // `let poll = pin!(fut).poll(cx);` - // - If the `pin!(value)` expression is part of a scrutinee: - // ```rust - // match pin!(fut) { pinned_fut => { - // pinned_fut.as_mut().poll(...); - // pinned_fut.as_mut().poll(...); - // }} // <- `fut` is dropped here. - // ``` - // Alas, it doesn't work for the more straight-forward use-case: `let` bindings. - // ```rust - // let pinned_fut = pin!(fut); // <- temporary value is freed at the end of this statement - // pinned_fut.poll(...) // error[E0716]: temporary value dropped while borrowed - // // note: consider using a `let` binding to create a longer lived value - // ``` - // - Issues such as this one are the ones motivating https://github.com/rust-lang/rfcs/pull/66 - // - // This makes such a macro incredibly unergonomic in practice, and the reason most macros - // out there had to take the path of being a statement/binding macro (_e.g._, `pin!(future);`) - // instead of featuring the more intuitive ergonomics of an expression macro. - // - // Luckily, there is a way to avoid the problem. Indeed, the problem stems from the fact that a - // temporary is dropped at the end of its enclosing statement when it is part of the parameters - // given to function call, which has precisely been the case with our `Pin::new_unchecked()`! - // For instance, - // ```rust - // let p = Pin::new_unchecked(&mut ); - // ``` - // becomes: - // ```rust - // let p = { let mut anon = ; &mut anon }; - // ``` - // - // However, when using a literal braced struct to construct the value, references to temporaries - // can then be taken. This makes Rust change the lifespan of such temporaries so that they are, - // instead, dropped _at the end of the enscoping block_. - // For instance, - // ```rust - // let p = Pin { __pointer: &mut }; - // ``` - // becomes: - // ```rust - // let mut anon = ; - // let p = Pin { __pointer: &mut anon }; - // ``` - // which is *exactly* what we want. - // - // See https://doc.rust-lang.org/1.58.1/reference/destructors.html#temporary-lifetime-extension - // for more info. - $crate::pin::Pin::<&mut _> { __pointer: &mut { $value } } + { + super let mut pinned = $value; + // SAFETY: The value is pinned: it is the local above which cannot be named outside this macro. + unsafe { $crate::pin::Pin::new_unchecked(&mut pinned) } + } +} + +/// Only for bootstrap. +#[cfg(bootstrap)] +#[stable(feature = "pin_macro", since = "1.68.0")] +#[rustc_macro_transparency = "semitransparent"] +pub macro pin($value:expr $(,)?) { + $crate::pin::Pin::<&mut _> { pointer: &mut { $value } } } diff --git a/library/coretests/tests/pin_macro.rs b/library/coretests/tests/pin_macro.rs index bfbfa8d280fa1..3174c91a6498b 100644 --- a/library/coretests/tests/pin_macro.rs +++ b/library/coretests/tests/pin_macro.rs @@ -38,6 +38,7 @@ fn rust_2024_expr() { } #[test] +#[cfg(not(bootstrap))] fn temp_lifetime() { // Check that temporary lifetimes work as in Rust 2021. // Regression test for https://github.com/rust-lang/rust/issues/138596 diff --git a/tests/ui/feature-gates/feature-gate-unsafe_pin_internals.rs b/tests/ui/feature-gates/feature-gate-unsafe_pin_internals.rs deleted file mode 100644 index deb5a2f691b8e..0000000000000 --- a/tests/ui/feature-gates/feature-gate-unsafe_pin_internals.rs +++ /dev/null @@ -1,16 +0,0 @@ -//@ edition:2018 -#![forbid(internal_features, unsafe_code)] -#![feature(unsafe_pin_internals)] -//~^ ERROR the feature `unsafe_pin_internals` is internal to the compiler or standard library - -use core::{marker::PhantomPinned, pin::Pin}; - -/// The `unsafe_pin_internals` is indeed unsound. -fn non_unsafe_pin_new_unchecked(pointer: &mut T) -> Pin<&mut T> { - Pin { __pointer: pointer } -} - -fn main() { - let mut self_referential = PhantomPinned; - let _: Pin<&mut PhantomPinned> = non_unsafe_pin_new_unchecked(&mut self_referential); -} diff --git a/tests/ui/feature-gates/feature-gate-unsafe_pin_internals.stderr b/tests/ui/feature-gates/feature-gate-unsafe_pin_internals.stderr deleted file mode 100644 index fc9bcd90e52ee..0000000000000 --- a/tests/ui/feature-gates/feature-gate-unsafe_pin_internals.stderr +++ /dev/null @@ -1,15 +0,0 @@ -error: the feature `unsafe_pin_internals` is internal to the compiler or standard library - --> $DIR/feature-gate-unsafe_pin_internals.rs:3:12 - | -LL | #![feature(unsafe_pin_internals)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: using it is strongly discouraged -note: the lint level is defined here - --> $DIR/feature-gate-unsafe_pin_internals.rs:2:11 - | -LL | #![forbid(internal_features, unsafe_code)] - | ^^^^^^^^^^^^^^^^^ - -error: aborting due to 1 previous error - diff --git a/tests/ui/pin-macro/cant_access_internals.rs b/tests/ui/pin-macro/cant_access_internals.rs deleted file mode 100644 index 36a47d0fdf937..0000000000000 --- a/tests/ui/pin-macro/cant_access_internals.rs +++ /dev/null @@ -1,12 +0,0 @@ -//@ edition:2018 - -use core::{ - marker::PhantomPinned, - mem, - pin::{pin, Pin}, -}; - -fn main() { - let mut phantom_pinned = pin!(PhantomPinned); - mem::take(phantom_pinned.__pointer); //~ ERROR use of unstable library feature `unsafe_pin_internals` -} diff --git a/tests/ui/pin-macro/cant_access_internals.stderr b/tests/ui/pin-macro/cant_access_internals.stderr deleted file mode 100644 index 8ad897bbbb951..0000000000000 --- a/tests/ui/pin-macro/cant_access_internals.stderr +++ /dev/null @@ -1,12 +0,0 @@ -error[E0658]: use of unstable library feature `unsafe_pin_internals` - --> $DIR/cant_access_internals.rs:11:15 - | -LL | mem::take(phantom_pinned.__pointer); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | - = help: add `#![feature(unsafe_pin_internals)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0658`. From d20b270b4e431a010e9149a64e816a9ff2b3dec9 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Fri, 28 Mar 2025 09:41:31 +0100 Subject: [PATCH 109/266] Don't name macro internals in "does not live long enough" errors. --- .../src/diagnostics/conflict_errors.rs | 16 +++++++++++----- .../src/diagnostics/explain_borrow.rs | 4 +++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 8a8ecc3b96e3c..2853ae0239e77 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -2959,21 +2959,27 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } } - let mut err = self.path_does_not_live_long_enough(borrow_span, &format!("`{name}`")); + let name = if borrow_span.in_external_macro(self.infcx.tcx.sess.source_map()) { + // Don't name local variables in external macros. + "value".to_string() + } else { + format!("`{name}`") + }; + + let mut err = self.path_does_not_live_long_enough(borrow_span, &name); if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) { let region_name = annotation.emit(self, &mut err); err.span_label( borrow_span, - format!("`{name}` would have to be valid for `{region_name}`..."), + format!("{name} would have to be valid for `{region_name}`..."), ); err.span_label( drop_span, format!( - "...but `{}` will be dropped here, when the {} returns", - name, + "...but {name} will be dropped here, when the {} returns", self.infcx .tcx .opt_item_name(self.mir_def_id().to_def_id()) @@ -3011,7 +3017,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } } else { err.span_label(borrow_span, "borrowed value does not live long enough"); - err.span_label(drop_span, format!("`{name}` dropped here while still borrowed")); + err.span_label(drop_span, format!("{name} dropped here while still borrowed")); borrow_spans.args_subdiag(&mut err, |args_span| { crate::session_diagnostics::CaptureArgLabel::Capture { diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index f77dda0d386aa..a845431facac1 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -95,7 +95,9 @@ impl<'tcx> BorrowExplanation<'tcx> { && let hir::def::Res::Local(hir_id) = p.res && let hir::Node::Pat(pat) = tcx.hir_node(hir_id) { - err.span_label(pat.span, format!("binding `{ident}` declared here")); + if !ident.span.in_external_macro(tcx.sess.source_map()) { + err.span_label(pat.span, format!("binding `{ident}` declared here")); + } } } } From 1ca930098911d5059b810b473941a94185cb29ff Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 27 Mar 2025 18:32:53 +0100 Subject: [PATCH 110/266] Update tests. --- ...ine_coroutine.main.Inline.panic-abort.diff | 2 +- ...ne_coroutine.main.Inline.panic-unwind.diff | 2 +- ...y.run2-{closure#0}.Inline.panic-abort.diff | 6 +++--- ....run2-{closure#0}.Inline.panic-unwind.diff | 6 +++--- tests/pretty/postfix-yield.rs | 3 ++- .../pin-ergonomics/reborrow-once.stderr | 2 +- tests/ui/coroutine/postfix-yield.rs | 2 +- .../lifetime_errors_on_promotion_misusage.rs | 4 ++-- ...fetime_errors_on_promotion_misusage.stderr | 20 +++++++------------ tests/ui/pin-macro/pin_move.stderr | 5 +++++ 10 files changed, 26 insertions(+), 26 deletions(-) diff --git a/tests/mir-opt/inline/inline_coroutine.main.Inline.panic-abort.diff b/tests/mir-opt/inline/inline_coroutine.main.Inline.panic-abort.diff index 56d4d50e967e2..151580da19e09 100644 --- a/tests/mir-opt/inline/inline_coroutine.main.Inline.panic-abort.diff +++ b/tests/mir-opt/inline/inline_coroutine.main.Inline.panic-abort.diff @@ -33,7 +33,7 @@ - _4 = g() -> [return: bb1, unwind unreachable]; + _4 = {coroutine@$DIR/inline_coroutine.rs:20:5: 20:8 (#0)}; + _3 = &mut _4; -+ _2 = Pin::<&mut {coroutine@$DIR/inline_coroutine.rs:20:5: 20:8}> { __pointer: copy _3 }; ++ _2 = Pin::<&mut {coroutine@$DIR/inline_coroutine.rs:20:5: 20:8}> { pointer: copy _3 }; + StorageDead(_3); + StorageLive(_5); + _5 = const false; diff --git a/tests/mir-opt/inline/inline_coroutine.main.Inline.panic-unwind.diff b/tests/mir-opt/inline/inline_coroutine.main.Inline.panic-unwind.diff index 751916a00f14d..6196fc0d0c6bf 100644 --- a/tests/mir-opt/inline/inline_coroutine.main.Inline.panic-unwind.diff +++ b/tests/mir-opt/inline/inline_coroutine.main.Inline.panic-unwind.diff @@ -33,7 +33,7 @@ - _4 = g() -> [return: bb1, unwind continue]; + _4 = {coroutine@$DIR/inline_coroutine.rs:20:5: 20:8 (#0)}; + _3 = &mut _4; -+ _2 = Pin::<&mut {coroutine@$DIR/inline_coroutine.rs:20:5: 20:8}> { __pointer: copy _3 }; ++ _2 = Pin::<&mut {coroutine@$DIR/inline_coroutine.rs:20:5: 20:8}> { pointer: copy _3 }; + StorageDead(_3); + StorageLive(_5); + _5 = const false; diff --git a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff index e49d7cea28e58..1e9a6dd4f5c8f 100644 --- a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff +++ b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff @@ -121,7 +121,7 @@ - } - - bb2: { -+ _4 = Pin::<&mut {async fn body of ActionPermit<'_, T>::perform()}> { __pointer: copy _5 }; ++ _4 = Pin::<&mut {async fn body of ActionPermit<'_, T>::perform()}> { pointer: copy _5 }; StorageDead(_5); StorageLive(_6); StorageLive(_7); @@ -218,7 +218,7 @@ + _37 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); + _21 = &mut (((*_37) as variant#3).1: std::future::Ready<()>); + _20 = &mut (*_21); -+ _19 = Pin::<&mut std::future::Ready<()>> { __pointer: copy _20 }; ++ _19 = Pin::<&mut std::future::Ready<()>> { pointer: copy _20 }; + StorageDead(_20); + StorageLive(_22); + StorageLive(_23); @@ -239,7 +239,7 @@ + _48 = &mut (_19.0: &mut std::future::Ready<()>); + _45 = copy (_19.0: &mut std::future::Ready<()>); + StorageDead(_48); -+ _47 = Pin::<&mut std::future::Ready<()>> { __pointer: copy _45 }; ++ _47 = Pin::<&mut std::future::Ready<()>> { pointer: copy _45 }; + StorageDead(_47); + _44 = &mut ((*_45).0: std::option::Option<()>); + StorageLive(_49); diff --git a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff index e7aed556f2d71..94b89a310baa8 100644 --- a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff +++ b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff @@ -123,7 +123,7 @@ - } - - bb2: { -+ _4 = Pin::<&mut {async fn body of ActionPermit<'_, T>::perform()}> { __pointer: copy _5 }; ++ _4 = Pin::<&mut {async fn body of ActionPermit<'_, T>::perform()}> { pointer: copy _5 }; StorageDead(_5); StorageLive(_6); StorageLive(_7); @@ -235,7 +235,7 @@ + _37 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); + _21 = &mut (((*_37) as variant#3).1: std::future::Ready<()>); + _20 = &mut (*_21); -+ _19 = Pin::<&mut std::future::Ready<()>> { __pointer: copy _20 }; ++ _19 = Pin::<&mut std::future::Ready<()>> { pointer: copy _20 }; + StorageDead(_20); + StorageLive(_22); + StorageLive(_23); @@ -256,7 +256,7 @@ + _50 = &mut (_19.0: &mut std::future::Ready<()>); + _47 = copy (_19.0: &mut std::future::Ready<()>); + StorageDead(_50); -+ _49 = Pin::<&mut std::future::Ready<()>> { __pointer: copy _47 }; ++ _49 = Pin::<&mut std::future::Ready<()>> { pointer: copy _47 }; + StorageDead(_49); + _46 = &mut ((*_47).0: std::option::Option<()>); + StorageLive(_51); diff --git a/tests/pretty/postfix-yield.rs b/tests/pretty/postfix-yield.rs index f76e8142ae86c..60380a4071c54 100644 --- a/tests/pretty/postfix-yield.rs +++ b/tests/pretty/postfix-yield.rs @@ -2,7 +2,8 @@ //@ edition: 2024 //@ pp-exact -#![feature(gen_blocks, coroutines, coroutine_trait, yield_expr)] +#![feature(gen_blocks, coroutines, coroutine_trait, yield_expr, +stmt_expr_attributes)] use std::ops::{Coroutine, CoroutineState}; use std::pin::pin; diff --git a/tests/ui/async-await/pin-ergonomics/reborrow-once.stderr b/tests/ui/async-await/pin-ergonomics/reborrow-once.stderr index a1ea2b4a57a70..dc8e424ad2a42 100644 --- a/tests/ui/async-await/pin-ergonomics/reborrow-once.stderr +++ b/tests/ui/async-await/pin-ergonomics/reborrow-once.stderr @@ -1,4 +1,4 @@ -error[E0499]: cannot borrow `*x.__pointer` as mutable more than once at a time +error[E0499]: cannot borrow `*x.pointer` as mutable more than once at a time --> $DIR/reborrow-once.rs:12:14 | LL | twice(x, x); diff --git a/tests/ui/coroutine/postfix-yield.rs b/tests/ui/coroutine/postfix-yield.rs index ff843138c8c2c..f2fdcebdaa9a9 100644 --- a/tests/ui/coroutine/postfix-yield.rs +++ b/tests/ui/coroutine/postfix-yield.rs @@ -3,7 +3,7 @@ //@ run-pass //@ edition: 2024 -#![feature(gen_blocks, coroutines, coroutine_trait, yield_expr)] +#![feature(gen_blocks, coroutines, coroutine_trait, yield_expr, stmt_expr_attributes)] use std::ops::{Coroutine, CoroutineState}; use std::pin::pin; diff --git a/tests/ui/pin-macro/lifetime_errors_on_promotion_misusage.rs b/tests/ui/pin-macro/lifetime_errors_on_promotion_misusage.rs index 8a0244e8145a7..e505fe435207c 100644 --- a/tests/ui/pin-macro/lifetime_errors_on_promotion_misusage.rs +++ b/tests/ui/pin-macro/lifetime_errors_on_promotion_misusage.rs @@ -9,14 +9,14 @@ use core::{ fn function_call_stops_borrow_extension() { let phantom_pinned = identity(pin!(PhantomPinned)); - //~^ ERROR temporary value dropped while borrowed + //~^ ERROR does not live long enough stuff(phantom_pinned) } fn promotion_only_works_for_the_innermost_block() { let phantom_pinned = { let phantom_pinned = pin!(PhantomPinned); - //~^ ERROR temporary value dropped while borrowed + //~^ ERROR does not live long enough phantom_pinned }; stuff(phantom_pinned) diff --git a/tests/ui/pin-macro/lifetime_errors_on_promotion_misusage.stderr b/tests/ui/pin-macro/lifetime_errors_on_promotion_misusage.stderr index 9df7f0ffd0c3f..43fb82be7c2f0 100644 --- a/tests/ui/pin-macro/lifetime_errors_on_promotion_misusage.stderr +++ b/tests/ui/pin-macro/lifetime_errors_on_promotion_misusage.stderr @@ -1,35 +1,29 @@ -error[E0716]: temporary value dropped while borrowed +error[E0597]: value does not live long enough --> $DIR/lifetime_errors_on_promotion_misusage.rs:11:35 | LL | let phantom_pinned = identity(pin!(PhantomPinned)); - | ^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement + | ^^^^^^^^^^^^^^^^^^^ - value dropped here while still borrowed | | - | creates a temporary value which is freed while still in use + | borrowed value does not live long enough LL | LL | stuff(phantom_pinned) | -------------- borrow later used here | = note: this error originates in the macro `pin` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider using a `let` binding to create a longer lived value - | -LL ~ let binding = pin!(PhantomPinned); -LL ~ let phantom_pinned = identity(binding); - | -error[E0716]: temporary value dropped while borrowed +error[E0597]: value does not live long enough --> $DIR/lifetime_errors_on_promotion_misusage.rs:18:30 | LL | let phantom_pinned = { | -------------- borrow later stored here LL | let phantom_pinned = pin!(PhantomPinned); - | ^^^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use + | ^^^^^^^^^^^^^^^^^^^ borrowed value does not live long enough ... LL | }; - | - temporary value is freed at the end of this statement + | - value dropped here while still borrowed | - = note: consider using a `let` binding to create a longer lived value = note: this error originates in the macro `pin` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0716`. +For more information about this error, try `rustc --explain E0597`. diff --git a/tests/ui/pin-macro/pin_move.stderr b/tests/ui/pin-macro/pin_move.stderr index c9b8ad9b2021f..3f46602098850 100644 --- a/tests/ui/pin-macro/pin_move.stderr +++ b/tests/ui/pin-macro/pin_move.stderr @@ -31,6 +31,11 @@ LL | struct NotCopy(T); LL | let mut pointee = NotCopy(PhantomPinned); LL | pin!(*&mut pointee); | ------------- you could clone this value +help: consider removing the dereference here + | +LL - pin!(*&mut pointee); +LL + pin!(&mut pointee); + | error: aborting due to 2 previous errors From ee53c26b41a74eb0ecf785e8cfac98e5aa980756 Mon Sep 17 00:00:00 2001 From: Obei Sideg Date: Tue, 8 Apr 2025 05:29:19 +0300 Subject: [PATCH 111/266] Add `explicit_extern_abis` unstable feature also add `explicit-extern-abis` feature section to the unstable book. --- compiler/rustc_feature/src/unstable.rs | 2 ++ compiler/rustc_span/src/symbol.rs | 1 + .../language-features/explicit-extern-abis.md | 23 +++++++++++++++++++ 3 files changed, 26 insertions(+) create mode 100644 src/doc/unstable-book/src/language-features/explicit-extern-abis.md diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 36e375c778d3f..d0ac822ba26e4 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -477,6 +477,8 @@ declare_features! ( (incomplete, ergonomic_clones, "1.87.0", Some(132290)), /// Allows exhaustive pattern matching on types that contain uninhabited types. (unstable, exhaustive_patterns, "1.13.0", Some(51085)), + /// Disallows `extern` without an explicit ABI. + (unstable, explicit_extern_abis, "CURRENT_RUSTC_VERSION", Some(134986)), /// Allows explicit tail calls via `become` expression. (incomplete, explicit_tail_calls, "1.72.0", Some(112788)), /// Allows using `aapcs`, `efiapi`, `sysv64` and `win64` as calling conventions diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index d1f3eb16e4e4a..0a2e4e4977f37 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -916,6 +916,7 @@ symbols! { expf16, expf32, expf64, + explicit_extern_abis, explicit_generic_args_with_impl_trait, explicit_tail_calls, export_name, diff --git a/src/doc/unstable-book/src/language-features/explicit-extern-abis.md b/src/doc/unstable-book/src/language-features/explicit-extern-abis.md new file mode 100644 index 0000000000000..ba622466ba74a --- /dev/null +++ b/src/doc/unstable-book/src/language-features/explicit-extern-abis.md @@ -0,0 +1,23 @@ +# `explicit_extern_abis` + +The tracking issue for this feature is: #134986 + +------ + +Disallow `extern` without an explicit ABI. We should write `extern "C"` +(or another ABI) instead of just `extern`. + +By making the ABI explicit, it becomes much clearer that "C" is just one of the +possible choices, rather than the "standard" way for external functions. +Removing the default makes it easier to add a new ABI on equal footing as "C". + +```rust,editionfuture,compile_fail +#![feature(explicit_extern_abis)] + +extern fn function1() {} // ERROR `extern` declarations without an explicit ABI + // are disallowed + +extern "C" fn function2() {} // compiles + +extern "aapcs" fn function3() {} // compiles +``` From 2907ab5bf9583bec1acb389637ed300ef333b273 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 15 Apr 2025 12:13:11 +0200 Subject: [PATCH 112/266] Move `is_builder_target`, `is_system_llvm` and `is_rust_llvm` from `Builder` to `Config` --- src/bootstrap/src/core/build_steps/compile.rs | 10 +++-- src/bootstrap/src/core/build_steps/dist.rs | 10 +++-- src/bootstrap/src/core/build_steps/llvm.rs | 6 +-- src/bootstrap/src/core/build_steps/test.rs | 4 +- src/bootstrap/src/core/config/config.rs | 36 ++++++++++++++++ src/bootstrap/src/core/sanity.rs | 2 +- src/bootstrap/src/lib.rs | 42 ++----------------- 7 files changed, 57 insertions(+), 53 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index dab58fccf5e68..30ab142b53bd7 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -155,7 +155,7 @@ impl Step for Std { // When using `download-rustc`, we already have artifacts for the host available. Don't // recompile them. - if builder.download_rustc() && builder.is_builder_target(target) + if builder.download_rustc() && builder.config.is_builder_target(target) // NOTE: the beta compiler may generate different artifacts than the downloaded compiler, so // its artifacts can't be reused. && compiler.stage != 0 @@ -229,7 +229,7 @@ impl Step for Std { // The LLD wrappers and `rust-lld` are self-contained linking components that can be // necessary to link the stdlib on some targets. We'll also need to copy these binaries to // the `stage0-sysroot` to ensure the linker is found when bootstrapping on such a target. - if compiler.stage == 0 && builder.is_builder_target(compiler.host) { + if compiler.stage == 0 && builder.config.is_builder_target(compiler.host) { trace!( "(build == host) copying linking components to `stage0-sysroot` for bootstrapping" ); @@ -1374,7 +1374,7 @@ pub fn rustc_cargo_env( /// Pass down configuration from the LLVM build into the build of /// rustc_llvm and rustc_codegen_llvm. fn rustc_llvm_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) { - if builder.is_rust_llvm(target) { + if builder.config.is_rust_llvm(target) { cargo.env("LLVM_RUSTLLVM", "1"); } if builder.config.llvm_enzyme { @@ -2532,7 +2532,9 @@ pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) // FIXME: to make things simpler for now, limit this to the host and target where we know // `strip -g` is both available and will fix the issue, i.e. on a x64 linux host that is not // cross-compiling. Expand this to other appropriate targets in the future. - if target != "x86_64-unknown-linux-gnu" || !builder.is_builder_target(target) || !path.exists() + if target != "x86_64-unknown-linux-gnu" + || !builder.config.is_builder_target(target) + || !path.exists() { return; } diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index 83f71aeed7204..00043cfc20470 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -612,7 +612,7 @@ impl Step for DebuggerScripts { fn skip_host_target_lib(builder: &Builder<'_>, compiler: Compiler) -> bool { // The only true set of target libraries came from the build triple, so // let's reduce redundant work by only producing archives from that host. - if !builder.is_builder_target(compiler.host) { + if !builder.config.is_builder_target(compiler.host) { builder.info("\tskipping, not a build host"); true } else { @@ -671,7 +671,9 @@ fn copy_target_libs( &self_contained_dst.join(path.file_name().unwrap()), FileType::NativeLibrary, ); - } else if dependency_type == DependencyType::Target || builder.is_builder_target(target) { + } else if dependency_type == DependencyType::Target + || builder.config.is_builder_target(target) + { builder.copy_link(&path, &dst.join(path.file_name().unwrap()), FileType::NativeLibrary); } } @@ -824,7 +826,7 @@ impl Step for Analysis { fn run(self, builder: &Builder<'_>) -> Option { let compiler = self.compiler; let target = self.target; - if !builder.is_builder_target(compiler.host) { + if !builder.config.is_builder_target(compiler.host) { return None; } @@ -2118,7 +2120,7 @@ fn maybe_install_llvm( // // If the LLVM is coming from ourselves (just from CI) though, we // still want to install it, as it otherwise won't be available. - if builder.is_system_llvm(target) { + if builder.config.is_system_llvm(target) { trace!("system LLVM requested, no install"); return false; } diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index 69a8bd59f16ca..f29520d25cf81 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -485,7 +485,7 @@ impl Step for Llvm { } // https://llvm.org/docs/HowToCrossCompileLLVM.html - if !builder.is_builder_target(target) { + if !builder.config.is_builder_target(target) { let LlvmResult { llvm_config, .. } = builder.ensure(Llvm { target: builder.config.build }); if !builder.config.dry_run() { @@ -637,7 +637,7 @@ fn configure_cmake( } cfg.target(&target.triple).host(&builder.config.build.triple); - if !builder.is_builder_target(target) { + if !builder.config.is_builder_target(target) { cfg.define("CMAKE_CROSSCOMPILING", "True"); // NOTE: Ideally, we wouldn't have to do this, and `cmake-rs` would just handle it for us. @@ -1098,7 +1098,7 @@ impl Step for Lld { .define("LLVM_CMAKE_DIR", llvm_cmake_dir) .define("LLVM_INCLUDE_TESTS", "OFF"); - if !builder.is_builder_target(target) { + if !builder.config.is_builder_target(target) { // Use the host llvm-tblgen binary. cfg.define( "LLVM_TABLEGEN_EXE", diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index b1a3bba08871d..ad62651cc6949 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -1894,7 +1894,7 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the .arg(llvm_components.trim()); llvm_components_passed = true; } - if !builder.is_rust_llvm(target) { + if !builder.config.is_rust_llvm(target) { cmd.arg("--system-llvm"); } @@ -2668,7 +2668,7 @@ impl Step for Crate { cargo } else { // Also prepare a sysroot for the target. - if !builder.is_builder_target(target) { + if !builder.config.is_builder_target(target) { builder.ensure(compile::Std::new(compiler, target).force_recompile(true)); builder.ensure(RemoteCopyLibs { compiler, target }); } diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 25ec64f90b53d..57015797a6299 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -3233,6 +3233,42 @@ impl Config { Some(commit.to_string()) } + + /// Checks if the given target is the same as the builder target. + pub fn is_builder_target(&self, target: TargetSelection) -> bool { + self.build == target + } + + /// Returns `true` if this is an external version of LLVM not managed by bootstrap. + /// In particular, we expect llvm sources to be available when this is false. + /// + /// NOTE: this is not the same as `!is_rust_llvm` when `llvm_has_patches` is set. + pub fn is_system_llvm(&self, target: TargetSelection) -> bool { + match self.target_config.get(&target) { + Some(Target { llvm_config: Some(_), .. }) => { + let ci_llvm = self.llvm_from_ci && self.is_builder_target(target); + !ci_llvm + } + // We're building from the in-tree src/llvm-project sources. + Some(Target { llvm_config: None, .. }) => false, + None => false, + } + } + + /// Returns `true` if this is our custom, patched, version of LLVM. + /// + /// This does not necessarily imply that we're managing the `llvm-project` submodule. + pub fn is_rust_llvm(&self, target: TargetSelection) -> bool { + match self.target_config.get(&target) { + // We're using a user-controlled version of LLVM. The user has explicitly told us whether the version has our patches. + // (They might be wrong, but that's not a supported use-case.) + // In particular, this tries to support `submodules = false` and `patches = false`, for using a newer version of LLVM that's not through `rust-lang/llvm-project`. + Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched, + // The user hasn't promised the patches match. + // This only has our patches if it's downloaded from CI or built from source. + _ => !self.is_system_llvm(target), + } + } } /// Compares the current `Llvm` options against those in the CI LLVM builder and detects any incompatible options. diff --git a/src/bootstrap/src/core/sanity.rs b/src/bootstrap/src/core/sanity.rs index 891340add908e..0310937e60c18 100644 --- a/src/bootstrap/src/core/sanity.rs +++ b/src/bootstrap/src/core/sanity.rs @@ -325,7 +325,7 @@ than building it. if target.contains("musl") && !target.contains("unikraft") { // If this is a native target (host is also musl) and no musl-root is given, // fall back to the system toolchain in /usr before giving up - if build.musl_root(*target).is_none() && build.is_builder_target(*target) { + if build.musl_root(*target).is_none() && build.config.is_builder_target(*target) { let target = build.config.target_config.entry(*target).or_default(); target.musl_root = Some("/usr".into()); } diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index 1a513a240e173..e088cf52073c4 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -35,7 +35,7 @@ use utils::channel::GitInfo; use crate::core::builder; use crate::core::builder::Kind; -use crate::core::config::{DryRun, LldMode, LlvmLibunwind, Target, TargetSelection, flags}; +use crate::core::config::{DryRun, LldMode, LlvmLibunwind, TargetSelection, flags}; use crate::utils::exec::{BehaviorOnFailure, BootstrapCommand, CommandOutput, OutputMode, command}; use crate::utils::helpers::{ self, dir_is_empty, exe, libdir, output, set_file_times, split_debuginfo, symlink_dir, @@ -803,7 +803,7 @@ impl Build { /// Note that if LLVM is configured externally then the directory returned /// will likely be empty. fn llvm_out(&self, target: TargetSelection) -> PathBuf { - if self.config.llvm_from_ci && self.is_builder_target(target) { + if self.config.llvm_from_ci && self.config.is_builder_target(target) { self.config.ci_llvm_root() } else { self.out.join(target).join("llvm") @@ -851,37 +851,6 @@ impl Build { if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None } } - /// Returns `true` if this is an external version of LLVM not managed by bootstrap. - /// In particular, we expect llvm sources to be available when this is false. - /// - /// NOTE: this is not the same as `!is_rust_llvm` when `llvm_has_patches` is set. - fn is_system_llvm(&self, target: TargetSelection) -> bool { - match self.config.target_config.get(&target) { - Some(Target { llvm_config: Some(_), .. }) => { - let ci_llvm = self.config.llvm_from_ci && self.is_builder_target(target); - !ci_llvm - } - // We're building from the in-tree src/llvm-project sources. - Some(Target { llvm_config: None, .. }) => false, - None => false, - } - } - - /// Returns `true` if this is our custom, patched, version of LLVM. - /// - /// This does not necessarily imply that we're managing the `llvm-project` submodule. - fn is_rust_llvm(&self, target: TargetSelection) -> bool { - match self.config.target_config.get(&target) { - // We're using a user-controlled version of LLVM. The user has explicitly told us whether the version has our patches. - // (They might be wrong, but that's not a supported use-case.) - // In particular, this tries to support `submodules = false` and `patches = false`, for using a newer version of LLVM that's not through `rust-lang/llvm-project`. - Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched, - // The user hasn't promised the patches match. - // This only has our patches if it's downloaded from CI or built from source. - _ => !self.is_system_llvm(target), - } - } - /// Returns the path to `FileCheck` binary for the specified target fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf { let target_config = self.config.target_config.get(&target); @@ -1356,7 +1325,7 @@ Executed at: {executed_at}"#, // need to use CXX compiler as linker to resolve the exception functions // that are only existed in CXX libraries Some(self.cxx.borrow()[&target].path().into()) - } else if !self.is_builder_target(target) + } else if !self.config.is_builder_target(target) && helpers::use_host_linker(target) && !target.is_msvc() { @@ -2025,11 +1994,6 @@ to download LLVM rather than building it. stream.reset().unwrap(); result } - - /// Checks if the given target is the same as the builder target. - fn is_builder_target(&self, target: TargetSelection) -> bool { - self.config.build == target - } } #[cfg(unix)] From 3c01dfe2ae09aef9ee42223f492764717e152cde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 15 Apr 2025 12:15:10 +0200 Subject: [PATCH 113/266] Rename `is_builder_target` to `is_host_target` --- src/bootstrap/src/core/build_steps/compile.rs | 6 +++--- src/bootstrap/src/core/build_steps/dist.rs | 7 +++---- src/bootstrap/src/core/build_steps/llvm.rs | 6 +++--- src/bootstrap/src/core/build_steps/test.rs | 2 +- src/bootstrap/src/core/builder/tests.rs | 4 ++-- src/bootstrap/src/core/config/config.rs | 6 +++--- src/bootstrap/src/core/sanity.rs | 2 +- src/bootstrap/src/lib.rs | 4 ++-- 8 files changed, 18 insertions(+), 19 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 30ab142b53bd7..f78539b47816b 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -229,7 +229,7 @@ impl Step for Std { // The LLD wrappers and `rust-lld` are self-contained linking components that can be // necessary to link the stdlib on some targets. We'll also need to copy these binaries to // the `stage0-sysroot` to ensure the linker is found when bootstrapping on such a target. - if compiler.stage == 0 && builder.config.is_builder_target(compiler.host) { + if compiler.stage == 0 && builder.config.is_host_target(compiler.host) { trace!( "(build == host) copying linking components to `stage0-sysroot` for bootstrapping" ); @@ -2182,7 +2182,7 @@ impl Step for Assemble { debug!("copying codegen backends to sysroot"); copy_codegen_backends_to_sysroot(builder, build_compiler, target_compiler); - if builder.config.lld_enabled { + if builder.config.lld_enabled && !builder.config.is_system_llvm(target_compiler.host) { builder.ensure(crate::core::build_steps::tool::LldWrapper { build_compiler, target_compiler, @@ -2533,7 +2533,7 @@ pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) // `strip -g` is both available and will fix the issue, i.e. on a x64 linux host that is not // cross-compiling. Expand this to other appropriate targets in the future. if target != "x86_64-unknown-linux-gnu" - || !builder.config.is_builder_target(target) + || !builder.config.is_host_target(target) || !path.exists() { return; diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index 00043cfc20470..ed90ede793622 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -612,7 +612,7 @@ impl Step for DebuggerScripts { fn skip_host_target_lib(builder: &Builder<'_>, compiler: Compiler) -> bool { // The only true set of target libraries came from the build triple, so // let's reduce redundant work by only producing archives from that host. - if !builder.config.is_builder_target(compiler.host) { + if !builder.config.is_host_target(compiler.host) { builder.info("\tskipping, not a build host"); true } else { @@ -671,8 +671,7 @@ fn copy_target_libs( &self_contained_dst.join(path.file_name().unwrap()), FileType::NativeLibrary, ); - } else if dependency_type == DependencyType::Target - || builder.config.is_builder_target(target) + } else if dependency_type == DependencyType::Target || builder.config.is_host_target(target) { builder.copy_link(&path, &dst.join(path.file_name().unwrap()), FileType::NativeLibrary); } @@ -826,7 +825,7 @@ impl Step for Analysis { fn run(self, builder: &Builder<'_>) -> Option { let compiler = self.compiler; let target = self.target; - if !builder.config.is_builder_target(compiler.host) { + if !builder.config.is_host_target(compiler.host) { return None; } diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index f29520d25cf81..0c82cb16348e6 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -485,7 +485,7 @@ impl Step for Llvm { } // https://llvm.org/docs/HowToCrossCompileLLVM.html - if !builder.config.is_builder_target(target) { + if !builder.config.is_host_target(target) { let LlvmResult { llvm_config, .. } = builder.ensure(Llvm { target: builder.config.build }); if !builder.config.dry_run() { @@ -637,7 +637,7 @@ fn configure_cmake( } cfg.target(&target.triple).host(&builder.config.build.triple); - if !builder.config.is_builder_target(target) { + if !builder.config.is_host_target(target) { cfg.define("CMAKE_CROSSCOMPILING", "True"); // NOTE: Ideally, we wouldn't have to do this, and `cmake-rs` would just handle it for us. @@ -1098,7 +1098,7 @@ impl Step for Lld { .define("LLVM_CMAKE_DIR", llvm_cmake_dir) .define("LLVM_INCLUDE_TESTS", "OFF"); - if !builder.config.is_builder_target(target) { + if !builder.config.is_host_target(target) { // Use the host llvm-tblgen binary. cfg.define( "LLVM_TABLEGEN_EXE", diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index ad62651cc6949..096f7de65975a 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -2668,7 +2668,7 @@ impl Step for Crate { cargo } else { // Also prepare a sysroot for the target. - if !builder.config.is_builder_target(target) { + if !builder.config.is_host_target(target) { builder.ensure(compile::Std::new(compiler, target).force_recompile(true)); builder.ensure(RemoteCopyLibs { compiler, target }); } diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index fd3b28e4e6ab2..5de824ebab238 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1107,8 +1107,8 @@ fn test_is_builder_target() { let build = Build::new(config); let builder = Builder::new(&build); - assert!(builder.is_builder_target(target1)); - assert!(!builder.is_builder_target(target2)); + assert!(builder.config.is_host_target(target1)); + assert!(!builder.config.is_host_target(target2)); } } diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 57015797a6299..12e157a34ae3e 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -3234,8 +3234,8 @@ impl Config { Some(commit.to_string()) } - /// Checks if the given target is the same as the builder target. - pub fn is_builder_target(&self, target: TargetSelection) -> bool { + /// Checks if the given target is the same as the host target. + pub fn is_host_target(&self, target: TargetSelection) -> bool { self.build == target } @@ -3246,7 +3246,7 @@ impl Config { pub fn is_system_llvm(&self, target: TargetSelection) -> bool { match self.target_config.get(&target) { Some(Target { llvm_config: Some(_), .. }) => { - let ci_llvm = self.llvm_from_ci && self.is_builder_target(target); + let ci_llvm = self.llvm_from_ci && self.is_host_target(target); !ci_llvm } // We're building from the in-tree src/llvm-project sources. diff --git a/src/bootstrap/src/core/sanity.rs b/src/bootstrap/src/core/sanity.rs index 0310937e60c18..4b020a7edb7ba 100644 --- a/src/bootstrap/src/core/sanity.rs +++ b/src/bootstrap/src/core/sanity.rs @@ -325,7 +325,7 @@ than building it. if target.contains("musl") && !target.contains("unikraft") { // If this is a native target (host is also musl) and no musl-root is given, // fall back to the system toolchain in /usr before giving up - if build.musl_root(*target).is_none() && build.config.is_builder_target(*target) { + if build.musl_root(*target).is_none() && build.config.is_host_target(*target) { let target = build.config.target_config.entry(*target).or_default(); target.musl_root = Some("/usr".into()); } diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index e088cf52073c4..88d181532a7ff 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -803,7 +803,7 @@ impl Build { /// Note that if LLVM is configured externally then the directory returned /// will likely be empty. fn llvm_out(&self, target: TargetSelection) -> PathBuf { - if self.config.llvm_from_ci && self.config.is_builder_target(target) { + if self.config.llvm_from_ci && self.config.is_host_target(target) { self.config.ci_llvm_root() } else { self.out.join(target).join("llvm") @@ -1325,7 +1325,7 @@ Executed at: {executed_at}"#, // need to use CXX compiler as linker to resolve the exception functions // that are only existed in CXX libraries Some(self.cxx.borrow()[&target].path().into()) - } else if !self.config.is_builder_target(target) + } else if !self.config.is_host_target(target) && helpers::use_host_linker(target) && !target.is_msvc() { From 502b630cd1042d8b2b613a12278a01c641cf096a Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Tue, 15 Apr 2025 13:11:14 +0200 Subject: [PATCH 114/266] tidy: don't crush on non-existent submodules --- src/tools/tidy/src/deps.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 88c2a02798ace..46e55859a5785 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -682,8 +682,10 @@ pub static CRATES: &[&str] = &[ pub fn has_missing_submodule(root: &Path, submodules: &[&str]) -> bool { !CiEnv::is_ci() && submodules.iter().any(|submodule| { + let path = root.join(submodule); + !path.exists() // If the directory is empty, we can consider it as an uninitialized submodule. - read_dir(root.join(submodule)).unwrap().next().is_none() + || read_dir(path).unwrap().next().is_none() }) } From 52f4b16075bf01d2c8f8539c26fb9b135967713f Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Tue, 15 Apr 2025 14:06:51 +0200 Subject: [PATCH 115/266] use helper function instead of writing rustfmt stamp by hand --- src/bootstrap/src/core/build_steps/format.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/src/core/build_steps/format.rs b/src/bootstrap/src/core/build_steps/format.rs index b1a97bde97b5b..43b831adf1f70 100644 --- a/src/bootstrap/src/core/build_steps/format.rs +++ b/src/bootstrap/src/core/build_steps/format.rs @@ -81,7 +81,8 @@ fn update_rustfmt_version(build: &Builder<'_>) { let Some((version, stamp_file)) = get_rustfmt_version(build) else { return; }; - t!(std::fs::write(stamp_file.path(), version)) + + t!(stamp_file.add_stamp(version).write()); } /// Returns the Rust files modified between the `merge-base` of HEAD and From dda4d7bc44aa4909aae72cd38965a11ccf46c02e Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Tue, 15 Apr 2025 14:06:51 +0200 Subject: [PATCH 116/266] slightly correct comments and diagnostics about checking modifications I feel like they are still wrong, but maybe less so .-. The `info:` was unhelpful -- we only use upstream in CI nowdays. --- src/bootstrap/src/core/build_steps/format.rs | 17 +++++++++-------- src/build_helper/src/git.rs | 6 ++++-- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/format.rs b/src/bootstrap/src/core/build_steps/format.rs index 43b831adf1f70..25d5f97d7eec5 100644 --- a/src/bootstrap/src/core/build_steps/format.rs +++ b/src/bootstrap/src/core/build_steps/format.rs @@ -85,11 +85,15 @@ fn update_rustfmt_version(build: &Builder<'_>) { t!(stamp_file.add_stamp(version).write()); } -/// Returns the Rust files modified between the `merge-base` of HEAD and -/// rust-lang/master and what is now on the disk. Does not include removed files. +/// Returns the Rust files modified between the last merge commit and what is now on the disk. +/// Does not include removed files. /// /// Returns `None` if all files should be formatted. fn get_modified_rs_files(build: &Builder<'_>) -> Result>, String> { + // In CI `get_git_modified_files` returns something different to normal environment. + // This shouldn't be called in CI anyway. + assert!(!build.config.is_running_on_ci); + if !verify_rustfmt_version(build) { return Ok(None); } @@ -104,7 +108,7 @@ struct RustfmtConfig { // Prints output describing a collection of paths, with lines such as "formatted modified file // foo/bar/baz" or "skipped 20 untracked files". -fn print_paths(build: &Builder<'_>, verb: &str, adjective: Option<&str>, paths: &[String]) { +fn print_paths(verb: &str, adjective: Option<&str>, paths: &[String]) { let len = paths.len(); let adjective = if let Some(adjective) = adjective { format!("{adjective} ") } else { String::new() }; @@ -115,9 +119,6 @@ fn print_paths(build: &Builder<'_>, verb: &str, adjective: Option<&str>, paths: } else { println!("fmt: {verb} {len} {adjective}files"); } - if len > 1000 && !build.config.is_running_on_ci { - println!("hint: if this number seems too high, try running `git fetch origin master`"); - } } pub fn format(build: &Builder<'_>, check: bool, all: bool, paths: &[PathBuf]) { @@ -190,7 +191,7 @@ pub fn format(build: &Builder<'_>, check: bool, all: bool, paths: &[PathBuf]) { ) .map(|x| x.to_string()) .collect(); - print_paths(build, "skipped", Some("untracked"), &untracked_paths); + print_paths("skipped", Some("untracked"), &untracked_paths); for untracked_path in untracked_paths { // The leading `/` makes it an exact match against the @@ -319,7 +320,7 @@ pub fn format(build: &Builder<'_>, check: bool, all: bool, paths: &[PathBuf]) { }); let mut paths = formatted_paths.into_inner().unwrap(); paths.sort(); - print_paths(build, if check { "checked" } else { "formatted" }, adjective, &paths); + print_paths(if check { "checked" } else { "formatted" }, adjective, &paths); drop(tx); diff --git a/src/build_helper/src/git.rs b/src/build_helper/src/git.rs index 693e0fc8f46d8..f5347c3082410 100644 --- a/src/build_helper/src/git.rs +++ b/src/build_helper/src/git.rs @@ -114,7 +114,9 @@ fn git_upstream_merge_base( Ok(output_result(git.arg("merge-base").arg(&updated_master).arg("HEAD"))?.trim().to_owned()) } -/// Searches for the nearest merge commit in the repository that also exists upstream. +/// Searches for the nearest merge commit in the repository. +/// +/// **In CI** finds the nearest merge commit that *also exists upstream*. /// /// It looks for the most recent commit made by the merge bot by matching the author's email /// address with the merge bot's email. @@ -165,7 +167,7 @@ pub fn get_closest_merge_commit( Ok(output_result(&mut git)?.trim().to_owned()) } -/// Returns the files that have been modified in the current branch compared to the master branch. +/// Returns the files that have been modified in the current branch compared to the last merge. /// The `extensions` parameter can be used to filter the files by their extension. /// Does not include removed files. /// If `extensions` is empty, all files will be returned. From 8934ac575988f2c15b7910d2f683b2792e5916cb Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Tue, 15 Apr 2025 14:06:51 +0200 Subject: [PATCH 117/266] add a comment for code that isn't --- src/bootstrap/src/core/build_steps/format.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/src/core/build_steps/format.rs b/src/bootstrap/src/core/build_steps/format.rs index 25d5f97d7eec5..6641c4b4e139b 100644 --- a/src/bootstrap/src/core/build_steps/format.rs +++ b/src/bootstrap/src/core/build_steps/format.rs @@ -214,7 +214,13 @@ pub fn format(build: &Builder<'_>, check: bool, all: bool, paths: &[PathBuf]) { override_builder.add(&format!("/{file}")).expect(&file); } } - Ok(None) => {} + Ok(None) => { + // NOTE: `Ok(None)` signifies that we need to format all files. + // The tricky part here is that if `override_builder` isn't given any white + // list files (i.e. files to be formatted, added without leading `!`), it + // will instead look for *all* files. So, by doing nothing here, we are + // actually making it so we format all files. + } Err(err) => { eprintln!("fmt warning: Something went wrong running git commands:"); eprintln!("fmt warning: {err}"); From 52694034ba0e3261fb53c97ca4da7743db4945e7 Mon Sep 17 00:00:00 2001 From: Jason Newcomb Date: Sun, 2 Mar 2025 02:23:14 -0500 Subject: [PATCH 118/266] Add `copy_within` to `IndexSlice` --- compiler/rustc_index/src/slice.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_index/src/slice.rs b/compiler/rustc_index/src/slice.rs index 67ac805c2bfe5..d2702bdb0571d 100644 --- a/compiler/rustc_index/src/slice.rs +++ b/compiler/rustc_index/src/slice.rs @@ -1,6 +1,6 @@ use std::fmt; use std::marker::PhantomData; -use std::ops::{Index, IndexMut}; +use std::ops::{Index, IndexMut, RangeBounds}; use std::slice::GetDisjointMutError::*; use std::slice::{self, SliceIndex}; @@ -104,6 +104,17 @@ impl IndexSlice { self.raw.swap(a.index(), b.index()) } + #[inline] + pub fn copy_within( + &mut self, + src: impl IntoSliceIdx>, + dest: I, + ) where + T: Copy, + { + self.raw.copy_within(src.into_slice_idx(), dest.index()); + } + #[inline] pub fn get>( &self, From 812095031b82b5974e03dafd6bf33d69de712474 Mon Sep 17 00:00:00 2001 From: reddevilmidzy Date: Tue, 15 Apr 2025 23:51:10 +0900 Subject: [PATCH 119/266] Add test for issue 125668 --- tests/ui/consts/const-blocks/const-block-in-array-size.rs | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 tests/ui/consts/const-blocks/const-block-in-array-size.rs diff --git a/tests/ui/consts/const-blocks/const-block-in-array-size.rs b/tests/ui/consts/const-blocks/const-block-in-array-size.rs new file mode 100644 index 0000000000000..ecab24322869c --- /dev/null +++ b/tests/ui/consts/const-blocks/const-block-in-array-size.rs @@ -0,0 +1,5 @@ +//@ check-pass + +type A = [u32; const { 2 }]; + +fn main() {} From 6d52b51d3e6321b7a1d24e5f995aa709057153e3 Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Tue, 15 Apr 2025 19:10:31 +0300 Subject: [PATCH 120/266] add comment in `TomlConfig::merge` about the merge order Signed-off-by: onur-ozkan --- src/bootstrap/src/core/config/config.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index b7afd81dfdb5b..e15aab4ad506e 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -805,6 +805,8 @@ impl Merge for TomlConfig { .and_then(|p| p.parent().map(ToOwned::to_owned)) .unwrap_or_default(); + // `include` handled later since we ignore duplicates using `ReplaceOpt::IgnoreDuplicate` to + // keep the upper-level configuration to take precedence. for include_path in include.clone().unwrap_or_default().iter().rev() { let include_path = parent_dir.join(include_path); let include_path = include_path.canonicalize().unwrap_or_else(|e| { From 11e5987d017b4ab8dfc522d674aea704aad8605a Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 15 Apr 2025 18:46:07 +0000 Subject: [PATCH 121/266] Don't compute name of associated item if it's an RPITIT --- .../rustc_hir_analysis/src/hir_ty_lowering/errors.rs | 3 +-- .../in-trait/dont-probe-missing-item-name.rs | 12 ++++++++++++ .../in-trait/dont-probe-missing-item-name.stderr | 9 +++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 tests/ui/impl-trait/in-trait/dont-probe-missing-item-name.rs create mode 100644 tests/ui/impl-trait/in-trait/dont-probe-missing-item-name.stderr diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs index 72f219bfeb802..3759a224ff75b 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs @@ -204,8 +204,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { .iter() .flat_map(|trait_def_id| tcx.associated_items(*trait_def_id).in_definition_order()) .filter_map(|item| { - (!item.is_impl_trait_in_trait() && item.as_tag() == assoc_tag) - .then_some(item.name()) + (!item.is_impl_trait_in_trait() && item.as_tag() == assoc_tag).then(|| item.name()) }) .collect(); diff --git a/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name.rs b/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name.rs new file mode 100644 index 0000000000000..450f41e209dfb --- /dev/null +++ b/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name.rs @@ -0,0 +1,12 @@ +// Regression test for . + +// Test that we don't try to get the (nonexistent) name of the RPITIT in `Trait::foo` +// when emitting an error for a missing associated item `Trait::Output`. + +trait Trait { + fn foo() -> impl Sized; + fn bar() -> Self::Output; + //~^ ERROR associated type `Output` not found for `Self` +} + +fn main() {} diff --git a/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name.stderr b/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name.stderr new file mode 100644 index 0000000000000..74e15785af19c --- /dev/null +++ b/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name.stderr @@ -0,0 +1,9 @@ +error[E0220]: associated type `Output` not found for `Self` + --> $DIR/dont-probe-missing-item-name.rs:8:23 + | +LL | fn bar() -> Self::Output; + | ^^^^^^ associated type `Output` not found + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0220`. From 2020adba86cb2852b11ab11a440975fb331e8424 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 15 Apr 2025 16:59:16 +0200 Subject: [PATCH 122/266] Fix wrong suggestion for async gen block and add regression ui test for #139839 --- .../src/diagnostics/conflict_errors.rs | 13 +++-- .../async-gen-move-suggestion.fixed | 35 ++++++++++++++ .../async-await/async-gen-move-suggestion.rs | 35 ++++++++++++++ .../async-gen-move-suggestion.stderr | 47 +++++++++++++++++++ 4 files changed, 126 insertions(+), 4 deletions(-) create mode 100644 tests/ui/async-await/async-gen-move-suggestion.fixed create mode 100644 tests/ui/async-await/async-gen-move-suggestion.rs create mode 100644 tests/ui/async-await/async-gen-move-suggestion.stderr diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index fe6dff7ff1b63..959cf9fa51399 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -3376,10 +3376,15 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { let (sugg_span, suggestion) = match tcx.sess.source_map().span_to_snippet(args_span) { Ok(string) => { - let coro_prefix = if string.starts_with("async") { - // `async` is 5 chars long. Not using `.len()` to avoid the cast from `usize` - // to `u32`. - Some(5) + let coro_prefix = if let Some(sub) = string.strip_prefix("async") { + let trimmed_sub = sub.trim_end(); + if trimmed_sub.ends_with("gen") { + // `async` is 5 chars long. + Some((trimmed_sub.len() + 5) as _) + } else { + // `async` is 5 chars long. + Some(5) + } } else if string.starts_with("gen") { // `gen` is 3 chars long Some(3) diff --git a/tests/ui/async-await/async-gen-move-suggestion.fixed b/tests/ui/async-await/async-gen-move-suggestion.fixed new file mode 100644 index 0000000000000..d802076552895 --- /dev/null +++ b/tests/ui/async-await/async-gen-move-suggestion.fixed @@ -0,0 +1,35 @@ +// This is a regression test for . +// It ensures that the "add `move` keyword" suggestion is valid. + +//@ run-rustfix +//@ edition:2024 + +#![feature(coroutines)] +#![feature(gen_blocks)] +#![feature(async_iterator)] + +use std::async_iter::AsyncIterator; + +#[allow(dead_code)] +fn moved() -> impl AsyncIterator { + let mut x = "foo".to_string(); + + async gen move { //~ ERROR + x.clear(); + for x in 3..6 { yield x } + } +} + +#[allow(dead_code)] +fn check_with_whitespace_chars() -> impl AsyncIterator { + let mut x = "foo".to_string(); + + async // Just to check that whitespace characters are correctly handled + gen move { //~^ ERROR + x.clear(); + for x in 3..6 { yield x } + } +} + +fn main() { +} diff --git a/tests/ui/async-await/async-gen-move-suggestion.rs b/tests/ui/async-await/async-gen-move-suggestion.rs new file mode 100644 index 0000000000000..825fb0fd1898c --- /dev/null +++ b/tests/ui/async-await/async-gen-move-suggestion.rs @@ -0,0 +1,35 @@ +// This is a regression test for . +// It ensures that the "add `move` keyword" suggestion is valid. + +//@ run-rustfix +//@ edition:2024 + +#![feature(coroutines)] +#![feature(gen_blocks)] +#![feature(async_iterator)] + +use std::async_iter::AsyncIterator; + +#[allow(dead_code)] +fn moved() -> impl AsyncIterator { + let mut x = "foo".to_string(); + + async gen { //~ ERROR + x.clear(); + for x in 3..6 { yield x } + } +} + +#[allow(dead_code)] +fn check_with_whitespace_chars() -> impl AsyncIterator { + let mut x = "foo".to_string(); + + async // Just to check that whitespace characters are correctly handled + gen { //~^ ERROR + x.clear(); + for x in 3..6 { yield x } + } +} + +fn main() { +} diff --git a/tests/ui/async-await/async-gen-move-suggestion.stderr b/tests/ui/async-await/async-gen-move-suggestion.stderr new file mode 100644 index 0000000000000..b8cdb8be7a4ae --- /dev/null +++ b/tests/ui/async-await/async-gen-move-suggestion.stderr @@ -0,0 +1,47 @@ +error[E0373]: async gen block may outlive the current function, but it borrows `x`, which is owned by the current function + --> $DIR/async-gen-move-suggestion.rs:17:5 + | +LL | async gen { + | ^^^^^^^^^ may outlive borrowed value `x` +LL | x.clear(); + | - `x` is borrowed here + | +note: async gen block is returned here + --> $DIR/async-gen-move-suggestion.rs:17:5 + | +LL | / async gen { +LL | | x.clear(); +LL | | for x in 3..6 { yield x } +LL | | } + | |_____^ +help: to force the async gen block to take ownership of `x` (and any other referenced variables), use the `move` keyword + | +LL | async gen move { + | ++++ + +error[E0373]: async gen block may outlive the current function, but it borrows `x`, which is owned by the current function + --> $DIR/async-gen-move-suggestion.rs:27:5 + | +LL | / async // Just to check that whitespace characters are correctly handled +LL | | gen { + | |_______^ may outlive borrowed value `x` +LL | x.clear(); + | - `x` is borrowed here + | +note: async gen block is returned here + --> $DIR/async-gen-move-suggestion.rs:27:5 + | +LL | / async // Just to check that whitespace characters are correctly handled +LL | | gen { +LL | | x.clear(); +LL | | for x in 3..6 { yield x } +LL | | } + | |_____^ +help: to force the async gen block to take ownership of `x` (and any other referenced variables), use the `move` keyword + | +LL | gen move { + | ++++ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0373`. From 90aec1367481ab05c78fefad314e03b26e84564f Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Tue, 15 Apr 2025 14:06:51 +0200 Subject: [PATCH 123/266] commit rustfmt stump in `x t tidy` even on `check` If checking succeeded, it's equivalent to successfully formatting. --- src/bootstrap/src/core/build_steps/format.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/format.rs b/src/bootstrap/src/core/build_steps/format.rs index 6641c4b4e139b..9da8b27a91778 100644 --- a/src/bootstrap/src/core/build_steps/format.rs +++ b/src/bootstrap/src/core/build_steps/format.rs @@ -336,7 +336,10 @@ pub fn format(build: &Builder<'_>, check: bool, all: bool, paths: &[PathBuf]) { crate::exit!(1); } - if !check { - update_rustfmt_version(build); - } + // Update `build/.rustfmt-stamp`, allowing this code to ignore files which have not been changed + // since last merge. + // + // NOTE: Because of the exit above, this is only reachable if formatting / format checking + // succeeded. So we are not commiting the version if formatting was not good. + update_rustfmt_version(build); } From 89b4eba49cc15e0a4e53f7816473201d12be5f4f Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Tue, 15 Apr 2025 10:09:31 +0200 Subject: [PATCH 124/266] normalize canonical and non-canonical paths in compiletest Apparently there are tests that print canonical paths *and* tests which print non-canonical paths. An example of the latter is `tests/ui/type_length_limit.rs`. --- src/tools/compiletest/src/runtest.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index fc83ea420430b..eb298060b2ece 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -2375,13 +2375,16 @@ impl<'test> TestCx<'test> { let rust_src_dir = rust_src_dir.read_link_utf8().unwrap_or(rust_src_dir.to_path_buf()); normalize_path(&rust_src_dir.join("library"), "$SRC_DIR_REAL"); - // Canonicalize test build directory path. - // Without this some tests fail if build directory is a symlink. - let output_base_dir = self.output_base_dir().canonicalize_utf8().unwrap(); - // eg. // /home/user/rust/build/x86_64-unknown-linux-gnu/test/ui//$name.$revision.$mode/ - normalize_path(&output_base_dir, "$TEST_BUILD_DIR"); + normalize_path(&self.output_base_dir(), "$TEST_BUILD_DIR"); + // Same as above, but with a canonicalized path. + // This is required because some tests print canonical paths inside test build directory, + // so if the build directory is a symlink, normalization doesn't help. + // + // NOTE: There are also tests which print the non-canonical name, so we need both this and + // the above normalizations. + normalize_path(&self.output_base_dir().canonicalize_utf8().unwrap(), "$TEST_BUILD_DIR"); // eg. /home/user/rust/build normalize_path(&self.config.build_root, "$BUILD_DIR"); From f35c85f72fc1249f0553d97482ca29fe3fa0a165 Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Tue, 8 Apr 2025 16:11:28 -0700 Subject: [PATCH 125/266] Add unstable foo::bar extern command line arguments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also refactors some of the crate name parsing code and adds unit tests Issue #122349 Co-authored-by: León Orell Valerian Liehr --- compiler/rustc_session/src/config.rs | 39 +------- compiler/rustc_session/src/config/externs.rs | 79 ++++++++++++++++ .../rustc_session/src/config/externs/tests.rs | 92 +++++++++++++++++++ compiler/rustc_session/src/options.rs | 2 + 4 files changed, 178 insertions(+), 34 deletions(-) create mode 100644 compiler/rustc_session/src/config/externs.rs create mode 100644 compiler/rustc_session/src/config/externs/tests.rs diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index fc05470d941c4..202378560eed7 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -14,6 +14,7 @@ use std::str::{self, FromStr}; use std::sync::LazyLock; use std::{cmp, fmt, fs, iter}; +use externs::{ExternOpt, split_extern_opt}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::stable_hasher::{StableOrd, ToStableHashKey}; use rustc_errors::emitter::HumanReadableErrorType; @@ -39,6 +40,7 @@ use crate::utils::CanonicalizedPath; use crate::{EarlyDiagCtxt, HashStableContext, Session, filesearch, lint}; mod cfg; +mod externs; mod native_libs; pub mod sigpipe; @@ -2205,44 +2207,13 @@ pub fn parse_externs( matches: &getopts::Matches, unstable_opts: &UnstableOptions, ) -> Externs { - fn is_ascii_ident(string: &str) -> bool { - let mut chars = string.chars(); - if let Some(start) = chars.next() - && (start.is_ascii_alphabetic() || start == '_') - { - chars.all(|char| char.is_ascii_alphanumeric() || char == '_') - } else { - false - } - } - let is_unstable_enabled = unstable_opts.unstable_options; let mut externs: BTreeMap = BTreeMap::new(); for arg in matches.opt_strs("extern") { - let (name, path) = match arg.split_once('=') { - None => (arg, None), - Some((name, path)) => (name.to_string(), Some(Path::new(path))), - }; - let (options, name) = match name.split_once(':') { - None => (None, name), - Some((opts, name)) => (Some(opts), name.to_string()), - }; - - if !is_ascii_ident(&name) { - let mut error = early_dcx.early_struct_fatal(format!( - "crate name `{name}` passed to `--extern` is not a valid ASCII identifier" - )); - let adjusted_name = name.replace('-', "_"); - if is_ascii_ident(&adjusted_name) { - #[allow(rustc::diagnostic_outside_of_impl)] // FIXME - error.help(format!( - "consider replacing the dashes with underscores: `{adjusted_name}`" - )); - } - error.emit(); - } + let ExternOpt { crate_name: name, path, options } = + split_extern_opt(early_dcx, unstable_opts, &arg).unwrap_or_else(|e| e.emit()); - let path = path.map(|p| CanonicalizedPath::new(p)); + let path = path.map(|p| CanonicalizedPath::new(p.as_path())); let entry = externs.entry(name.to_owned()); diff --git a/compiler/rustc_session/src/config/externs.rs b/compiler/rustc_session/src/config/externs.rs new file mode 100644 index 0000000000000..1420ee38bf214 --- /dev/null +++ b/compiler/rustc_session/src/config/externs.rs @@ -0,0 +1,79 @@ +//! This module contains code to help parse and manipulate `--extern` arguments. + +use std::path::PathBuf; + +use rustc_errors::{Diag, FatalAbort}; + +use super::UnstableOptions; +use crate::EarlyDiagCtxt; + +#[cfg(test)] +mod tests; + +/// Represents the pieces of an `--extern` argument. +pub(crate) struct ExternOpt { + pub(crate) crate_name: String, + pub(crate) path: Option, + pub(crate) options: Option, +} + +/// Breaks out the major components of an `--extern` argument. +/// +/// The options field will be a string containing comma-separated options that will need further +/// parsing and processing. +pub(crate) fn split_extern_opt<'a>( + early_dcx: &'a EarlyDiagCtxt, + unstable_opts: &UnstableOptions, + extern_opt: &str, +) -> Result> { + let (name, path) = match extern_opt.split_once('=') { + None => (extern_opt.to_string(), None), + Some((name, path)) => (name.to_string(), Some(PathBuf::from(path))), + }; + let (options, crate_name) = match name.split_once(':') { + None => (None, name), + Some((opts, crate_name)) => { + if unstable_opts.namespaced_crates && crate_name.starts_with(':') { + // If the name starts with `:`, we know this was actually something like `foo::bar` and + // not a set of options. We can just use the original name as the crate name. + (None, name) + } else { + (Some(opts.to_string()), crate_name.to_string()) + } + } + }; + + if !valid_crate_name(&crate_name, unstable_opts) { + let mut error = early_dcx.early_struct_fatal(format!( + "crate name `{crate_name}` passed to `--extern` is not a valid ASCII identifier" + )); + let adjusted_name = crate_name.replace('-', "_"); + if is_ascii_ident(&adjusted_name) { + #[allow(rustc::diagnostic_outside_of_impl)] // FIXME + error + .help(format!("consider replacing the dashes with underscores: `{adjusted_name}`")); + } + return Err(error); + } + + Ok(ExternOpt { crate_name, path, options }) +} + +fn valid_crate_name(name: &str, unstable_opts: &UnstableOptions) -> bool { + match name.split_once("::") { + Some((a, b)) if unstable_opts.namespaced_crates => is_ascii_ident(a) && is_ascii_ident(b), + Some(_) => false, + None => is_ascii_ident(name), + } +} + +fn is_ascii_ident(string: &str) -> bool { + let mut chars = string.chars(); + if let Some(start) = chars.next() + && (start.is_ascii_alphabetic() || start == '_') + { + chars.all(|char| char.is_ascii_alphanumeric() || char == '_') + } else { + false + } +} diff --git a/compiler/rustc_session/src/config/externs/tests.rs b/compiler/rustc_session/src/config/externs/tests.rs new file mode 100644 index 0000000000000..6544886951572 --- /dev/null +++ b/compiler/rustc_session/src/config/externs/tests.rs @@ -0,0 +1,92 @@ +use std::path::PathBuf; + +use super::split_extern_opt; +use crate::EarlyDiagCtxt; +use crate::config::UnstableOptions; + +/// Verifies split_extern_opt handles the supported cases. +#[test] +fn test_split_extern_opt() { + let early_dcx = EarlyDiagCtxt::new(<_>::default()); + let unstable_opts = &UnstableOptions::default(); + + let extern_opt = + split_extern_opt(&early_dcx, unstable_opts, "priv,noprelude:foo=libbar.rlib").unwrap(); + assert_eq!(extern_opt.crate_name, "foo"); + assert_eq!(extern_opt.path, Some(PathBuf::from("libbar.rlib"))); + assert_eq!(extern_opt.options, Some("priv,noprelude".to_string())); + + let extern_opt = split_extern_opt(&early_dcx, unstable_opts, "priv,noprelude:foo").unwrap(); + assert_eq!(extern_opt.crate_name, "foo"); + assert_eq!(extern_opt.path, None); + assert_eq!(extern_opt.options, Some("priv,noprelude".to_string())); + + let extern_opt = split_extern_opt(&early_dcx, unstable_opts, "foo=libbar.rlib").unwrap(); + assert_eq!(extern_opt.crate_name, "foo"); + assert_eq!(extern_opt.path, Some(PathBuf::from("libbar.rlib"))); + assert_eq!(extern_opt.options, None); + + let extern_opt = split_extern_opt(&early_dcx, unstable_opts, "foo").unwrap(); + assert_eq!(extern_opt.crate_name, "foo"); + assert_eq!(extern_opt.path, None); + assert_eq!(extern_opt.options, None); +} + +/// Tests some invalid cases for split_extern_opt. +#[test] +fn test_split_extern_opt_invalid() { + let early_dcx = EarlyDiagCtxt::new(<_>::default()); + let unstable_opts = &UnstableOptions::default(); + + // too many `:`s + let result = split_extern_opt(&early_dcx, unstable_opts, "priv:noprelude:foo=libbar.rlib"); + assert!(result.is_err()); + let _ = result.map_err(|e| e.cancel()); + + // can't nest externs without the unstable flag + let result = split_extern_opt(&early_dcx, unstable_opts, "noprelude:foo::bar=libbar.rlib"); + assert!(result.is_err()); + let _ = result.map_err(|e| e.cancel()); +} + +/// Tests some cases for split_extern_opt with nested crates like `foo::bar`. +#[test] +fn test_split_extern_opt_nested() { + let early_dcx = EarlyDiagCtxt::new(<_>::default()); + let unstable_opts = &UnstableOptions { namespaced_crates: true, ..Default::default() }; + + let extern_opt = + split_extern_opt(&early_dcx, unstable_opts, "priv,noprelude:foo::bar=libbar.rlib").unwrap(); + assert_eq!(extern_opt.crate_name, "foo::bar"); + assert_eq!(extern_opt.path, Some(PathBuf::from("libbar.rlib"))); + assert_eq!(extern_opt.options, Some("priv,noprelude".to_string())); + + let extern_opt = + split_extern_opt(&early_dcx, unstable_opts, "priv,noprelude:foo::bar").unwrap(); + assert_eq!(extern_opt.crate_name, "foo::bar"); + assert_eq!(extern_opt.path, None); + assert_eq!(extern_opt.options, Some("priv,noprelude".to_string())); + + let extern_opt = split_extern_opt(&early_dcx, unstable_opts, "foo::bar=libbar.rlib").unwrap(); + assert_eq!(extern_opt.crate_name, "foo::bar"); + assert_eq!(extern_opt.path, Some(PathBuf::from("libbar.rlib"))); + assert_eq!(extern_opt.options, None); + + let extern_opt = split_extern_opt(&early_dcx, unstable_opts, "foo::bar").unwrap(); + assert_eq!(extern_opt.crate_name, "foo::bar"); + assert_eq!(extern_opt.path, None); + assert_eq!(extern_opt.options, None); +} + +/// Tests some invalid cases for split_extern_opt with nested crates like `foo::bar`. +#[test] +fn test_split_extern_opt_nested_invalid() { + let early_dcx = EarlyDiagCtxt::new(<_>::default()); + let unstable_opts = &UnstableOptions { namespaced_crates: true, ..Default::default() }; + + // crates can only be nested one deep. + let result = + split_extern_opt(&early_dcx, unstable_opts, "priv,noprelude:foo::bar::baz=libbar.rlib"); + assert!(result.is_err()); + let _ = result.map_err(|e| e.cancel()); +} diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index c70f1500d3930..bd66f835f1201 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -2331,6 +2331,8 @@ options! { "the size at which the `large_assignments` lint starts to be emitted"), mutable_noalias: bool = (true, parse_bool, [TRACKED], "emit noalias metadata for mutable references (default: yes)"), + namespaced_crates: bool = (false, parse_bool, [TRACKED], + "allow crates to be namespaced by other crates (default: no)"), next_solver: NextSolverConfig = (NextSolverConfig::default(), parse_next_solver_config, [TRACKED], "enable and configure the next generation trait solver used by rustc"), nll_facts: bool = (false, parse_bool, [UNTRACKED], From f3f53d2183a4980f36ee6836f172a01a8b92c44a Mon Sep 17 00:00:00 2001 From: rustbot <47979223+rustbot@users.noreply.github.com> Date: Tue, 15 Apr 2025 22:48:28 +0200 Subject: [PATCH 126/266] Update books --- src/doc/book | 2 +- src/doc/edition-guide | 2 +- src/doc/nomicon | 2 +- src/doc/reference | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/doc/book b/src/doc/book index 45f05367360f0..d33916341d480 160000 --- a/src/doc/book +++ b/src/doc/book @@ -1 +1 @@ -Subproject commit 45f05367360f033f89235eacbbb54e8d73ce6b70 +Subproject commit d33916341d480caede1d0ae57cbeae23aab23e88 diff --git a/src/doc/edition-guide b/src/doc/edition-guide index 1e27e5e6d5133..467f45637b73e 160000 --- a/src/doc/edition-guide +++ b/src/doc/edition-guide @@ -1 +1 @@ -Subproject commit 1e27e5e6d5133ae4612f5cc195c15fc8d51b1c9c +Subproject commit 467f45637b73ec6aa70fb36bc3054bb50b8967ea diff --git a/src/doc/nomicon b/src/doc/nomicon index b4448fa406a6d..0c10c30cc5473 160000 --- a/src/doc/nomicon +++ b/src/doc/nomicon @@ -1 +1 @@ -Subproject commit b4448fa406a6dccde62d1e2f34f70fc51814cdcc +Subproject commit 0c10c30cc54736c5c194ce98c50e2de84eeb6e79 diff --git a/src/doc/reference b/src/doc/reference index 46435cd4eba11..3340922df189b 160000 --- a/src/doc/reference +++ b/src/doc/reference @@ -1 +1 @@ -Subproject commit 46435cd4eba11b66acaa42c01da5c80ad88aee4b +Subproject commit 3340922df189bddcbaad17dc3927d51a76bcd5ed From fe882bf330f00f7bc07327430fdded4164dac25e Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 27 Mar 2025 15:52:33 +1100 Subject: [PATCH 127/266] Rename `LifetimeName` as `LifetimeKind`. It's a much better name, more consistent with how we name such things. Also rename `Lifetime::res` as `Lifetime::kind` to match. I suspect this field used to have the type `LifetimeRes` and then the type was changed but the field name remained the same. --- compiler/rustc_ast_lowering/src/lib.rs | 12 ++--- .../src/diagnostics/region_errors.rs | 2 +- compiler/rustc_hir/src/hir.rs | 20 ++++---- compiler/rustc_hir/src/hir/tests.rs | 2 +- .../src/collect/resolve_bound_vars.rs | 46 +++++++++---------- .../src/hir_ty_lowering/dyn_compatibility.rs | 2 +- compiler/rustc_middle/src/ty/diagnostics.rs | 4 +- .../nice_region_error/static_impl_trait.rs | 8 ++-- .../src/error_reporting/infer/region.rs | 6 +-- src/doc/rustc-dev-guide/src/ty.md | 8 ++-- .../clippy/clippy_lints/src/lifetimes.rs | 14 +++--- src/tools/clippy/clippy_lints/src/ptr.rs | 4 +- .../clippy/clippy_utils/src/hir_utils.rs | 8 ++-- 13 files changed, 68 insertions(+), 68 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index b1d1c35e64a1d..b091847fa7e20 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1768,21 +1768,21 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { debug_assert_ne!(ident.name, kw::Empty); let res = self.resolver.get_lifetime_res(id).unwrap_or(LifetimeRes::Error); let res = match res { - LifetimeRes::Param { param, .. } => hir::LifetimeName::Param(param), + LifetimeRes::Param { param, .. } => hir::LifetimeKind::Param(param), LifetimeRes::Fresh { param, .. } => { debug_assert_eq!(ident.name, kw::UnderscoreLifetime); let param = self.local_def_id(param); - hir::LifetimeName::Param(param) + hir::LifetimeKind::Param(param) } LifetimeRes::Infer => { debug_assert_eq!(ident.name, kw::UnderscoreLifetime); - hir::LifetimeName::Infer + hir::LifetimeKind::Infer } LifetimeRes::Static { .. } => { debug_assert!(matches!(ident.name, kw::StaticLifetime | kw::UnderscoreLifetime)); - hir::LifetimeName::Static + hir::LifetimeKind::Static } - LifetimeRes::Error => hir::LifetimeName::Error, + LifetimeRes::Error => hir::LifetimeKind::Error, LifetimeRes::ElidedAnchor { .. } => { panic!("Unexpected `ElidedAnchar` {:?} at {:?}", ident, ident.span); } @@ -2389,7 +2389,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let r = hir::Lifetime::new( self.next_id(), Ident::new(kw::UnderscoreLifetime, self.lower_span(span)), - hir::LifetimeName::ImplicitObjectLifetimeDefault, + hir::LifetimeKind::ImplicitObjectLifetimeDefault, IsAnonInPath::No, ); debug!("elided_dyn_bound: r={:?}", r); diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 8d530b51636a5..4423edb060518 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -888,7 +888,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { // Skip `async` desugaring `impl Future`. } if let TyKind::TraitObject(_, lt) = alias_ty.kind { - if lt.res == hir::LifetimeName::ImplicitObjectLifetimeDefault { + if lt.kind == hir::LifetimeKind::ImplicitObjectLifetimeDefault { spans_suggs.push((lt.ident.span.shrink_to_hi(), " + 'a".to_string())); } else { spans_suggs.push((lt.ident.span, "'a".to_string())); diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 6455f33b9d153..3f5269eeb9b9d 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -42,7 +42,7 @@ pub enum IsAnonInPath { } /// A lifetime. The valid field combinations are non-obvious. The following -/// example shows some of them. See also the comments on `LifetimeName`. +/// example shows some of them. See also the comments on `LifetimeKind`. /// ``` /// #[repr(C)] /// struct S<'a>(&'a u32); // res=Param, name='a, IsAnonInPath::No @@ -84,7 +84,7 @@ pub struct Lifetime { pub ident: Ident, /// Semantics of this lifetime. - pub res: LifetimeName, + pub kind: LifetimeKind, /// Is the lifetime anonymous and in a path? Used only for error /// suggestions. See `Lifetime::suggestion` for example use. @@ -130,7 +130,7 @@ impl ParamName { } #[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)] -pub enum LifetimeName { +pub enum LifetimeKind { /// User-given names or fresh (synthetic) names. Param(LocalDefId), @@ -160,16 +160,16 @@ pub enum LifetimeName { Static, } -impl LifetimeName { +impl LifetimeKind { fn is_elided(&self) -> bool { match self { - LifetimeName::ImplicitObjectLifetimeDefault | LifetimeName::Infer => true, + LifetimeKind::ImplicitObjectLifetimeDefault | LifetimeKind::Infer => true, // It might seem surprising that `Fresh` counts as not *elided* // -- but this is because, as far as the code in the compiler is // concerned -- `Fresh` variants act equivalently to "some fresh name". // They correspond to early-bound regions on an impl, in other words. - LifetimeName::Error | LifetimeName::Param(..) | LifetimeName::Static => false, + LifetimeKind::Error | LifetimeKind::Param(..) | LifetimeKind::Static => false, } } } @@ -184,10 +184,10 @@ impl Lifetime { pub fn new( hir_id: HirId, ident: Ident, - res: LifetimeName, + kind: LifetimeKind, is_anon_in_path: IsAnonInPath, ) -> Lifetime { - let lifetime = Lifetime { hir_id, ident, res, is_anon_in_path }; + let lifetime = Lifetime { hir_id, ident, kind, is_anon_in_path }; // Sanity check: elided lifetimes form a strict subset of anonymous lifetimes. #[cfg(debug_assertions)] @@ -202,7 +202,7 @@ impl Lifetime { } pub fn is_elided(&self) -> bool { - self.res.is_elided() + self.kind.is_elided() } pub fn is_anonymous(&self) -> bool { @@ -1014,7 +1014,7 @@ pub struct WhereRegionPredicate<'hir> { impl<'hir> WhereRegionPredicate<'hir> { /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate. fn is_param_bound(&self, param_def_id: LocalDefId) -> bool { - self.lifetime.res == LifetimeName::Param(param_def_id) + self.lifetime.kind == LifetimeKind::Param(param_def_id) } } diff --git a/compiler/rustc_hir/src/hir/tests.rs b/compiler/rustc_hir/src/hir/tests.rs index 62ef02d2f500c..fcd0eafa46139 100644 --- a/compiler/rustc_hir/src/hir/tests.rs +++ b/compiler/rustc_hir/src/hir/tests.rs @@ -57,7 +57,7 @@ fn trait_object_roundtrips_impl(syntax: TraitObjectSyntax) { Lifetime { hir_id: HirId::INVALID, ident: Ident::new(sym::name, DUMMY_SP), - res: LifetimeName::Static, + kind: LifetimeKind::Static, is_anon_in_path: IsAnonInPath::No, } }, diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index 1c477755e5ac6..59ab36d98fdab 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -16,7 +16,7 @@ use rustc_errors::ErrorGuaranteed; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::{self, InferKind, Visitor, VisitorExt}; use rustc_hir::{ - self as hir, AmbigArg, GenericArg, GenericParam, GenericParamKind, HirId, LifetimeName, Node, + self as hir, AmbigArg, GenericArg, GenericParam, GenericParamKind, HirId, LifetimeKind, Node, }; use rustc_macros::extension; use rustc_middle::hir::nested_filter; @@ -646,14 +646,14 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { arg: &'tcx hir::PreciseCapturingArg<'tcx>, ) -> Self::Result { match *arg { - hir::PreciseCapturingArg::Lifetime(lt) => match lt.res { - LifetimeName::Param(def_id) => { + hir::PreciseCapturingArg::Lifetime(lt) => match lt.kind { + LifetimeKind::Param(def_id) => { self.resolve_lifetime_ref(def_id, lt); } - LifetimeName::Error => {} - LifetimeName::ImplicitObjectLifetimeDefault - | LifetimeName::Infer - | LifetimeName::Static => { + LifetimeKind::Error => {} + LifetimeKind::ImplicitObjectLifetimeDefault + | LifetimeKind::Infer + | LifetimeKind::Static => { self.tcx.dcx().emit_err(errors::BadPreciseCapture { span: lt.ident.span, kind: "lifetime", @@ -774,26 +774,26 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { ); } }); - match lifetime.res { - LifetimeName::ImplicitObjectLifetimeDefault => { + match lifetime.kind { + LifetimeKind::ImplicitObjectLifetimeDefault => { // If the user does not write *anything*, we // use the object lifetime defaulting // rules. So e.g., `Box` becomes // `Box`. self.resolve_object_lifetime_default(&*lifetime) } - LifetimeName::Infer => { + LifetimeKind::Infer => { // If the user writes `'_`, we use the *ordinary* elision // rules. So the `'_` in e.g., `Box` will be // resolved the same as the `'_` in `&'_ Foo`. // // cc #48468 } - LifetimeName::Param(..) | LifetimeName::Static => { + LifetimeKind::Param(..) | LifetimeKind::Static => { // If the user wrote an explicit name, use that. self.visit_lifetime(&*lifetime); } - LifetimeName::Error => {} + LifetimeKind::Error => {} } } hir::TyKind::Ref(lifetime_ref, ref mt) => { @@ -873,17 +873,17 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { #[instrument(level = "debug", skip(self))] fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) { - match lifetime_ref.res { - hir::LifetimeName::Static => { + match lifetime_ref.kind { + hir::LifetimeKind::Static => { self.insert_lifetime(lifetime_ref, ResolvedArg::StaticLifetime) } - hir::LifetimeName::Param(param_def_id) => { + hir::LifetimeKind::Param(param_def_id) => { self.resolve_lifetime_ref(param_def_id, lifetime_ref) } // If we've already reported an error, just ignore `lifetime_ref`. - hir::LifetimeName::Error => {} + hir::LifetimeKind::Error => {} // Those will be resolved by typechecking. - hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Infer => {} + hir::LifetimeKind::ImplicitObjectLifetimeDefault | hir::LifetimeKind::Infer => {} } } @@ -1063,15 +1063,15 @@ fn object_lifetime_default(tcx: TyCtxt<'_>, param_def_id: LocalDefId) -> ObjectL for bound in bound.bounds { if let hir::GenericBound::Outlives(lifetime) = bound { - set.insert(lifetime.res); + set.insert(lifetime.kind); } } } match set { Set1::Empty => ObjectLifetimeDefault::Empty, - Set1::One(hir::LifetimeName::Static) => ObjectLifetimeDefault::Static, - Set1::One(hir::LifetimeName::Param(param_def_id)) => { + Set1::One(hir::LifetimeKind::Static) => ObjectLifetimeDefault::Static, + Set1::One(hir::LifetimeKind::Param(param_def_id)) => { ObjectLifetimeDefault::Param(param_def_id.to_def_id()) } _ => ObjectLifetimeDefault::Ambiguous, @@ -1241,7 +1241,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { // Fresh lifetimes in APIT used to be allowed in async fns and forbidden in // regular fns. if let Some(hir::PredicateOrigin::ImplTrait) = where_bound_origin - && let hir::LifetimeName::Param(param_id) = lifetime_ref.res + && let hir::LifetimeKind::Param(param_id) = lifetime_ref.kind && let Some(generics) = self.tcx.hir_get_generics(self.tcx.local_parent(param_id)) && let Some(param) = generics.params.iter().find(|p| p.def_id == param_id) @@ -2440,7 +2440,7 @@ fn is_late_bound_map( } fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) { - if let hir::LifetimeName::Param(def_id) = lifetime_ref.res { + if let hir::LifetimeKind::Param(def_id) = lifetime_ref.kind { self.regions.insert(def_id); } } @@ -2453,7 +2453,7 @@ fn is_late_bound_map( impl<'tcx> Visitor<'tcx> for AllCollector { fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) { - if let hir::LifetimeName::Param(def_id) = lifetime_ref.res { + if let hir::LifetimeKind::Param(def_id) = lifetime_ref.kind { self.regions.insert(def_id); } } diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs index 2e39beed8ae3c..88f745892048c 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs @@ -415,7 +415,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { self.lower_lifetime(lifetime, RegionInferReason::ExplicitObjectLifetime) } else { let reason = - if let hir::LifetimeName::ImplicitObjectLifetimeDefault = lifetime.res { + if let hir::LifetimeKind::ImplicitObjectLifetimeDefault = lifetime.kind { if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::Ref(parent_lifetime, _), .. diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index 09db6eee2c9ec..fbb57b8df6bbc 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -578,8 +578,8 @@ impl<'v> hir::intravisit::Visitor<'v> for TraitObjectVisitor<'v> { match ty.kind { hir::TyKind::TraitObject(_, tagged_ptr) if let hir::Lifetime { - res: - hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Static, + kind: + hir::LifetimeKind::ImplicitObjectLifetimeDefault | hir::LifetimeKind::Static, .. } = tagged_ptr.pointer() => { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs index 3559c660ee275..eaa06d8e8b0ae 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs @@ -6,7 +6,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{Visitor, VisitorExt, walk_ty}; use rustc_hir::{ self as hir, AmbigArg, GenericBound, GenericParam, GenericParamKind, Item, ItemKind, Lifetime, - LifetimeName, LifetimeParamKind, MissingLifetimeKind, Node, TyKind, + LifetimeKind, LifetimeParamKind, MissingLifetimeKind, Node, TyKind, }; use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor}; use rustc_span::def_id::LocalDefId; @@ -165,7 +165,7 @@ pub fn suggest_new_region_bound( if let Some(span) = opaque.bounds.iter().find_map(|arg| match arg { GenericBound::Outlives(Lifetime { - res: LifetimeName::Static, ident, .. + kind: LifetimeKind::Static, ident, .. }) => Some(ident.span), _ => None, }) { @@ -253,7 +253,7 @@ pub fn suggest_new_region_bound( } } TyKind::TraitObject(_, lt) => { - if let LifetimeName::ImplicitObjectLifetimeDefault = lt.res { + if let LifetimeKind::ImplicitObjectLifetimeDefault = lt.kind { err.span_suggestion_verbose( fn_return.span.shrink_to_hi(), format!("{declare} the trait object {captures}, {explicit}",), @@ -414,7 +414,7 @@ pub struct HirTraitObjectVisitor<'a>(pub &'a mut Vec, pub DefId); impl<'a, 'tcx> Visitor<'tcx> for HirTraitObjectVisitor<'a> { fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) { if let TyKind::TraitObject(poly_trait_refs, lifetime_ptr) = t.kind - && let Lifetime { res: LifetimeName::ImplicitObjectLifetimeDefault, .. } = + && let Lifetime { kind: LifetimeKind::ImplicitObjectLifetimeDefault, .. } = lifetime_ptr.pointer() { for ptr in poly_trait_refs { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs index df3cce880dd48..1cf1ac5403f05 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs @@ -850,14 +850,14 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { add_lt_suggs: &mut Vec<(Span, String)>, ) -> String { struct LifetimeReplaceVisitor<'a> { - needle: hir::LifetimeName, + needle: hir::LifetimeKind, new_lt: &'a str, add_lt_suggs: &'a mut Vec<(Span, String)>, } impl<'hir> hir::intravisit::Visitor<'hir> for LifetimeReplaceVisitor<'_> { fn visit_lifetime(&mut self, lt: &'hir hir::Lifetime) { - if lt.res == self.needle { + if lt.kind == self.needle { self.add_lt_suggs.push(lt.suggestion(self.new_lt)); } } @@ -894,7 +894,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }; let mut visitor = LifetimeReplaceVisitor { - needle: hir::LifetimeName::Param(lifetime_def_id), + needle: hir::LifetimeKind::Param(lifetime_def_id), add_lt_suggs, new_lt: &new_lt, }; diff --git a/src/doc/rustc-dev-guide/src/ty.md b/src/doc/rustc-dev-guide/src/ty.md index b33d540358642..ce6cffec1adb7 100644 --- a/src/doc/rustc-dev-guide/src/ty.md +++ b/src/doc/rustc-dev-guide/src/ty.md @@ -61,11 +61,11 @@ Here is a summary: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Describe the *syntax* of a type: what the user wrote (with some desugaring). | Describe the *semantics* of a type: the meaning of what the user wrote. | | Each `rustc_hir::Ty` has its own spans corresponding to the appropriate place in the program. | Doesn’t correspond to a single place in the user’s program. | -| `rustc_hir::Ty` has generics and lifetimes; however, some of those lifetimes are special markers like [`LifetimeName::Implicit`][implicit]. | `ty::Ty` has the full type, including generics and lifetimes, even if the user left them out | +| `rustc_hir::Ty` has generics and lifetimes; however, some of those lifetimes are special markers like [`LifetimeKind::Implicit`][implicit]. | `ty::Ty` has the full type, including generics and lifetimes, even if the user left them out | | `fn foo(x: u32) → u32 { }` - Two `rustc_hir::Ty` representing each usage of `u32`, each has its own `Span`s, and `rustc_hir::Ty` doesn’t tell us that both are the same type | `fn foo(x: u32) → u32 { }` - One `ty::Ty` for all instances of `u32` throughout the program, and `ty::Ty` tells us that both usages of `u32` mean the same type. | -| `fn foo(x: &u32) -> &u32)` - Two `rustc_hir::Ty` again. Lifetimes for the references show up in the `rustc_hir::Ty`s using a special marker, [`LifetimeName::Implicit`][implicit]. | `fn foo(x: &u32) -> &u32)`- A single `ty::Ty`. The `ty::Ty` has the hidden lifetime param. | +| `fn foo(x: &u32) -> &u32)` - Two `rustc_hir::Ty` again. Lifetimes for the references show up in the `rustc_hir::Ty`s using a special marker, [`LifetimeKind::Implicit`][implicit]. | `fn foo(x: &u32) -> &u32)`- A single `ty::Ty`. The `ty::Ty` has the hidden lifetime param. | -[implicit]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir/enum.LifetimeName.html#variant.Implicit +[implicit]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir/enum.LifetimeKind.html#variant.Implicit **Order** @@ -323,4 +323,4 @@ When looking at the debug output of `Ty` or simply talking about different types - Generic parameters: `{name}/#{index}` e.g. `T/#0`, where `index` corresponds to its position in the list of generic parameters - Inference variables: `?{id}` e.g. `?x`/`?0`, where `id` identifies the inference variable - Variables from binders: `^{binder}_{index}` e.g. `^0_x`/`^0_2`, where `binder` and `index` identify which variable from which binder is being referred to -- Placeholders: `!{id}` or `!{id}_{universe}` e.g. `!x`/`!0`/`!x_2`/`!0_2`, representing some unique type in the specified universe. The universe is often elided when it is `0` \ No newline at end of file +- Placeholders: `!{id}` or `!{id}_{universe}` e.g. `!x`/`!0`/`!x_2`/`!0_2`, representing some unique type in the specified universe. The universe is often elided when it is `0` diff --git a/src/tools/clippy/clippy_lints/src/lifetimes.rs b/src/tools/clippy/clippy_lints/src/lifetimes.rs index 8d47c756fc53c..dabef18b98a90 100644 --- a/src/tools/clippy/clippy_lints/src/lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/lifetimes.rs @@ -14,7 +14,7 @@ use rustc_hir::intravisit::{ }; use rustc_hir::{ AmbigArg, BareFnTy, BodyId, FnDecl, FnSig, GenericArg, GenericArgs, GenericBound, GenericParam, GenericParamKind, - Generics, HirId, Impl, ImplItem, ImplItemKind, Item, ItemKind, Lifetime, LifetimeName, LifetimeParamKind, Node, + Generics, HirId, Impl, ImplItem, ImplItemKind, Item, ItemKind, Lifetime, LifetimeKind, LifetimeParamKind, Node, PolyTraitRef, PredicateOrigin, TraitFn, TraitItem, TraitItemKind, Ty, TyKind, WhereBoundPredicate, WherePredicate, WherePredicateKind, lang_items, }; @@ -218,7 +218,7 @@ fn check_fn_inner<'tcx>( for bound in pred.bounds { let mut visitor = RefVisitor::new(cx); walk_param_bound(&mut visitor, bound); - if visitor.lts.iter().any(|lt| matches!(lt.res, LifetimeName::Param(_))) { + if visitor.lts.iter().any(|lt| matches!(lt.kind, LifetimeKind::Param(_))) { return; } if let GenericBound::Trait(ref trait_ref) = *bound { @@ -235,7 +235,7 @@ fn check_fn_inner<'tcx>( _ => None, }); for bound in lifetimes { - if bound.res != LifetimeName::Static && !bound.is_elided() { + if bound.kind != LifetimeKind::Static && !bound.is_elided() { return; } } @@ -421,8 +421,8 @@ fn named_lifetime_occurrences(lts: &[Lifetime]) -> Vec<(LocalDefId, usize)> { } fn named_lifetime(lt: &Lifetime) -> Option { - match lt.res { - LifetimeName::Param(id) if !lt.is_anonymous() => Some(id), + match lt.kind { + LifetimeKind::Param(id) if !lt.is_anonymous() => Some(id), _ => None, } } @@ -614,7 +614,7 @@ where // for lifetimes as parameters of generics fn visit_lifetime(&mut self, lifetime: &'tcx Lifetime) { - if let LifetimeName::Param(def_id) = lifetime.res + if let LifetimeKind::Param(def_id) = lifetime.kind && let Some(usages) = self.map.get_mut(&def_id) { usages.push(Usage { @@ -826,7 +826,7 @@ fn report_elidable_lifetimes( .iter() .map(|<| cx.tcx.def_span(lt)) .chain(usages.iter().filter_map(|usage| { - if let LifetimeName::Param(def_id) = usage.res + if let LifetimeKind::Param(def_id) = usage.kind && elidable_lts.contains(&def_id) { return Some(usage.ident.span); diff --git a/src/tools/clippy/clippy_lints/src/ptr.rs b/src/tools/clippy/clippy_lints/src/ptr.rs index 50ef56db167c1..901a1634ddc88 100644 --- a/src/tools/clippy/clippy_lints/src/ptr.rs +++ b/src/tools/clippy/clippy_lints/src/ptr.rs @@ -3,7 +3,7 @@ use clippy_utils::source::SpanRangeExt; use clippy_utils::sugg::Sugg; use clippy_utils::visitors::contains_unsafe_block; use clippy_utils::{get_expr_use_or_unification_node, is_lint_allowed, path_def_id, path_to_local, std_or_core}; -use hir::LifetimeName; +use hir::LifetimeKind; use rustc_abi::ExternAbi; use rustc_errors::{Applicability, MultiSpan}; use rustc_hir::hir_id::{HirId, HirIdMap}; @@ -432,7 +432,7 @@ fn check_fn_args<'cx, 'tcx: 'cx>( } None }) { - if let LifetimeName::Param(param_def_id) = lifetime.res + if let LifetimeKind::Param(param_def_id) = lifetime.kind && !lifetime.is_anonymous() && fn_sig .output() diff --git a/src/tools/clippy/clippy_utils/src/hir_utils.rs b/src/tools/clippy/clippy_utils/src/hir_utils.rs index b813cd361ed8c..be295b59f609e 100644 --- a/src/tools/clippy/clippy_utils/src/hir_utils.rs +++ b/src/tools/clippy/clippy_utils/src/hir_utils.rs @@ -8,7 +8,7 @@ use rustc_hir::MatchSource::TryDesugar; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{ AssocItemConstraint, BinOpKind, BindingMode, Block, BodyId, Closure, ConstArg, ConstArgKind, Expr, ExprField, - ExprKind, FnRetTy, GenericArg, GenericArgs, HirId, HirIdMap, InlineAsmOperand, LetExpr, Lifetime, LifetimeName, + ExprKind, FnRetTy, GenericArg, GenericArgs, HirId, HirIdMap, InlineAsmOperand, LetExpr, Lifetime, LifetimeKind, Pat, PatExpr, PatExprKind, PatField, PatKind, Path, PathSegment, PrimTy, QPath, Stmt, StmtKind, StructTailExpr, TraitBoundModifiers, Ty, TyKind, TyPat, TyPatKind, }; @@ -483,7 +483,7 @@ impl HirEqInterExpr<'_, '_, '_> { } fn eq_lifetime(left: &Lifetime, right: &Lifetime) -> bool { - left.res == right.res + left.kind == right.kind } fn eq_pat_field(&mut self, left: &PatField<'_>, right: &PatField<'_>) -> bool { @@ -1245,8 +1245,8 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { pub fn hash_lifetime(&mut self, lifetime: &Lifetime) { lifetime.ident.name.hash(&mut self.s); - std::mem::discriminant(&lifetime.res).hash(&mut self.s); - if let LifetimeName::Param(param_id) = lifetime.res { + std::mem::discriminant(&lifetime.kind).hash(&mut self.s); + if let LifetimeKind::Param(param_id) = lifetime.kind { param_id.hash(&mut self.s); } } From c4d35635545ba9fb6d5f4a1652b4520c7da3fca0 Mon Sep 17 00:00:00 2001 From: Bastian Kersting Date: Wed, 16 Apr 2025 00:14:10 +0200 Subject: [PATCH 128/266] Also remove the no_sanitize feature for std --- library/std/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 5c381181218df..3a52b7790376c 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -312,7 +312,6 @@ #![feature(needs_panic_runtime)] #![feature(negative_impls)] #![feature(never_type)] -#![feature(no_sanitize)] #![feature(optimize_attribute)] #![feature(prelude_import)] #![feature(rustc_attrs)] From ea1b230170c36ddf95cb24a8542316df9f786e5a Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Tue, 15 Apr 2025 15:20:27 -0700 Subject: [PATCH 129/266] Update Cargo.lock for rustbook --- src/tools/rustbook/Cargo.lock | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/tools/rustbook/Cargo.lock b/src/tools/rustbook/Cargo.lock index e0939afc09bb7..c14372dd6aec4 100644 --- a/src/tools/rustbook/Cargo.lock +++ b/src/tools/rustbook/Cargo.lock @@ -951,6 +951,7 @@ dependencies = [ "once_cell", "pathdiff", "pulldown-cmark 0.10.3", + "railroad", "regex", "semver", "serde_json", @@ -1300,6 +1301,15 @@ version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" +[[package]] +name = "railroad" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ecedffc46c1b2cb04f4b80e094eae6b3f3f470a9635f1f396dd5206428f6b58" +dependencies = [ + "unicode-width", +] + [[package]] name = "rand" version = "0.8.5" From 766cd3a58320f2ec9e30573f39e377513f1a4443 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 16 Apr 2025 08:35:34 +1000 Subject: [PATCH 130/266] Remove support for `#[rustc_mir(borrowck_graphviz_format="gen_kill")]`. Because it's equivalent to `#[rustc_mir(borrowck_graphviz_format)]`. It used to be distinct, but the distinction was removed in https://github.com/rust-lang/rust/pull/76044/commits/3233fb18a891363a2da36ce69ca16fbb219c96be. --- compiler/rustc_mir_dataflow/src/framework/graphviz.rs | 2 +- compiler/rustc_span/src/symbol.rs | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs index 448fad2dc3ece..c436b8c0fb019 100644 --- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs +++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs @@ -122,7 +122,7 @@ impl RustcMirAttrs { }) } else if attr.has_name(sym::borrowck_graphviz_format) { Self::set_field(&mut ret.formatter, tcx, &attr, |s| match s { - sym::gen_kill | sym::two_phase => Ok(s), + sym::two_phase => Ok(s), _ => { tcx.dcx().emit_err(UnknownFormatter { span: attr.span() }); Err(()) diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index d1f3eb16e4e4a..2af567f2ec502 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1068,7 +1068,6 @@ symbols! { ge, gen_blocks, gen_future, - gen_kill, generator_clone, generators, generic_arg_infer, From 62882f355e50f9af3ddb84661dfad0559848a3f5 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 16 Apr 2025 08:57:15 +1000 Subject: [PATCH 131/266] Improve `borrowck_graphviz_*` documentation. In particular, `borrowck_graphviz_preflow` no longer exists. --- src/doc/rustc-dev-guide/src/compiler-debugging.md | 3 ++- tests/ui/mir-dataflow/README.md | 9 --------- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/compiler-debugging.md b/src/doc/rustc-dev-guide/src/compiler-debugging.md index 47f3976202228..102e20207792e 100644 --- a/src/doc/rustc-dev-guide/src/compiler-debugging.md +++ b/src/doc/rustc-dev-guide/src/compiler-debugging.md @@ -301,7 +301,8 @@ Right below you can find elaborate explainers on a selected few. Some compiler options for debugging specific features yield graphviz graphs - e.g. the `#[rustc_mir(borrowck_graphviz_postflow="suffix.dot")]` attribute -dumps various borrow-checker dataflow graphs. +on a function dumps various borrow-checker dataflow graphs in conjunction with +`-Zdump-mir-dataflow`. These all produce `.dot` files. To view these files, install graphviz (e.g. `apt-get install graphviz`) and then run the following commands: diff --git a/tests/ui/mir-dataflow/README.md b/tests/ui/mir-dataflow/README.md index a3ab14b23c7db..886020226d031 100644 --- a/tests/ui/mir-dataflow/README.md +++ b/tests/ui/mir-dataflow/README.md @@ -42,12 +42,3 @@ each generated output path. on *entry* to each block, as well as the gen- and kill-sets that were so-called "transfer functions" summarizing the effect of each basic block. - - * (In addition to the `borrowck_graphviz_postflow` attribute-key - noted above, there is also `borrowck_graphviz_preflow`; it has the - same interface and generates the same set of files, but it renders - the dataflow state after building the gen- and kill-sets but - *before* running the dataflow analysis itself, so each entry-set is - just the initial default state for that dataflow analysis. This is - less useful for understanding the error message output in these - tests.) From 6999305926b4199d6a33ae4f82002e72115223a8 Mon Sep 17 00:00:00 2001 From: blyxyas Date: Tue, 15 Apr 2025 19:01:35 +0200 Subject: [PATCH 132/266] Make CodeStat's type sizes a public field --- compiler/rustc_session/src/code_stats.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_session/src/code_stats.rs b/compiler/rustc_session/src/code_stats.rs index b4597ae2515d4..6b18d450e9e5e 100644 --- a/compiler/rustc_session/src/code_stats.rs +++ b/compiler/rustc_session/src/code_stats.rs @@ -72,7 +72,7 @@ pub struct TypeSizeInfo { #[derive(Default)] pub struct CodeStats { - type_sizes: Lock>, + pub type_sizes: Lock>, } impl CodeStats { From b084603c631cf4cea540a35aca0ad7b2d8599ef2 Mon Sep 17 00:00:00 2001 From: Tsukasa OI Date: Sun, 6 Apr 2025 03:36:45 +0000 Subject: [PATCH 133/266] rustc_target: RISC-V: feature addition batch 2 This commit adds unprivileged ratified extensions that are either dicoverable from the `riscv_hwprobe` syscall of the Linux kernel (as of version 6.14) plus 1 minus 3 extensions. Plus 1: * "B" This is a combination of "Zba", "Zbb" and "Zbs". Note: Although not required by the RISC-V specification, it is convenient to imply "B" from its three members (will be implemented in LLVM 21/22) but this is not yet implemented in Rust due to current implication handling. It still implies three members *from* "B". Minus 2: * "Zcf" (target_arch = "riscv32" only) This is the compression instruction subset corresponding "F". This is implied from RV32 + "C" + "F" but this complex handling is not yet supported by Rust's feature handling. * "Zcd" This is the compression instruction subset corresponding "D". This is implied from "C" + "D" but this complex handling is not yet supported by Rust's feature handling. * "Supm" Unlike regular RISC-V extensions, "Supm" and "Sspm" extensions do not provide any specific architectural features / constraints but requires *some* mechanisms to control pointer masking for the current mode. For instance, reported existence of the "Supm" extension in Linux means that `prctl` system call to control pointer masking is available and there are alternative ways to detect the existence. Notes: * Because this commit adds the "Zca" extension (an integer subset of the "C" extension), the "C" extension is modified to imply "Zca". --- compiler/rustc_target/src/target_features.rs | 12 +++++++++++- tests/ui/check-cfg/target_feature.stderr | 10 ++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index b4ec1879fed5c..aeace6a40c72e 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -491,7 +491,8 @@ const MIPS_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ // tidy-alphabetical-start ("a", Stable, &["zaamo", "zalrsc"]), - ("c", Stable, &[]), + ("b", Unstable(sym::riscv_target_feature), &["zba", "zbb", "zbs"]), + ("c", Stable, &["zca"]), ("d", Unstable(sym::riscv_target_feature), &["f"]), ("e", Unstable(sym::riscv_target_feature), &[]), ("f", Unstable(sym::riscv_target_feature), &["zicsr"]), @@ -520,17 +521,25 @@ static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("zbkc", Stable, &[]), ("zbkx", Stable, &[]), ("zbs", Stable, &[]), + ("zca", Unstable(sym::riscv_target_feature), &[]), + ("zcb", Unstable(sym::riscv_target_feature), &["zca"]), + ("zcmop", Unstable(sym::riscv_target_feature), &["zca"]), ("zdinx", Unstable(sym::riscv_target_feature), &["zfinx"]), + ("zfa", Unstable(sym::riscv_target_feature), &["f"]), ("zfh", Unstable(sym::riscv_target_feature), &["zfhmin"]), ("zfhmin", Unstable(sym::riscv_target_feature), &["f"]), ("zfinx", Unstable(sym::riscv_target_feature), &["zicsr"]), ("zhinx", Unstable(sym::riscv_target_feature), &["zhinxmin"]), ("zhinxmin", Unstable(sym::riscv_target_feature), &["zfinx"]), + ("zicboz", Unstable(sym::riscv_target_feature), &[]), ("zicntr", Unstable(sym::riscv_target_feature), &["zicsr"]), + ("zicond", Unstable(sym::riscv_target_feature), &[]), ("zicsr", Unstable(sym::riscv_target_feature), &[]), ("zifencei", Unstable(sym::riscv_target_feature), &[]), + ("zihintntl", Unstable(sym::riscv_target_feature), &[]), ("zihintpause", Unstable(sym::riscv_target_feature), &[]), ("zihpm", Unstable(sym::riscv_target_feature), &["zicsr"]), + ("zimop", Unstable(sym::riscv_target_feature), &[]), ("zk", Stable, &["zkn", "zkr", "zkt"]), ("zkn", Stable, &["zbkb", "zbkc", "zbkx", "zkne", "zknd", "zknh"]), ("zknd", Stable, &[]), @@ -541,6 +550,7 @@ static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("zksed", Stable, &[]), ("zksh", Stable, &[]), ("zkt", Stable, &[]), + ("ztso", Unstable(sym::riscv_target_feature), &[]), ("zvbb", Unstable(sym::riscv_target_feature), &["zvkb"]), ("zvbc", Unstable(sym::riscv_target_feature), &["zve64x"]), ("zve32f", Unstable(sym::riscv_target_feature), &["zve32x", "f"]), diff --git a/tests/ui/check-cfg/target_feature.stderr b/tests/ui/check-cfg/target_feature.stderr index aa5fd09c0c7bb..4f7b8345e86ad 100644 --- a/tests/ui/check-cfg/target_feature.stderr +++ b/tests/ui/check-cfg/target_feature.stderr @@ -49,6 +49,7 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `avxvnni` `avxvnniint16` `avxvnniint8` +`b` `backchain` `bf16` `bmi1` @@ -318,17 +319,25 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `zbkc` `zbkx` `zbs` +`zca` +`zcb` +`zcmop` `zdinx` +`zfa` `zfh` `zfhmin` `zfinx` `zhinx` `zhinxmin` +`zicboz` `zicntr` +`zicond` `zicsr` `zifencei` +`zihintntl` `zihintpause` `zihpm` +`zimop` `zk` `zkn` `zknd` @@ -339,6 +348,7 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `zksed` `zksh` `zkt` +`ztso` `zvbb` `zvbc` `zve32f` From 52392ec9e1ebc5bf794583e2b2b146367d36b663 Mon Sep 17 00:00:00 2001 From: Tsukasa OI Date: Sun, 6 Apr 2025 04:21:01 +0000 Subject: [PATCH 134/266] rustc_target: Use "B" shorthand on the RISC-V Android target The "B" extension is ratified as a combination of three extensions: "Zba", "Zbb" and "Zbs". To maximize discoverability of the RISC-V target features, this commit makes use of the "B" extension instead of its three members. This way, `#[cfg(target_feature = "b")]` can also be used instead of: `#[cfg(all(target_feature = "zba", target_feature = "zbb", target_feature = "zbs"))]` --- compiler/rustc_target/src/spec/targets/riscv64_linux_android.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_target/src/spec/targets/riscv64_linux_android.rs b/compiler/rustc_target/src/spec/targets/riscv64_linux_android.rs index 9f02ed4bcbe9f..b9176c939f805 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64_linux_android.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64_linux_android.rs @@ -19,7 +19,7 @@ pub(crate) fn target() -> Target { options: TargetOptions { code_model: Some(CodeModel::Medium), cpu: "generic-rv64".into(), - features: "+m,+a,+f,+d,+c,+zicsr,+zifencei,+zba,+zbb,+zbs,+v".into(), + features: "+m,+a,+f,+d,+c,+b,+v,+zicsr,+zifencei".into(), llvm_abiname: "lp64d".into(), supported_sanitizers: SanitizerSet::ADDRESS, max_atomic_width: Some(64), From 8c50f95cf088c6ccf882a152bd46c090efa3a1c7 Mon Sep 17 00:00:00 2001 From: Will Glynn Date: Fri, 4 Apr 2025 17:46:35 -0500 Subject: [PATCH 135/266] rustdoc: Output target feature information `#[target_feature]` attributes refer to a target-specific list of features. Enabling certain features can imply enabling other features. Certain features are always enabled on certain targets, since they are required by the target's ABI. Features can also be enabled indirectly based on other compiler flags. Feature information is ultimately known to `rustc`. Rather than force external tools to track it -- which may be wildly impractical due to `-C target-cpu` -- have `rustdoc` output `rustc`'s feature data. --- src/librustdoc/json/mod.rs | 60 +++++++++++++++++++ src/rustdoc-json-types/lib.rs | 58 +++++++++++++++++- src/tools/compiletest/src/directive-list.rs | 3 + src/tools/jsondocck/src/main.rs | 2 +- src/tools/jsondoclint/src/validator/tests.rs | 4 ++ .../targets/aarch64_apple_darwin.rs | 14 +++++ .../aarch64_reflects_compiler_options.rs | 10 ++++ .../targets/aarch64_unknown_linux_gnu.rs | 14 +++++ .../targets/i686_pc_windows_msvc.rs | 14 +++++ .../targets/i686_unknown_linux_gnu.rs | 14 +++++ .../targets/x86_64_apple_darwin.rs | 14 +++++ .../targets/x86_64_pc_windows_gnu.rs | 14 +++++ .../targets/x86_64_pc_windows_msvc.rs | 14 +++++ .../x86_64_reflects_compiler_options.rs | 10 ++++ .../targets/x86_64_unknown_linux_gnu.rs | 14 +++++ 15 files changed, 257 insertions(+), 2 deletions(-) create mode 100644 tests/rustdoc-json/targets/aarch64_apple_darwin.rs create mode 100644 tests/rustdoc-json/targets/aarch64_reflects_compiler_options.rs create mode 100644 tests/rustdoc-json/targets/aarch64_unknown_linux_gnu.rs create mode 100644 tests/rustdoc-json/targets/i686_pc_windows_msvc.rs create mode 100644 tests/rustdoc-json/targets/i686_unknown_linux_gnu.rs create mode 100644 tests/rustdoc-json/targets/x86_64_apple_darwin.rs create mode 100644 tests/rustdoc-json/targets/x86_64_pc_windows_gnu.rs create mode 100644 tests/rustdoc-json/targets/x86_64_pc_windows_msvc.rs create mode 100644 tests/rustdoc-json/targets/x86_64_reflects_compiler_options.rs create mode 100644 tests/rustdoc-json/targets/x86_64_unknown_linux_gnu.rs diff --git a/src/librustdoc/json/mod.rs b/src/librustdoc/json/mod.rs index ba27eed7c1136..131a12ce228f7 100644 --- a/src/librustdoc/json/mod.rs +++ b/src/librustdoc/json/mod.rs @@ -14,6 +14,7 @@ use std::io::{BufWriter, Write, stdout}; use std::path::PathBuf; use std::rc::Rc; +use rustc_data_structures::fx::FxHashSet; use rustc_hir::def_id::{DefId, DefIdSet}; use rustc_middle::ty::TyCtxt; use rustc_session::Session; @@ -123,6 +124,58 @@ impl<'tcx> JsonRenderer<'tcx> { } } +fn target(sess: &rustc_session::Session) -> types::Target { + // Build a set of which features are enabled on this target + let globally_enabled_features: FxHashSet<&str> = + sess.unstable_target_features.iter().map(|name| name.as_str()).collect(); + + // Build a map of target feature stability by feature name + use rustc_target::target_features::Stability; + let feature_stability: FxHashMap<&str, Stability> = sess + .target + .rust_target_features() + .into_iter() + .copied() + .map(|(name, stability, _)| (name, stability)) + .collect(); + + types::Target { + triple: sess.opts.target_triple.tuple().into(), + target_features: sess + .target + .rust_target_features() + .into_iter() + .copied() + .filter(|(_, stability, _)| { + // Describe only target features which the user can toggle + stability.toggle_allowed().is_ok() + }) + .map(|(name, stability, implied_features)| { + types::TargetFeature { + name: name.into(), + unstable_feature_gate: match stability { + Stability::Unstable(feature_gate) => Some(feature_gate.as_str().into()), + _ => None, + }, + implies_features: implied_features + .into_iter() + .copied() + .filter(|name| { + // Imply only target features which the user can toggle + feature_stability + .get(name) + .map(|stability| stability.toggle_allowed().is_ok()) + .unwrap_or(false) + }) + .map(String::from) + .collect(), + globally_enabled: globally_enabled_features.contains(name), + } + }) + .collect(), + } +} + impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> { fn descr() -> &'static str { "json" @@ -248,6 +301,12 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> { let e = ExternalCrate { crate_num: LOCAL_CRATE }; let index = (*self.index).clone().into_inner(); + // Note that tcx.rust_target_features is inappropriate here because rustdoc tries to run for + // multiple targets: https://github.com/rust-lang/rust/pull/137632 + // + // We want to describe a single target, so pass tcx.sess rather than tcx. + let target = target(self.tcx.sess); + debug!("Constructing Output"); let output_crate = types::Crate { root: self.id_from_item_default(e.def_id().into()), @@ -288,6 +347,7 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> { ) }) .collect(), + target, format_version: types::FORMAT_VERSION, }; if let Some(ref out_dir) = self.out_dir { diff --git a/src/rustdoc-json-types/lib.rs b/src/rustdoc-json-types/lib.rs index 137fe4c4c3544..7247950545ad5 100644 --- a/src/rustdoc-json-types/lib.rs +++ b/src/rustdoc-json-types/lib.rs @@ -30,7 +30,7 @@ pub type FxHashMap = HashMap; // re-export for use in src/librustdoc /// This integer is incremented with every breaking change to the API, /// and is returned along with the JSON blob as [`Crate::format_version`]. /// Consuming code should assert that this value matches the format version(s) that it supports. -pub const FORMAT_VERSION: u32 = 43; +pub const FORMAT_VERSION: u32 = 44; /// The root of the emitted JSON blob. /// @@ -52,11 +52,67 @@ pub struct Crate { pub paths: HashMap, /// Maps `crate_id` of items to a crate name and html_root_url if it exists. pub external_crates: HashMap, + /// Information about the target for which this documentation was generated + pub target: Target, /// A single version number to be used in the future when making backwards incompatible changes /// to the JSON output. pub format_version: u32, } +/// Information about a target +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Target { + /// The target triple for which this documentation was generated + pub triple: String, + /// A list of features valid for use in `#[target_feature]` attributes + /// for the target where this rustdoc JSON was generated. + pub target_features: Vec, +} + +/// Information about a target feature. +/// +/// Rust target features are used to influence code generation, especially around selecting +/// instructions which are not universally supported by the target architecture. +/// +/// Target features are commonly enabled by the [`#[target_feature]` attribute][1] to influence code +/// generation for a particular function, and less commonly enabled by compiler options like +/// `-Ctarget-feature` or `-Ctarget-cpu`. Targets themselves automatically enable certain target +/// features by default, for example because the target's ABI specification requires saving specific +/// registers which only exist in an architectural extension. +/// +/// Target features can imply other target features: for example, x86-64 `avx2` implies `avx`, and +/// aarch64 `sve2` implies `sve`, since both of these architectural extensions depend on their +/// predecessors. +/// +/// Target features can be probed at compile time by [`#[cfg(target_feature)]`][2] or `cfg!(…)` +/// conditional compilation to determine whether a target feature is enabled in a particular +/// context. +/// +/// [1]: https://doc.rust-lang.org/stable/reference/attributes/codegen.html#the-target_feature-attribute +/// [2]: https://doc.rust-lang.org/reference/conditional-compilation.html#target_feature +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TargetFeature { + /// The name of this target feature. + pub name: String, + /// Other target features which are implied by this target feature, if any. + pub implies_features: Vec, + /// If this target feature is unstable, the name of the associated language feature gate. + pub unstable_feature_gate: Option, + /// Whether this feature is globally enabled for this compilation session. + /// + /// Target features can be globally enabled implicitly as a result of the target's definition. + /// For example, x86-64 hardware floating point ABIs require saving x87 and SSE2 registers, + /// which in turn requires globally enabling the `x87` and `sse2` target features so that the + /// generated machine code conforms to the target's ABI. + /// + /// Target features can also be globally enabled explicitly as a result of compiler flags like + /// [`-Ctarget-feature`][1] or [`-Ctarget-cpu`][2]. + /// + /// [1]: https://doc.rust-lang.org/beta/rustc/codegen-options/index.html#target-feature + /// [2]: https://doc.rust-lang.org/beta/rustc/codegen-options/index.html#target-cpu + pub globally_enabled: bool, +} + /// Metadata of a crate, either the same crate on which `rustdoc` was invoked, or its dependency. #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct ExternalCrate { diff --git a/src/tools/compiletest/src/directive-list.rs b/src/tools/compiletest/src/directive-list.rs index 44d9c0330f76e..f8b92f11bdee4 100644 --- a/src/tools/compiletest/src/directive-list.rs +++ b/src/tools/compiletest/src/directive-list.rs @@ -176,6 +176,7 @@ const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "only-32bit", "only-64bit", "only-aarch64", + "only-aarch64-apple-darwin", "only-aarch64-unknown-linux-gnu", "only-apple", "only-arm", @@ -189,6 +190,7 @@ const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "only-gnu", "only-i686-pc-windows-gnu", "only-i686-pc-windows-msvc", + "only-i686-unknown-linux-gnu", "only-ios", "only-linux", "only-loongarch64", @@ -220,6 +222,7 @@ const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "only-windows-msvc", "only-x86", "only-x86_64", + "only-x86_64-apple-darwin", "only-x86_64-fortanix-unknown-sgx", "only-x86_64-pc-windows-gnu", "only-x86_64-pc-windows-msvc", diff --git a/src/tools/jsondocck/src/main.rs b/src/tools/jsondocck/src/main.rs index 54249fbd9ae71..79e419884c68e 100644 --- a/src/tools/jsondocck/src/main.rs +++ b/src/tools/jsondocck/src/main.rs @@ -156,7 +156,7 @@ static LINE_PATTERN: LazyLock = LazyLock::new(|| { r#" //@\s+ (?P!?) - (?P[A-Za-z]+(?:-[A-Za-z]+)*) + (?P[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*) (?P.*)$ "#, ) diff --git a/src/tools/jsondoclint/src/validator/tests.rs b/src/tools/jsondoclint/src/validator/tests.rs index 28deb7e7ceef6..dd0b4ac5601a7 100644 --- a/src/tools/jsondoclint/src/validator/tests.rs +++ b/src/tools/jsondoclint/src/validator/tests.rs @@ -42,6 +42,7 @@ fn errors_on_missing_links() { )]), paths: FxHashMap::default(), external_crates: FxHashMap::default(), + target: rustdoc_json_types::Target { triple: "".to_string(), target_features: vec![] }, format_version: rustdoc_json_types::FORMAT_VERSION, }; @@ -112,6 +113,7 @@ fn errors_on_local_in_paths_and_not_index() { }, )]), external_crates: FxHashMap::default(), + target: rustdoc_json_types::Target { triple: "".to_string(), target_features: vec![] }, format_version: rustdoc_json_types::FORMAT_VERSION, }; @@ -216,6 +218,7 @@ fn errors_on_missing_path() { ItemSummary { crate_id: 0, path: vec!["foo".to_owned()], kind: ItemKind::Module }, )]), external_crates: FxHashMap::default(), + target: rustdoc_json_types::Target { triple: "".to_string(), target_features: vec![] }, format_version: rustdoc_json_types::FORMAT_VERSION, }; @@ -259,6 +262,7 @@ fn checks_local_crate_id_is_correct() { )]), paths: FxHashMap::default(), external_crates: FxHashMap::default(), + target: rustdoc_json_types::Target { triple: "".to_string(), target_features: vec![] }, format_version: FORMAT_VERSION, }; check(&krate, &[]); diff --git a/tests/rustdoc-json/targets/aarch64_apple_darwin.rs b/tests/rustdoc-json/targets/aarch64_apple_darwin.rs new file mode 100644 index 0000000000000..c6ae5517d4767 --- /dev/null +++ b/tests/rustdoc-json/targets/aarch64_apple_darwin.rs @@ -0,0 +1,14 @@ +//@ only-aarch64-apple-darwin + +//@ is "$.target.triple" \"aarch64-apple-darwin\" +//@ is "$.target.target_features[?(@.name=='vh')].globally_enabled" true +//@ is "$.target.target_features[?(@.name=='sve')].globally_enabled" false +//@ has "$.target.target_features[?(@.name=='sve2')].implies_features" '["sve"]' +//@ is "$.target.target_features[?(@.name=='sve2')].unstable_feature_gate" null + +// If this breaks due to stabilization, check rustc_target::target_features for a replacement +//@ is "$.target.target_features[?(@.name=='cssc')].unstable_feature_gate" '"aarch64_unstable_target_feature"' +//@ is "$.target.target_features[?(@.name=='v9a')].unstable_feature_gate" '"aarch64_ver_target_feature"' + +// Ensure we don't look like x86-64 +//@ !has "$.target.target_features[?(@.name=='avx2')]" diff --git a/tests/rustdoc-json/targets/aarch64_reflects_compiler_options.rs b/tests/rustdoc-json/targets/aarch64_reflects_compiler_options.rs new file mode 100644 index 0000000000000..f91221eb23c65 --- /dev/null +++ b/tests/rustdoc-json/targets/aarch64_reflects_compiler_options.rs @@ -0,0 +1,10 @@ +//@ only-aarch64 + +// If we enable SVE Bit Permute, we should see that it is enabled +//@ compile-flags: -Ctarget-feature=+sve2-bitperm +//@ is "$.target.target_features[?(@.name=='sve2-bitperm')].globally_enabled" true + +// As well as its dependency chain +//@ is "$.target.target_features[?(@.name=='sve2')].globally_enabled" true +//@ is "$.target.target_features[?(@.name=='sve')].globally_enabled" true +//@ is "$.target.target_features[?(@.name=='neon')].globally_enabled" true diff --git a/tests/rustdoc-json/targets/aarch64_unknown_linux_gnu.rs b/tests/rustdoc-json/targets/aarch64_unknown_linux_gnu.rs new file mode 100644 index 0000000000000..9139b00a12857 --- /dev/null +++ b/tests/rustdoc-json/targets/aarch64_unknown_linux_gnu.rs @@ -0,0 +1,14 @@ +//@ only-aarch64-unknown-linux-gnu + +//@ is "$.target.triple" \"aarch64-unknown-linux-gnu\" +//@ is "$.target.target_features[?(@.name=='neon')].globally_enabled" true +//@ is "$.target.target_features[?(@.name=='sve')].globally_enabled" false +//@ has "$.target.target_features[?(@.name=='sve2')].implies_features" '["sve"]' +//@ is "$.target.target_features[?(@.name=='sve2')].unstable_feature_gate" null + +// If this breaks due to stabilization, check rustc_target::target_features for a replacement +//@ is "$.target.target_features[?(@.name=='cssc')].unstable_feature_gate" '"aarch64_unstable_target_feature"' +//@ is "$.target.target_features[?(@.name=='v9a')].unstable_feature_gate" '"aarch64_ver_target_feature"' + +// Ensure we don't look like x86-64 +//@ !has "$.target.target_features[?(@.name=='avx2')]" diff --git a/tests/rustdoc-json/targets/i686_pc_windows_msvc.rs b/tests/rustdoc-json/targets/i686_pc_windows_msvc.rs new file mode 100644 index 0000000000000..088c741d11382 --- /dev/null +++ b/tests/rustdoc-json/targets/i686_pc_windows_msvc.rs @@ -0,0 +1,14 @@ +//@ only-i686-pc-windows-msvc + +//@ is "$.target.triple" \"i686-pc-windows-msvc\" +//@ is "$.target.target_features[?(@.name=='sse2')].globally_enabled" true +//@ is "$.target.target_features[?(@.name=='avx2')].globally_enabled" false +//@ has "$.target.target_features[?(@.name=='avx2')].implies_features" '["avx"]' +//@ is "$.target.target_features[?(@.name=='avx2')].unstable_feature_gate" null + +// If this breaks due to stabilization, check rustc_target::target_features for a replacement +//@ is "$.target.target_features[?(@.name=='amx-tile')].unstable_feature_gate" '"x86_amx_intrinsics"' +//@ is "$.target.target_features[?(@.name=='x87')].unstable_feature_gate" '"x87_target_feature"' + +// Ensure we don't look like aarch64 +//@ !has "$.target.target_features[?(@.name=='sve2')]" diff --git a/tests/rustdoc-json/targets/i686_unknown_linux_gnu.rs b/tests/rustdoc-json/targets/i686_unknown_linux_gnu.rs new file mode 100644 index 0000000000000..03788b000f12c --- /dev/null +++ b/tests/rustdoc-json/targets/i686_unknown_linux_gnu.rs @@ -0,0 +1,14 @@ +//@ only-i686-unknown-linux-gnu + +//@ is "$.target.triple" \"i686-unknown-linux-gnu\" +//@ is "$.target.target_features[?(@.name=='sse2')].globally_enabled" true +//@ is "$.target.target_features[?(@.name=='avx2')].globally_enabled" false +//@ has "$.target.target_features[?(@.name=='avx2')].implies_features" '["avx"]' +//@ is "$.target.target_features[?(@.name=='avx2')].unstable_feature_gate" null + +// If this breaks due to stabilization, check rustc_target::target_features for a replacement +//@ is "$.target.target_features[?(@.name=='amx-tile')].unstable_feature_gate" '"x86_amx_intrinsics"' +//@ is "$.target.target_features[?(@.name=='x87')].unstable_feature_gate" '"x87_target_feature"' + +// Ensure we don't look like aarch64 +//@ !has "$.target.target_features[?(@.name=='sve2')]" diff --git a/tests/rustdoc-json/targets/x86_64_apple_darwin.rs b/tests/rustdoc-json/targets/x86_64_apple_darwin.rs new file mode 100644 index 0000000000000..a46f9138e8678 --- /dev/null +++ b/tests/rustdoc-json/targets/x86_64_apple_darwin.rs @@ -0,0 +1,14 @@ +//@ only-x86_64-apple-darwin + +//@ is "$.target.triple" \"x86_64-apple-darwin\" +//@ is "$.target.target_features[?(@.name=='sse2')].globally_enabled" true +//@ is "$.target.target_features[?(@.name=='avx2')].globally_enabled" false +//@ has "$.target.target_features[?(@.name=='avx2')].implies_features" '["avx"]' +//@ is "$.target.target_features[?(@.name=='avx2')].unstable_feature_gate" null + +// If this breaks due to stabilization, check rustc_target::target_features for a replacement +//@ is "$.target.target_features[?(@.name=='amx-tile')].unstable_feature_gate" '"x86_amx_intrinsics"' +//@ is "$.target.target_features[?(@.name=='x87')].unstable_feature_gate" '"x87_target_feature"' + +// Ensure we don't look like aarch64 +//@ !has "$.target.target_features[?(@.name=='sve2')]" diff --git a/tests/rustdoc-json/targets/x86_64_pc_windows_gnu.rs b/tests/rustdoc-json/targets/x86_64_pc_windows_gnu.rs new file mode 100644 index 0000000000000..7da12eb4d5809 --- /dev/null +++ b/tests/rustdoc-json/targets/x86_64_pc_windows_gnu.rs @@ -0,0 +1,14 @@ +//@ only-x86_64-pc-windows-gnu + +//@ is "$.target.triple" \"x86_64-pc-windows-gnu\" +//@ is "$.target.target_features[?(@.name=='sse2')].globally_enabled" true +//@ is "$.target.target_features[?(@.name=='avx2')].globally_enabled" false +//@ has "$.target.target_features[?(@.name=='avx2')].implies_features" '["avx"]' +//@ is "$.target.target_features[?(@.name=='avx2')].unstable_feature_gate" null + +// If this breaks due to stabilization, check rustc_target::target_features for a replacement +//@ is "$.target.target_features[?(@.name=='amx-tile')].unstable_feature_gate" '"x86_amx_intrinsics"' +//@ is "$.target.target_features[?(@.name=='x87')].unstable_feature_gate" '"x87_target_feature"' + +// Ensure we don't look like aarch64 +//@ !has "$.target.target_features[?(@.name=='sve2')]" diff --git a/tests/rustdoc-json/targets/x86_64_pc_windows_msvc.rs b/tests/rustdoc-json/targets/x86_64_pc_windows_msvc.rs new file mode 100644 index 0000000000000..d55f5776e85e9 --- /dev/null +++ b/tests/rustdoc-json/targets/x86_64_pc_windows_msvc.rs @@ -0,0 +1,14 @@ +//@ only-x86_64-pc-windows-msvc + +//@ is "$.target.triple" \"x86_64-pc-windows-msvc\" +//@ is "$.target.target_features[?(@.name=='sse2')].globally_enabled" true +//@ is "$.target.target_features[?(@.name=='avx2')].globally_enabled" false +//@ has "$.target.target_features[?(@.name=='avx2')].implies_features" '["avx"]' +//@ is "$.target.target_features[?(@.name=='avx2')].unstable_feature_gate" null + +// If this breaks due to stabilization, check rustc_target::target_features for a replacement +//@ is "$.target.target_features[?(@.name=='amx-tile')].unstable_feature_gate" '"x86_amx_intrinsics"' +//@ is "$.target.target_features[?(@.name=='x87')].unstable_feature_gate" '"x87_target_feature"' + +// Ensure we don't look like aarch64 +//@ !has "$.target.target_features[?(@.name=='sve2')]" diff --git a/tests/rustdoc-json/targets/x86_64_reflects_compiler_options.rs b/tests/rustdoc-json/targets/x86_64_reflects_compiler_options.rs new file mode 100644 index 0000000000000..ba029b0999638 --- /dev/null +++ b/tests/rustdoc-json/targets/x86_64_reflects_compiler_options.rs @@ -0,0 +1,10 @@ +//@ only-x86_64 + +// If we enable AVX2, we should see that it is enabled +//@ compile-flags: -Ctarget-feature=+avx2 +//@ is "$.target.target_features[?(@.name=='avx2')].globally_enabled" true + +// As well as its dependency chain +//@ is "$.target.target_features[?(@.name=='avx')].globally_enabled" true +//@ is "$.target.target_features[?(@.name=='sse4.2')].globally_enabled" true +//@ is "$.target.target_features[?(@.name=='sse4.1')].globally_enabled" true diff --git a/tests/rustdoc-json/targets/x86_64_unknown_linux_gnu.rs b/tests/rustdoc-json/targets/x86_64_unknown_linux_gnu.rs new file mode 100644 index 0000000000000..3372fe7eb9dd5 --- /dev/null +++ b/tests/rustdoc-json/targets/x86_64_unknown_linux_gnu.rs @@ -0,0 +1,14 @@ +//@ only-x86_64-unknown-linux-gnu + +//@ is "$.target.triple" \"x86_64-unknown-linux-gnu\" +//@ is "$.target.target_features[?(@.name=='sse2')].globally_enabled" true +//@ is "$.target.target_features[?(@.name=='avx2')].globally_enabled" false +//@ has "$.target.target_features[?(@.name=='avx2')].implies_features" '["avx"]' +//@ is "$.target.target_features[?(@.name=='avx2')].unstable_feature_gate" null + +// If this breaks due to stabilization, check rustc_target::target_features for a replacement +//@ is "$.target.target_features[?(@.name=='amx-tile')].unstable_feature_gate" '"x86_amx_intrinsics"' +//@ is "$.target.target_features[?(@.name=='x87')].unstable_feature_gate" '"x87_target_feature"' + +// Ensure we don't look like aarch64 +//@ !has "$.target.target_features[?(@.name=='sve2')]" From 9dbd2bb85cd0de44b4cec80c17b5c767e960553d Mon Sep 17 00:00:00 2001 From: Christian Poveda Date: Tue, 15 Apr 2025 22:18:10 -0500 Subject: [PATCH 136/266] Include optional dso_local marker for functions in `enum-match.rs` --- tests/codegen/enum/enum-match.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/codegen/enum/enum-match.rs b/tests/codegen/enum/enum-match.rs index 6e185cf89329c..6da6ad1f078d3 100644 --- a/tests/codegen/enum/enum-match.rs +++ b/tests/codegen/enum/enum-match.rs @@ -15,7 +15,7 @@ pub enum Enum0 { B, } -// CHECK-LABEL: define noundef{{( range\(i8 [0-9]+, [0-9]+\))?}} i8 @match0(i8{{.+}}%0) +// CHECK-LABEL: define{{( dso_local)?}} noundef{{( range\(i8 [0-9]+, [0-9]+\))?}} i8 @match0(i8{{.+}}%0) // CHECK-NEXT: start: // CHECK-NEXT: %[[IS_B:.+]] = icmp eq i8 %0, 2 // CHECK-NEXT: %[[TRUNC:.+]] = and i8 %0, 1 @@ -37,7 +37,7 @@ pub enum Enum1 { C, } -// CHECK-LABEL: define noundef{{( range\(i8 [0-9]+, [0-9]+\))?}} i8 @match1(i8{{.+}}%0) +// CHECK-LABEL: define{{( dso_local)?}} noundef{{( range\(i8 [0-9]+, [0-9]+\))?}} i8 @match1(i8{{.+}}%0) // CHECK-NEXT: start: // CHECK-NEXT: %[[REL_VAR:.+]] = add{{( nsw)?}} i8 %0, -2 // CHECK-NEXT: %[[REL_VAR_WIDE:.+]] = zext i8 %[[REL_VAR]] to i64 @@ -98,7 +98,7 @@ pub enum Enum2 { E, } -// CHECK-LABEL: define noundef{{( range\(i8 [0-9]+, [0-9]+\))?}} i8 @match2(i8{{.+}}%0) +// CHECK-LABEL: define{{( dso_local)?}} noundef{{( range\(i8 [0-9]+, [0-9]+\))?}} i8 @match2(i8{{.+}}%0) // CHECK-NEXT: start: // CHECK-NEXT: %[[REL_VAR:.+]] = add i8 %0, 2 // CHECK-NEXT: %[[REL_VAR_WIDE:.+]] = zext i8 %[[REL_VAR]] to i64 @@ -121,7 +121,7 @@ pub fn match2(e: Enum2) -> u8 { // And make sure it works even if the niched scalar is a pointer. // (For example, that we don't try to `sub` on pointers.) -// CHECK-LABEL: define noundef{{( range\(i16 -?[0-9]+, -?[0-9]+\))?}} i16 @match3(ptr{{.+}}%0) +// CHECK-LABEL: define{{( dso_local)?}} noundef{{( range\(i16 -?[0-9]+, -?[0-9]+\))?}} i16 @match3(ptr{{.+}}%0) // CHECK-NEXT: start: // CHECK-NEXT: %[[IS_NULL:.+]] = icmp eq ptr %0, null // CHECK-NEXT: br i1 %[[IS_NULL]] @@ -145,7 +145,7 @@ pub enum MiddleNiche { E, } -// CHECK-LABEL: define noundef{{( range\(i8 -?[0-9]+, -?[0-9]+\))?}} i8 @match4(i8{{.+}}%0) +// CHECK-LABEL: define{{( dso_local)?}} noundef{{( range\(i8 -?[0-9]+, -?[0-9]+\))?}} i8 @match4(i8{{.+}}%0) // CHECK-NEXT: start: // CHECK-NEXT: %[[REL_VAR:.+]] = add{{( nsw)?}} i8 %0, -2 // CHECK-NEXT: %[[IS_NICHE:.+]] = icmp ult i8 %[[REL_VAR]], 5 @@ -449,7 +449,7 @@ pub enum HugeVariantIndex { Possible259, } -// CHECK-LABEL: define noundef{{( range\(i8 [0-9]+, [0-9]+\))?}} i8 @match5(i8{{.+}}%0) +// CHECK-LABEL: define{{( dso_local)?}} noundef{{( range\(i8 [0-9]+, [0-9]+\))?}} i8 @match5(i8{{.+}}%0) // CHECK-NEXT: start: // CHECK-NEXT: %[[REL_VAR:.+]] = add{{( nsw)?}} i8 %0, -2 // CHECK-NEXT: %[[REL_VAR_WIDE:.+]] = zext i8 %[[REL_VAR]] to i64 From bd9bd388fcba2d68b9eab6ff8a051bd07bcde525 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 16 Apr 2025 08:14:36 +0200 Subject: [PATCH 137/266] Allow disabling `--llvm-shared` in opt-dist --- src/tools/opt-dist/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/opt-dist/src/main.rs b/src/tools/opt-dist/src/main.rs index ac5d294f07ed1..ff4ddbaea49b7 100644 --- a/src/tools/opt-dist/src/main.rs +++ b/src/tools/opt-dist/src/main.rs @@ -76,7 +76,7 @@ enum EnvironmentCmd { rustc_perf_checkout_dir: Option, /// Is LLVM for `rustc` built in shared library mode? - #[arg(long, default_value_t = true)] + #[arg(long, default_value_t = true, action(clap::ArgAction::Set))] llvm_shared: bool, /// Should BOLT optimization be used? If yes, host LLVM must have BOLT binaries From 6f386e7a9c5224a37e02d627c3e12bee59dee519 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 16 Apr 2025 08:15:04 +0200 Subject: [PATCH 138/266] Only delete the lld directory if it exists --- src/tools/opt-dist/src/utils/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/tools/opt-dist/src/utils/mod.rs b/src/tools/opt-dist/src/utils/mod.rs index 32d88a59af92d..fb4f14ea41aea 100644 --- a/src/tools/opt-dist/src/utils/mod.rs +++ b/src/tools/opt-dist/src/utils/mod.rs @@ -36,7 +36,9 @@ pub fn clear_llvm_files(env: &Environment) -> anyhow::Result<()> { // directories ourselves. log::info!("Clearing LLVM build files"); delete_directory(&env.build_artifacts().join("llvm"))?; - delete_directory(&env.build_artifacts().join("lld"))?; + if env.build_artifacts().join("lld").is_dir() { + delete_directory(&env.build_artifacts().join("lld"))?; + } Ok(()) } From 48e119ef5a8b46ce8db8d362a6d94668c6deb541 Mon Sep 17 00:00:00 2001 From: lcnr Date: Wed, 16 Apr 2025 10:19:14 +0200 Subject: [PATCH 139/266] stepping into impls for norm is unproductive --- .../src/solve/eval_ctxt/mod.rs | 21 +++++--- .../normalizes-to-is-not-productive-2.rs | 24 +++++++++ ...alizes-to-is-not-productive.current.stderr | 48 +++++++++++++++++ ...ormalizes-to-is-not-productive.next.stderr | 31 +++++++++++ .../cycles/normalizes-to-is-not-productive.rs | 54 +++++++++++++++++++ .../normalizes-to-is-not-productive.stderr | 31 +++++++++++ 6 files changed, 201 insertions(+), 8 deletions(-) create mode 100644 tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive-2.rs create mode 100644 tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.current.stderr create mode 100644 tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.next.stderr create mode 100644 tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.rs create mode 100644 tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.stderr diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs index 148ba02252d94..9994c85d0d0d4 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs @@ -286,18 +286,23 @@ where // fixing it may cause inference breakage or introduce ambiguity. GoalSource::Misc => PathKind::Unknown, GoalSource::NormalizeGoal(path_kind) => path_kind, - GoalSource::ImplWhereBound => { + GoalSource::ImplWhereBound => match self.current_goal_kind { // We currently only consider a cycle coinductive if it steps // into a where-clause of a coinductive trait. + CurrentGoalKind::CoinductiveTrait => PathKind::Coinductive, + // While normalizing via an impl does step into a where-clause of + // an impl, accessing the associated item immediately steps out of + // it again. This means cycles/recursive calls are not guarded + // by impls used for normalization. // + // See tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.rs + // for how this can go wrong. + CurrentGoalKind::NormalizesTo => PathKind::Inductive, // We probably want to make all traits coinductive in the future, - // so we treat cycles involving their where-clauses as ambiguous. - if let CurrentGoalKind::CoinductiveTrait = self.current_goal_kind { - PathKind::Coinductive - } else { - PathKind::Unknown - } - } + // so we treat cycles involving where-clauses of not-yet coinductive + // traits as ambiguous for now. + CurrentGoalKind::Misc => PathKind::Unknown, + }, // Relating types is always unproductive. If we were to map proof trees to // corecursive functions as explained in #136824, relating types never // introduces a constructor which could cause the recursion to be guarded. diff --git a/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive-2.rs b/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive-2.rs new file mode 100644 index 0000000000000..bb3540f9a214f --- /dev/null +++ b/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive-2.rs @@ -0,0 +1,24 @@ +//@ revisions: current next +//@ ignore-compare-mode-next-solver (explicit revisions) +//@[next] compile-flags: -Znext-solver +//@ check-pass + +// Regression test for trait-system-refactor-initiative#176. +// +// Normalizing ` as IntoIterator>::IntoIter` has two candidates +// inside of the function: +// - `impl IntoIterator for Vec` which trivially applies +// - `impl IntoIterator for I` +// - requires `Vec: Iterator` +// - where-clause requires ` as IntoIterator>::IntoIter eq Vec` +// - normalize ` as IntoIterator>::IntoIter` again, cycle +// +// We need to treat this cycle as an error to be able to use the actual impl. + +fn test() +where + as IntoIterator>::IntoIter: Iterator, +{ +} + +fn main() {} diff --git a/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.current.stderr b/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.current.stderr new file mode 100644 index 0000000000000..0a5b90f3d12bf --- /dev/null +++ b/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.current.stderr @@ -0,0 +1,48 @@ +error[E0277]: the trait bound `Foo: Bound` is not satisfied + --> $DIR/normalizes-to-is-not-productive.rs:41:1 + | +LL | / fn generic() +LL | | where +LL | | >::Assoc: Bound, + | |____________________________________^ the trait `Bound` is not implemented for `Foo` + | + = help: the trait `Bound` is implemented for `u32` +note: required for `Foo` to implement `Trait` + --> $DIR/normalizes-to-is-not-productive.rs:24:19 + | +LL | impl Trait for T { + | ----- ^^^^^^^^ ^ + | | + | unsatisfied trait bound introduced here + +error[E0277]: the trait bound `Foo: Bound` is not satisfied + --> $DIR/normalizes-to-is-not-productive.rs:41:4 + | +LL | fn generic() + | ^^^^^^^ the trait `Bound` is not implemented for `Foo` + | + = help: the trait `Bound` is implemented for `u32` +note: required for `Foo` to implement `Trait` + --> $DIR/normalizes-to-is-not-productive.rs:24:19 + | +LL | impl Trait for T { + | ----- ^^^^^^^^ ^ + | | + | unsatisfied trait bound introduced here + +error[E0277]: the trait bound `Foo: Bound` is not satisfied + --> $DIR/normalizes-to-is-not-productive.rs:48:19 + | +LL | impls_bound::(); + | ^^^ the trait `Bound` is not implemented for `Foo` + | + = help: the trait `Bound` is implemented for `u32` +note: required by a bound in `impls_bound` + --> $DIR/normalizes-to-is-not-productive.rs:28:19 + | +LL | fn impls_bound() { + | ^^^^^ required by this bound in `impls_bound` + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.next.stderr b/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.next.stderr new file mode 100644 index 0000000000000..d888fbf9db183 --- /dev/null +++ b/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.next.stderr @@ -0,0 +1,31 @@ +error[E0277]: the trait bound `Foo: Bound` is not satisfied + --> $DIR/normalizes-to-is-not-productive.rs:43:31 + | +LL | >::Assoc: Bound, + | ^^^^^ the trait `Bound` is not implemented for `Foo` + | + = help: the trait `Bound` is implemented for `u32` +note: required for `Foo` to implement `Trait` + --> $DIR/normalizes-to-is-not-productive.rs:24:19 + | +LL | impl Trait for T { + | ----- ^^^^^^^^ ^ + | | + | unsatisfied trait bound introduced here + +error[E0277]: the trait bound `Foo: Bound` is not satisfied + --> $DIR/normalizes-to-is-not-productive.rs:48:19 + | +LL | impls_bound::(); + | ^^^ the trait `Bound` is not implemented for `Foo` + | + = help: the trait `Bound` is implemented for `u32` +note: required by a bound in `impls_bound` + --> $DIR/normalizes-to-is-not-productive.rs:28:19 + | +LL | fn impls_bound() { + | ^^^^^ required by this bound in `impls_bound` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.rs b/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.rs new file mode 100644 index 0000000000000..ffbbecaf89570 --- /dev/null +++ b/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.rs @@ -0,0 +1,54 @@ +//@ ignore-compare-mode-next-solver (explicit) +//@ compile-flags: -Znext-solver + +// Make sure that stepping into impl where-clauses of `NormalizesTo` +// goals is unproductive. This must not compile, see the inline +// comments. + +trait Bound { + fn method(); +} +impl Bound for u32 { + fn method() {} +} +trait Trait { + type Assoc: Bound; +} + +struct Foo; + +impl Trait for Foo { + type Assoc = u32; +} +impl Trait for T { + type Assoc = T; +} + +fn impls_bound() { + T::method(); +} + +// The where-clause requires `Foo: Trait` to hold to be wf. +// If stepping into where-clauses during normalization is considered +// to be productive, this would be the case: +// +// - `Foo: Trait` +// - via blanket impls, requires `Foo: Bound` +// - via where-bound, requires `Foo eq >::Assoc` +// - normalize `>::Assoc` +// - via blanket impl, requires where-clause `Foo: Bound` -> cycle +fn generic() +where + >::Assoc: Bound, + //~^ ERROR the trait bound `Foo: Bound` is not satisfied +{ + // Requires proving `Foo: Bound` by normalizing + // `>::Assoc` to `Foo`. + impls_bound::(); + //~^ ERROR the trait bound `Foo: Bound` is not satisfied +} +fn main() { + // Requires proving `>::Assoc: Bound`. + // This is trivially true. + generic::(); +} diff --git a/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.stderr b/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.stderr new file mode 100644 index 0000000000000..8901805a20f5f --- /dev/null +++ b/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.stderr @@ -0,0 +1,31 @@ +error[E0277]: the trait bound `Foo: Bound` is not satisfied + --> $DIR/normalizes-to-is-not-productive.rs:42:31 + | +LL | >::Assoc: Bound, + | ^^^^^ the trait `Bound` is not implemented for `Foo` + | + = help: the trait `Bound` is implemented for `u32` +note: required for `Foo` to implement `Trait` + --> $DIR/normalizes-to-is-not-productive.rs:23:19 + | +LL | impl Trait for T { + | ----- ^^^^^^^^ ^ + | | + | unsatisfied trait bound introduced here + +error[E0277]: the trait bound `Foo: Bound` is not satisfied + --> $DIR/normalizes-to-is-not-productive.rs:47:19 + | +LL | impls_bound::(); + | ^^^ the trait `Bound` is not implemented for `Foo` + | + = help: the trait `Bound` is implemented for `u32` +note: required by a bound in `impls_bound` + --> $DIR/normalizes-to-is-not-productive.rs:27:19 + | +LL | fn impls_bound() { + | ^^^^^ required by this bound in `impls_bound` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. From 20ab952b4dd994aa6e22ff56df5314eee5ff415c Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Wed, 16 Apr 2025 10:45:03 +0200 Subject: [PATCH 140/266] Explicitly annotate edition for `unpretty=expanded` and `unpretty=hir` tests These emit prelude imports which means they are always edition dependent --- diff | 0 tests/ui/asm/unpretty-expanded.rs | 1 + tests/ui/asm/unpretty-expanded.stdout | 1 + tests/ui/codemap_tests/unicode.expanded.stdout | 1 + tests/ui/codemap_tests/unicode.normal.stderr | 2 +- tests/ui/codemap_tests/unicode.rs | 1 + tests/ui/const-generics/defaults/pretty-printing-ast.rs | 1 + .../const-generics/defaults/pretty-printing-ast.stdout | 1 + tests/ui/deriving/built-in-proc-macro-scope.rs | 1 + tests/ui/deriving/built-in-proc-macro-scope.stdout | 1 + tests/ui/deriving/deriving-coerce-pointee-expanded.rs | 1 + .../ui/deriving/deriving-coerce-pointee-expanded.stdout | 1 + tests/ui/deriving/proc-macro-attribute-mixing.rs | 1 + tests/ui/deriving/proc-macro-attribute-mixing.stdout | 1 + .../no_ice_for_partial_compiler_runs.rs | 1 + .../no_ice_for_partial_compiler_runs.stdout | 1 + tests/ui/macros/genercs-in-path-with-prettry-hir.rs | 1 + tests/ui/macros/genercs-in-path-with-prettry-hir.stderr | 2 +- tests/ui/macros/genercs-in-path-with-prettry-hir.stdout | 1 + .../non-consuming-methods-have-optimized-codegen.rs | 1 + .../non-consuming-methods-have-optimized-codegen.stdout | 1 + tests/ui/match/issue-82392.rs | 1 + tests/ui/match/issue-82392.stdout | 1 + tests/ui/proc-macro/nonterminal-token-hygiene.rs | 1 + tests/ui/proc-macro/nonterminal-token-hygiene.stdout | 9 +++++---- tests/ui/proc-macro/quote/debug.rs | 1 + tests/ui/proc-macro/quote/debug.stdout | 1 + tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.rs | 1 + .../rfcs/rfc-2497-if-let-chains/ast-pretty-check.stdout | 1 + tests/ui/type-alias-impl-trait/issue-60662.rs | 1 + tests/ui/type-alias-impl-trait/issue-60662.stdout | 1 + tests/ui/unpretty/bad-literal.rs | 1 + tests/ui/unpretty/bad-literal.stderr | 2 +- tests/ui/unpretty/bad-literal.stdout | 1 + tests/ui/unpretty/debug-fmt-hir.rs | 1 + tests/ui/unpretty/debug-fmt-hir.stdout | 1 + tests/ui/unpretty/deprecated-attr.rs | 1 + tests/ui/unpretty/deprecated-attr.stdout | 1 + tests/ui/unpretty/diagnostic-attr.rs | 1 + tests/ui/unpretty/diagnostic-attr.stdout | 1 + tests/ui/unpretty/expanded-interpolation.rs | 1 + tests/ui/unpretty/expanded-interpolation.stdout | 1 + tests/ui/unpretty/flattened-format-args.rs | 1 + tests/ui/unpretty/flattened-format-args.stdout | 1 + tests/ui/unpretty/let-else-hir.rs | 1 + tests/ui/unpretty/let-else-hir.stdout | 1 + tests/ui/unpretty/self-hir.rs | 1 + tests/ui/unpretty/self-hir.stdout | 1 + tests/ui/unpretty/unpretty-expr-fn-arg.rs | 1 + tests/ui/unpretty/unpretty-expr-fn-arg.stdout | 1 + 50 files changed, 53 insertions(+), 7 deletions(-) create mode 100644 diff diff --git a/diff b/diff new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/tests/ui/asm/unpretty-expanded.rs b/tests/ui/asm/unpretty-expanded.rs index 1da2c7704f41f..3eb46fe4889c6 100644 --- a/tests/ui/asm/unpretty-expanded.rs +++ b/tests/ui/asm/unpretty-expanded.rs @@ -1,4 +1,5 @@ //@ needs-asm-support //@ check-pass //@ compile-flags: -Zunpretty=expanded +//@ edition: 2015 core::arch::global_asm!("x: .byte 42"); diff --git a/tests/ui/asm/unpretty-expanded.stdout b/tests/ui/asm/unpretty-expanded.stdout index 80ccd127d506d..7ba1702dfed8e 100644 --- a/tests/ui/asm/unpretty-expanded.stdout +++ b/tests/ui/asm/unpretty-expanded.stdout @@ -7,4 +7,5 @@ extern crate std; //@ needs-asm-support //@ check-pass //@ compile-flags: -Zunpretty=expanded +//@ edition: 2015 global_asm! ("x: .byte 42"); diff --git a/tests/ui/codemap_tests/unicode.expanded.stdout b/tests/ui/codemap_tests/unicode.expanded.stdout index eb53d12e94f3c..c88035de0449f 100644 --- a/tests/ui/codemap_tests/unicode.expanded.stdout +++ b/tests/ui/codemap_tests/unicode.expanded.stdout @@ -7,6 +7,7 @@ extern crate std; //@ revisions: normal expanded //@[expanded] check-pass //@[expanded]compile-flags: -Zunpretty=expanded +//@ edition: 2015 extern "路濫狼á́́" fn foo() {} diff --git a/tests/ui/codemap_tests/unicode.normal.stderr b/tests/ui/codemap_tests/unicode.normal.stderr index 0f254e0246f41..10cb34f48326e 100644 --- a/tests/ui/codemap_tests/unicode.normal.stderr +++ b/tests/ui/codemap_tests/unicode.normal.stderr @@ -1,5 +1,5 @@ error[E0703]: invalid ABI: found `路濫狼á́́` - --> $DIR/unicode.rs:5:8 + --> $DIR/unicode.rs:6:8 | LL | extern "路濫狼á́́" fn foo() {} | ^^^^^^^^^ invalid ABI diff --git a/tests/ui/codemap_tests/unicode.rs b/tests/ui/codemap_tests/unicode.rs index 73023e3c669d3..4b93ef0940697 100644 --- a/tests/ui/codemap_tests/unicode.rs +++ b/tests/ui/codemap_tests/unicode.rs @@ -1,6 +1,7 @@ //@ revisions: normal expanded //@[expanded] check-pass //@[expanded]compile-flags: -Zunpretty=expanded +//@ edition: 2015 extern "路濫狼á́́" fn foo() {} //[normal]~ ERROR invalid ABI diff --git a/tests/ui/const-generics/defaults/pretty-printing-ast.rs b/tests/ui/const-generics/defaults/pretty-printing-ast.rs index 20bf900d9f3e4..f7a166d00d551 100644 --- a/tests/ui/const-generics/defaults/pretty-printing-ast.rs +++ b/tests/ui/const-generics/defaults/pretty-printing-ast.rs @@ -1,6 +1,7 @@ // Test the AST pretty printer correctly handles default values for const generics //@ check-pass //@ compile-flags: -Z unpretty=expanded +//@ edition: 2015 #![crate_type = "lib"] diff --git a/tests/ui/const-generics/defaults/pretty-printing-ast.stdout b/tests/ui/const-generics/defaults/pretty-printing-ast.stdout index f1cd1451700fa..b6cb7fa09c880 100644 --- a/tests/ui/const-generics/defaults/pretty-printing-ast.stdout +++ b/tests/ui/const-generics/defaults/pretty-printing-ast.stdout @@ -3,6 +3,7 @@ // Test the AST pretty printer correctly handles default values for const generics //@ check-pass //@ compile-flags: -Z unpretty=expanded +//@ edition: 2015 #![crate_type = "lib"] #[prelude_import] diff --git a/tests/ui/deriving/built-in-proc-macro-scope.rs b/tests/ui/deriving/built-in-proc-macro-scope.rs index e67197b7e2051..69128a08b9978 100644 --- a/tests/ui/deriving/built-in-proc-macro-scope.rs +++ b/tests/ui/deriving/built-in-proc-macro-scope.rs @@ -1,6 +1,7 @@ //@ check-pass //@ proc-macro: another-proc-macro.rs //@ compile-flags: -Zunpretty=expanded +//@ edition:2015 #![feature(derive_coerce_pointee)] diff --git a/tests/ui/deriving/built-in-proc-macro-scope.stdout b/tests/ui/deriving/built-in-proc-macro-scope.stdout index fa4e50968f4de..2697618ab0035 100644 --- a/tests/ui/deriving/built-in-proc-macro-scope.stdout +++ b/tests/ui/deriving/built-in-proc-macro-scope.stdout @@ -3,6 +3,7 @@ //@ check-pass //@ proc-macro: another-proc-macro.rs //@ compile-flags: -Zunpretty=expanded +//@ edition:2015 #![feature(derive_coerce_pointee)] #[prelude_import] diff --git a/tests/ui/deriving/deriving-coerce-pointee-expanded.rs b/tests/ui/deriving/deriving-coerce-pointee-expanded.rs index 94be7031fb77f..9394ae4efe5ae 100644 --- a/tests/ui/deriving/deriving-coerce-pointee-expanded.rs +++ b/tests/ui/deriving/deriving-coerce-pointee-expanded.rs @@ -1,5 +1,6 @@ //@ check-pass //@ compile-flags: -Zunpretty=expanded +//@ edition: 2015 #![feature(derive_coerce_pointee)] use std::marker::CoercePointee; diff --git a/tests/ui/deriving/deriving-coerce-pointee-expanded.stdout b/tests/ui/deriving/deriving-coerce-pointee-expanded.stdout index a774efbbe354b..84f8e9a3195a7 100644 --- a/tests/ui/deriving/deriving-coerce-pointee-expanded.stdout +++ b/tests/ui/deriving/deriving-coerce-pointee-expanded.stdout @@ -2,6 +2,7 @@ #![no_std] //@ check-pass //@ compile-flags: -Zunpretty=expanded +//@ edition: 2015 #![feature(derive_coerce_pointee)] #[prelude_import] use ::std::prelude::rust_2015::*; diff --git a/tests/ui/deriving/proc-macro-attribute-mixing.rs b/tests/ui/deriving/proc-macro-attribute-mixing.rs index 2c11c3f72ca59..c9e123d7e8a12 100644 --- a/tests/ui/deriving/proc-macro-attribute-mixing.rs +++ b/tests/ui/deriving/proc-macro-attribute-mixing.rs @@ -7,6 +7,7 @@ //@ check-pass //@ proc-macro: another-proc-macro.rs //@ compile-flags: -Zunpretty=expanded +//@ edition: 2015 #![feature(derive_coerce_pointee)] diff --git a/tests/ui/deriving/proc-macro-attribute-mixing.stdout b/tests/ui/deriving/proc-macro-attribute-mixing.stdout index ad743d013d25d..faa9c0218a33c 100644 --- a/tests/ui/deriving/proc-macro-attribute-mixing.stdout +++ b/tests/ui/deriving/proc-macro-attribute-mixing.stdout @@ -9,6 +9,7 @@ //@ check-pass //@ proc-macro: another-proc-macro.rs //@ compile-flags: -Zunpretty=expanded +//@ edition: 2015 #![feature(derive_coerce_pointee)] #[prelude_import] diff --git a/tests/ui/lint/rfc-2383-lint-reason/no_ice_for_partial_compiler_runs.rs b/tests/ui/lint/rfc-2383-lint-reason/no_ice_for_partial_compiler_runs.rs index 9e38b94b76ce6..11ee2bc852abb 100644 --- a/tests/ui/lint/rfc-2383-lint-reason/no_ice_for_partial_compiler_runs.rs +++ b/tests/ui/lint/rfc-2383-lint-reason/no_ice_for_partial_compiler_runs.rs @@ -1,6 +1,7 @@ // This ensures that ICEs like rust#94953 don't happen //@ check-pass //@ compile-flags: -Z unpretty=expanded +//@ edition: 2015 // This `expect` will create an expectation with an unstable expectation id #[expect(while_true)] diff --git a/tests/ui/lint/rfc-2383-lint-reason/no_ice_for_partial_compiler_runs.stdout b/tests/ui/lint/rfc-2383-lint-reason/no_ice_for_partial_compiler_runs.stdout index d804c1d2d200b..d63abea92302a 100644 --- a/tests/ui/lint/rfc-2383-lint-reason/no_ice_for_partial_compiler_runs.stdout +++ b/tests/ui/lint/rfc-2383-lint-reason/no_ice_for_partial_compiler_runs.stdout @@ -7,6 +7,7 @@ extern crate std; // This ensures that ICEs like rust#94953 don't happen //@ check-pass //@ compile-flags: -Z unpretty=expanded +//@ edition: 2015 // This `expect` will create an expectation with an unstable expectation id #[expect(while_true)] diff --git a/tests/ui/macros/genercs-in-path-with-prettry-hir.rs b/tests/ui/macros/genercs-in-path-with-prettry-hir.rs index 84370fcebbcbc..e6773f610da30 100644 --- a/tests/ui/macros/genercs-in-path-with-prettry-hir.rs +++ b/tests/ui/macros/genercs-in-path-with-prettry-hir.rs @@ -1,4 +1,5 @@ //@ compile-flags: -Zunpretty=hir +//@ edition: 2015 // issue#97006 diff --git a/tests/ui/macros/genercs-in-path-with-prettry-hir.stderr b/tests/ui/macros/genercs-in-path-with-prettry-hir.stderr index 8fcc7c6fbff06..173e77569a805 100644 --- a/tests/ui/macros/genercs-in-path-with-prettry-hir.stderr +++ b/tests/ui/macros/genercs-in-path-with-prettry-hir.stderr @@ -1,5 +1,5 @@ error: unexpected generic arguments in path - --> $DIR/genercs-in-path-with-prettry-hir.rs:12:10 + --> $DIR/genercs-in-path-with-prettry-hir.rs:13:10 | LL | m!(inline); | ^^^^ diff --git a/tests/ui/macros/genercs-in-path-with-prettry-hir.stdout b/tests/ui/macros/genercs-in-path-with-prettry-hir.stdout index e8c88d2dcdf2c..6b41eb530dbc8 100644 --- a/tests/ui/macros/genercs-in-path-with-prettry-hir.stdout +++ b/tests/ui/macros/genercs-in-path-with-prettry-hir.stdout @@ -3,6 +3,7 @@ use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; //@ compile-flags: -Zunpretty=hir +//@ edition: 2015 // issue#97006 diff --git a/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.rs b/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.rs index cf47a1e67aed8..29f71d10719b7 100644 --- a/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.rs +++ b/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.rs @@ -1,5 +1,6 @@ //@ check-pass //@ compile-flags: -Z unpretty=expanded +//@ edition: 2015 #![feature(core_intrinsics, generic_assert)] diff --git a/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.stdout b/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.stdout index 8065d0dff8fc1..9300f610f8e20 100644 --- a/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.stdout +++ b/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.stdout @@ -2,6 +2,7 @@ #![no_std] //@ check-pass //@ compile-flags: -Z unpretty=expanded +//@ edition: 2015 #![feature(core_intrinsics, generic_assert)] #[prelude_import] diff --git a/tests/ui/match/issue-82392.rs b/tests/ui/match/issue-82392.rs index 6f9527fb337ba..4ae08fed93a29 100644 --- a/tests/ui/match/issue-82392.rs +++ b/tests/ui/match/issue-82392.rs @@ -1,6 +1,7 @@ // https://github.com/rust-lang/rust/issues/82329 //@ compile-flags: -Zunpretty=hir,typed //@ check-pass +//@ edition:2015 pub fn main() { if true { diff --git a/tests/ui/match/issue-82392.stdout b/tests/ui/match/issue-82392.stdout index 8949611ac12f4..8b7edabf004ed 100644 --- a/tests/ui/match/issue-82392.stdout +++ b/tests/ui/match/issue-82392.stdout @@ -5,6 +5,7 @@ extern crate std; // https://github.com/rust-lang/rust/issues/82329 //@ compile-flags: -Zunpretty=hir,typed //@ check-pass +//@ edition:2015 fn main() ({ (if (true as bool) diff --git a/tests/ui/proc-macro/nonterminal-token-hygiene.rs b/tests/ui/proc-macro/nonterminal-token-hygiene.rs index e2aedb245d075..b7b0d1ea3dd7c 100644 --- a/tests/ui/proc-macro/nonterminal-token-hygiene.rs +++ b/tests/ui/proc-macro/nonterminal-token-hygiene.rs @@ -8,6 +8,7 @@ //@ normalize-stdout: "expn\d{3,}" -> "expnNNN" //@ normalize-stdout: "extern crate compiler_builtins /\* \d+ \*/" -> "extern crate compiler_builtins /* NNN */" //@ proc-macro: test-macros.rs +//@ edition: 2015 #![feature(decl_macro)] #![no_std] // Don't load unnecessary hygiene information from std diff --git a/tests/ui/proc-macro/nonterminal-token-hygiene.stdout b/tests/ui/proc-macro/nonterminal-token-hygiene.stdout index 6fd6cb474693b..2ebfb47d98151 100644 --- a/tests/ui/proc-macro/nonterminal-token-hygiene.stdout +++ b/tests/ui/proc-macro/nonterminal-token-hygiene.stdout @@ -5,19 +5,19 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ stream: TokenStream [ Ident { ident: "struct", - span: $DIR/nonterminal-token-hygiene.rs:32:5: 32:11 (#5), + span: $DIR/nonterminal-token-hygiene.rs:33:5: 33:11 (#5), }, Ident { ident: "S", - span: $DIR/nonterminal-token-hygiene.rs:32:12: 32:13 (#5), + span: $DIR/nonterminal-token-hygiene.rs:33:12: 33:13 (#5), }, Punct { ch: ';', spacing: Alone, - span: $DIR/nonterminal-token-hygiene.rs:32:13: 32:14 (#5), + span: $DIR/nonterminal-token-hygiene.rs:33:13: 33:14 (#5), }, ], - span: $DIR/nonterminal-token-hygiene.rs:22:27: 22:32 (#4), + span: $DIR/nonterminal-token-hygiene.rs:23:27: 23:32 (#4), }, ] #![feature /* 0#0 */(prelude_import)] @@ -32,6 +32,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ //@ normalize-stdout: "expn\d{3,}" -> "expnNNN" //@ normalize-stdout: "extern crate compiler_builtins /\* \d+ \*/" -> "extern crate compiler_builtins /* NNN */" //@ proc-macro: test-macros.rs +//@ edition: 2015 #![feature /* 0#0 */(decl_macro)] #![no_std /* 0#0 */] diff --git a/tests/ui/proc-macro/quote/debug.rs b/tests/ui/proc-macro/quote/debug.rs index ce113079e5678..ce1ef81bedaf1 100644 --- a/tests/ui/proc-macro/quote/debug.rs +++ b/tests/ui/proc-macro/quote/debug.rs @@ -3,6 +3,7 @@ //@ no-prefer-dynamic //@ compile-flags: -Z unpretty=expanded //@ needs-unwind compiling proc macros with panic=abort causes a warning +//@ edition: 2015 // // This file is not actually used as a proc-macro - instead, // it's just used to show the output of the `quote!` macro diff --git a/tests/ui/proc-macro/quote/debug.stdout b/tests/ui/proc-macro/quote/debug.stdout index 3eaad9eb96997..6ebb3a3795114 100644 --- a/tests/ui/proc-macro/quote/debug.stdout +++ b/tests/ui/proc-macro/quote/debug.stdout @@ -5,6 +5,7 @@ //@ no-prefer-dynamic //@ compile-flags: -Z unpretty=expanded //@ needs-unwind compiling proc macros with panic=abort causes a warning +//@ edition: 2015 // // This file is not actually used as a proc-macro - instead, // it's just used to show the output of the `quote!` macro diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.rs b/tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.rs index 8d78264633364..16165c4a42cce 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.rs +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.rs @@ -1,5 +1,6 @@ //@ check-pass //@ compile-flags: -Z unpretty=expanded +//@ edition: 2015 fn main() { if let 0 = 1 {} diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.stdout b/tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.stdout index 1c103f03c3547..e2e45ae94ea6e 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.stdout +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.stdout @@ -6,5 +6,6 @@ use ::std::prelude::rust_2015::*; extern crate std; //@ check-pass //@ compile-flags: -Z unpretty=expanded +//@ edition: 2015 fn main() { if let 0 = 1 {} } diff --git a/tests/ui/type-alias-impl-trait/issue-60662.rs b/tests/ui/type-alias-impl-trait/issue-60662.rs index 35d96e52fd611..7ecdd26473555 100644 --- a/tests/ui/type-alias-impl-trait/issue-60662.rs +++ b/tests/ui/type-alias-impl-trait/issue-60662.rs @@ -1,5 +1,6 @@ //@ check-pass //@ compile-flags: -Z unpretty=hir +//@ edition: 2015 #![feature(type_alias_impl_trait)] diff --git a/tests/ui/type-alias-impl-trait/issue-60662.stdout b/tests/ui/type-alias-impl-trait/issue-60662.stdout index b541cbeb2279a..56fef852e37bf 100644 --- a/tests/ui/type-alias-impl-trait/issue-60662.stdout +++ b/tests/ui/type-alias-impl-trait/issue-60662.stdout @@ -1,5 +1,6 @@ //@ check-pass //@ compile-flags: -Z unpretty=hir +//@ edition: 2015 #![feature(type_alias_impl_trait)] #[prelude_import] diff --git a/tests/ui/unpretty/bad-literal.rs b/tests/ui/unpretty/bad-literal.rs index 37377898b14f0..0ec1d7b07f1f7 100644 --- a/tests/ui/unpretty/bad-literal.rs +++ b/tests/ui/unpretty/bad-literal.rs @@ -1,5 +1,6 @@ //@ compile-flags: -Zunpretty=hir //@ check-fail +//@ edition: 2015 // In #100948 this caused an ICE with -Zunpretty=hir. fn main() { diff --git a/tests/ui/unpretty/bad-literal.stderr b/tests/ui/unpretty/bad-literal.stderr index b6259484f67d5..fd1801a87f209 100644 --- a/tests/ui/unpretty/bad-literal.stderr +++ b/tests/ui/unpretty/bad-literal.stderr @@ -1,5 +1,5 @@ error: invalid suffix `u` for number literal - --> $DIR/bad-literal.rs:6:5 + --> $DIR/bad-literal.rs:7:5 | LL | 1u; | ^^ invalid suffix `u` diff --git a/tests/ui/unpretty/bad-literal.stdout b/tests/ui/unpretty/bad-literal.stdout index c5272711d6e93..06116a4ab5534 100644 --- a/tests/ui/unpretty/bad-literal.stdout +++ b/tests/ui/unpretty/bad-literal.stdout @@ -4,6 +4,7 @@ use ::std::prelude::rust_2015::*; extern crate std; //@ compile-flags: -Zunpretty=hir //@ check-fail +//@ edition: 2015 // In #100948 this caused an ICE with -Zunpretty=hir. fn main() { diff --git a/tests/ui/unpretty/debug-fmt-hir.rs b/tests/ui/unpretty/debug-fmt-hir.rs index c19f3c4c0c57e..c79349de44424 100644 --- a/tests/ui/unpretty/debug-fmt-hir.rs +++ b/tests/ui/unpretty/debug-fmt-hir.rs @@ -1,5 +1,6 @@ //@ compile-flags: -Zunpretty=hir //@ check-pass +//@ edition: 2015 use std::fmt; diff --git a/tests/ui/unpretty/debug-fmt-hir.stdout b/tests/ui/unpretty/debug-fmt-hir.stdout index 2c9c96de9d142..dc18675ea8031 100644 --- a/tests/ui/unpretty/debug-fmt-hir.stdout +++ b/tests/ui/unpretty/debug-fmt-hir.stdout @@ -4,6 +4,7 @@ use ::std::prelude::rust_2015::*; extern crate std; //@ compile-flags: -Zunpretty=hir //@ check-pass +//@ edition: 2015 use std::fmt; diff --git a/tests/ui/unpretty/deprecated-attr.rs b/tests/ui/unpretty/deprecated-attr.rs index dda362a595e24..0c80203e9652f 100644 --- a/tests/ui/unpretty/deprecated-attr.rs +++ b/tests/ui/unpretty/deprecated-attr.rs @@ -1,5 +1,6 @@ //@ compile-flags: -Zunpretty=hir //@ check-pass +//@ edition: 2015 #[deprecated] pub struct PlainDeprecated; diff --git a/tests/ui/unpretty/deprecated-attr.stdout b/tests/ui/unpretty/deprecated-attr.stdout index 42de7b4533e51..97d863b2e943c 100644 --- a/tests/ui/unpretty/deprecated-attr.stdout +++ b/tests/ui/unpretty/deprecated-attr.stdout @@ -4,6 +4,7 @@ use ::std::prelude::rust_2015::*; extern crate std; //@ compile-flags: -Zunpretty=hir //@ check-pass +//@ edition: 2015 #[attr = Deprecation {deprecation: Deprecation {since: Unspecified}}] struct PlainDeprecated; diff --git a/tests/ui/unpretty/diagnostic-attr.rs b/tests/ui/unpretty/diagnostic-attr.rs index 27f5b693e691c..4ef85c71f90e2 100644 --- a/tests/ui/unpretty/diagnostic-attr.rs +++ b/tests/ui/unpretty/diagnostic-attr.rs @@ -1,5 +1,6 @@ //@ compile-flags: -Zunpretty=hir //@ check-pass +//@ edition: 2015 #[diagnostic::on_unimplemented( message = "My Message for `ImportantTrait<{A}>` implemented for `{Self}`", diff --git a/tests/ui/unpretty/diagnostic-attr.stdout b/tests/ui/unpretty/diagnostic-attr.stdout index e8696d04d38ab..81d71b91d8154 100644 --- a/tests/ui/unpretty/diagnostic-attr.stdout +++ b/tests/ui/unpretty/diagnostic-attr.stdout @@ -4,6 +4,7 @@ use ::std::prelude::rust_2015::*; extern crate std; //@ compile-flags: -Zunpretty=hir //@ check-pass +//@ edition: 2015 #[diagnostic::on_unimplemented(message = "My Message for `ImportantTrait<{A}>` implemented for `{Self}`", label = diff --git a/tests/ui/unpretty/expanded-interpolation.rs b/tests/ui/unpretty/expanded-interpolation.rs index 1dc72c67f511e..0c447ae669dd9 100644 --- a/tests/ui/unpretty/expanded-interpolation.rs +++ b/tests/ui/unpretty/expanded-interpolation.rs @@ -1,5 +1,6 @@ //@ compile-flags: -Zunpretty=expanded //@ check-pass +//@ edition: 2015 // This test covers the AST pretty-printer's insertion of parentheses in some // macro metavariable edge cases. Synthetic parentheses (i.e. not appearing in diff --git a/tests/ui/unpretty/expanded-interpolation.stdout b/tests/ui/unpretty/expanded-interpolation.stdout index 556e57dbd9210..10729a96ef595 100644 --- a/tests/ui/unpretty/expanded-interpolation.stdout +++ b/tests/ui/unpretty/expanded-interpolation.stdout @@ -2,6 +2,7 @@ #![no_std] //@ compile-flags: -Zunpretty=expanded //@ check-pass +//@ edition: 2015 // This test covers the AST pretty-printer's insertion of parentheses in some // macro metavariable edge cases. Synthetic parentheses (i.e. not appearing in diff --git a/tests/ui/unpretty/flattened-format-args.rs b/tests/ui/unpretty/flattened-format-args.rs index 772f44cc268ec..ab065f494dc00 100644 --- a/tests/ui/unpretty/flattened-format-args.rs +++ b/tests/ui/unpretty/flattened-format-args.rs @@ -1,5 +1,6 @@ //@ compile-flags: -Zunpretty=hir -Zflatten-format-args=yes //@ check-pass +//@ edition: 2015 fn main() { let x = 1; diff --git a/tests/ui/unpretty/flattened-format-args.stdout b/tests/ui/unpretty/flattened-format-args.stdout index 2de1cdd96b5b7..a5d943281ad8d 100644 --- a/tests/ui/unpretty/flattened-format-args.stdout +++ b/tests/ui/unpretty/flattened-format-args.stdout @@ -4,6 +4,7 @@ use ::std::prelude::rust_2015::*; extern crate std; //@ compile-flags: -Zunpretty=hir -Zflatten-format-args=yes //@ check-pass +//@ edition: 2015 fn main() { let x = 1; diff --git a/tests/ui/unpretty/let-else-hir.rs b/tests/ui/unpretty/let-else-hir.rs index 9c231189659af..786c84a09dddf 100644 --- a/tests/ui/unpretty/let-else-hir.rs +++ b/tests/ui/unpretty/let-else-hir.rs @@ -1,5 +1,6 @@ //@ compile-flags: -Zunpretty=hir //@ check-pass +//@ edition: 2015 diff --git a/tests/ui/unpretty/let-else-hir.stdout b/tests/ui/unpretty/let-else-hir.stdout index a2ffa5de5673c..a6dd943ec1b7e 100644 --- a/tests/ui/unpretty/let-else-hir.stdout +++ b/tests/ui/unpretty/let-else-hir.stdout @@ -4,6 +4,7 @@ use ::std::prelude::rust_2015::*; extern crate std; //@ compile-flags: -Zunpretty=hir //@ check-pass +//@ edition: 2015 diff --git a/tests/ui/unpretty/self-hir.rs b/tests/ui/unpretty/self-hir.rs index 448d828d4446f..70e0ba589fb8f 100644 --- a/tests/ui/unpretty/self-hir.rs +++ b/tests/ui/unpretty/self-hir.rs @@ -1,5 +1,6 @@ //@ compile-flags: -Zunpretty=hir //@ check-pass +//@ edition: 2015 pub struct Bar { a: String, diff --git a/tests/ui/unpretty/self-hir.stdout b/tests/ui/unpretty/self-hir.stdout index 4da080dc611e8..a9e80b1f59201 100644 --- a/tests/ui/unpretty/self-hir.stdout +++ b/tests/ui/unpretty/self-hir.stdout @@ -4,6 +4,7 @@ use ::std::prelude::rust_2015::*; extern crate std; //@ compile-flags: -Zunpretty=hir //@ check-pass +//@ edition: 2015 struct Bar { a: String, diff --git a/tests/ui/unpretty/unpretty-expr-fn-arg.rs b/tests/ui/unpretty/unpretty-expr-fn-arg.rs index 7f496e773c28e..b2ab2e0911e52 100644 --- a/tests/ui/unpretty/unpretty-expr-fn-arg.rs +++ b/tests/ui/unpretty/unpretty-expr-fn-arg.rs @@ -6,6 +6,7 @@ //@ check-pass //@ compile-flags: -Zunpretty=hir,typed +//@ edition: 2015 #![allow(dead_code)] fn main() {} diff --git a/tests/ui/unpretty/unpretty-expr-fn-arg.stdout b/tests/ui/unpretty/unpretty-expr-fn-arg.stdout index 43aa93c83bd31..fd2e794fcac89 100644 --- a/tests/ui/unpretty/unpretty-expr-fn-arg.stdout +++ b/tests/ui/unpretty/unpretty-expr-fn-arg.stdout @@ -6,6 +6,7 @@ //@ check-pass //@ compile-flags: -Zunpretty=hir,typed +//@ edition: 2015 #![allow(dead_code)] #[prelude_import] use ::std::prelude::rust_2015::*; From a6dcd519f325e8e3bce6b59461d6f073a9f5c18b Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Wed, 16 Apr 2025 12:16:40 +0200 Subject: [PATCH 141/266] fix multiple `#[repr(align(N))]` on functions --- .../rustc_codegen_ssa/src/codegen_attrs.rs | 3 ++- tests/codegen/align-fn.rs | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index ddb6118898334..8f23a5f21cdfa 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -114,7 +114,8 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { AttributeKind::Repr(reprs) => { codegen_fn_attrs.alignment = reprs .iter() - .find_map(|(r, _)| if let ReprAlign(x) = r { Some(*x) } else { None }); + .filter_map(|(r, _)| if let ReprAlign(x) = r { Some(*x) } else { None }) + .max(); } _ => {} diff --git a/tests/codegen/align-fn.rs b/tests/codegen/align-fn.rs index 97f23cc042304..660d8cd2bbf4f 100644 --- a/tests/codegen/align-fn.rs +++ b/tests/codegen/align-fn.rs @@ -47,3 +47,22 @@ impl T for () {} pub fn foo() { ().trait_method(); } + +// CHECK-LABEL: align_specified_twice_1 +// CHECK-SAME: align 64 +#[no_mangle] +#[repr(align(32), align(64))] +pub fn align_specified_twice_1() {} + +// CHECK-LABEL: align_specified_twice_2 +// CHECK-SAME: align 128 +#[no_mangle] +#[repr(align(128), align(32))] +pub fn align_specified_twice_2() {} + +// CHECK-LABEL: align_specified_twice_3 +// CHECK-SAME: align 256 +#[no_mangle] +#[repr(align(32))] +#[repr(align(256))] +pub fn align_specified_twice_3() {} From 4d6ae78fa22d04b2c255cb43faabc1ada36cd2c1 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Wed, 16 Apr 2025 20:03:18 +1000 Subject: [PATCH 142/266] Remove old diagnostic notes for type ascription syntax Type ascription syntax was removed in 2023. --- compiler/rustc_parse/messages.ftl | 3 --- compiler/rustc_parse/src/errors.rs | 6 ------ compiler/rustc_parse/src/parser/diagnostics.rs | 5 +---- compiler/rustc_parse/src/parser/path.rs | 2 -- compiler/rustc_parse/src/parser/stmt.rs | 4 ---- ...492-tuple-destructure-missing-parens.stderr | 1 - ...single-colon-path-not-const-generics.stderr | 1 - .../or-patterns-syntactic-fail.stderr | 1 - .../issue-35813-postfix-after-cast.stderr | 18 ------------------ .../turbofish-arg-with-stray-colon.stderr | 1 - tests/ui/parser/ternary_operator.stderr | 2 -- ...ype-ascription-syntactically-invalid.stderr | 2 -- ...ment-list-from-path-sep-error-129273.stderr | 1 - .../ui/suggestions/many-type-ascription.stderr | 2 -- ...ct-field-type-including-single-colon.stderr | 2 -- .../type-ascription-instead-of-method.stderr | 1 - .../type-ascription-instead-of-path-2.stderr | 1 - .../type-ascription-instead-of-path.stderr | 1 - .../type-ascription-instead-of-variant.stderr | 1 - tests/ui/type/ascription/issue-47666.stderr | 1 - tests/ui/type/ascription/issue-54516.stderr | 1 - tests/ui/type/ascription/issue-60933.stderr | 1 - tests/ui/type/missing-let-in-binding.stderr | 1 - ...-ascription-instead-of-statement-end.stderr | 1 - .../ui/type/type-ascription-precedence.stderr | 2 -- .../type/type-ascription-with-fn-call.stderr | 1 - 26 files changed, 1 insertion(+), 62 deletions(-) diff --git a/compiler/rustc_parse/messages.ftl b/compiler/rustc_parse/messages.ftl index 93fa89b68b97a..5837f5de5ee82 100644 --- a/compiler/rustc_parse/messages.ftl +++ b/compiler/rustc_parse/messages.ftl @@ -806,9 +806,6 @@ parse_trait_alias_cannot_be_unsafe = trait aliases cannot be `unsafe` parse_transpose_dyn_or_impl = `for<...>` expected after `{$kw}`, not before .suggestion = move `{$kw}` before the `for<...>` -parse_type_ascription_removed = - if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 - parse_unclosed_unicode_escape = unterminated unicode escape .label = missing a closing `{"}"}` .terminate = terminate the unicode escape diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index dfdef018bc374..bca2f1daaf626 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -1598,9 +1598,6 @@ pub(crate) struct PathSingleColon { #[suggestion(applicability = "machine-applicable", code = ":", style = "verbose")] pub suggestion: Span, - - #[note(parse_type_ascription_removed)] - pub type_ascription: bool, } #[derive(Diagnostic)] @@ -1617,9 +1614,6 @@ pub(crate) struct ColonAsSemi { #[primary_span] #[suggestion(applicability = "machine-applicable", code = ";", style = "verbose")] pub span: Span, - - #[note(parse_type_ascription_removed)] - pub type_ascription: bool, } #[derive(Diagnostic)] diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index a4978b5a0fe1d..b6945c6f7dbd1 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -1943,10 +1943,7 @@ impl<'a> Parser<'a> { && self.token == token::Colon && self.look_ahead(1, |next| line_idx(self.token.span) < line_idx(next.span)) { - self.dcx().emit_err(ColonAsSemi { - span: self.token.span, - type_ascription: self.psess.unstable_features.is_nightly_build(), - }); + self.dcx().emit_err(ColonAsSemi { span: self.token.span }); self.bump(); return true; } diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index 30fb96c6ea906..0288365566238 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -273,7 +273,6 @@ impl<'a> Parser<'a> { self.dcx().emit_err(PathSingleColon { span: self.prev_token.span, suggestion: self.prev_token.span.shrink_to_hi(), - type_ascription: self.psess.unstable_features.is_nightly_build(), }); } continue; @@ -348,7 +347,6 @@ impl<'a> Parser<'a> { err = self.dcx().create_err(PathSingleColon { span: self.token.span, suggestion: self.prev_token.span.shrink_to_hi(), - type_ascription: self.psess.unstable_features.is_nightly_build(), }); } // Attempt to find places where a missing `>` might belong. diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index 551b9e2f13718..0cc8b60501869 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -771,10 +771,6 @@ impl<'a> Parser<'a> { Applicability::MaybeIncorrect, ); } - if self.psess.unstable_features.is_nightly_build() { - // FIXME(Nilstrieb): Remove this again after a few months. - err.note("type ascription syntax has been removed, see issue #101728 "); - } } } diff --git a/tests/ui/did_you_mean/issue-48492-tuple-destructure-missing-parens.stderr b/tests/ui/did_you_mean/issue-48492-tuple-destructure-missing-parens.stderr index d4812d4831b03..c74cb89f85cb9 100644 --- a/tests/ui/did_you_mean/issue-48492-tuple-destructure-missing-parens.stderr +++ b/tests/ui/did_you_mean/issue-48492-tuple-destructure-missing-parens.stderr @@ -66,7 +66,6 @@ error: unexpected `,` in pattern LL | let women, men: (Vec, Vec) = genomes.iter().cloned() | ^ | - = note: type ascription syntax has been removed, see issue #101728 help: try adding parentheses to match on a tuple | LL | let (women, men): (Vec, Vec) = genomes.iter().cloned() diff --git a/tests/ui/generics/single-colon-path-not-const-generics.stderr b/tests/ui/generics/single-colon-path-not-const-generics.stderr index c14a5e62a0c8f..9eb62de275614 100644 --- a/tests/ui/generics/single-colon-path-not-const-generics.stderr +++ b/tests/ui/generics/single-colon-path-not-const-generics.stderr @@ -4,7 +4,6 @@ error: path separator must be a double colon LL | a: Vec, | ^ | - = note: if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 help: use a double colon instead | LL | a: Vec, diff --git a/tests/ui/or-patterns/or-patterns-syntactic-fail.stderr b/tests/ui/or-patterns/or-patterns-syntactic-fail.stderr index 5608138078fbb..74e4ceab80e88 100644 --- a/tests/ui/or-patterns/or-patterns-syntactic-fail.stderr +++ b/tests/ui/or-patterns/or-patterns-syntactic-fail.stderr @@ -6,7 +6,6 @@ LL | let _ = |A | B: E| (); | | | while parsing the body of this closure | - = note: type ascription syntax has been removed, see issue #101728 help: you might have meant to open the body of the closure | LL | let _ = |A | { B: E| (); diff --git a/tests/ui/parser/issues/issue-35813-postfix-after-cast.stderr b/tests/ui/parser/issues/issue-35813-postfix-after-cast.stderr index e34371be3d262..64cf8baf9a5d4 100644 --- a/tests/ui/parser/issues/issue-35813-postfix-after-cast.stderr +++ b/tests/ui/parser/issues/issue-35813-postfix-after-cast.stderr @@ -49,24 +49,18 @@ error: expected one of `.`, `;`, `?`, `else`, or an operator, found `:` | LL | let _ = 0i32: i32: i32.count_ones(); | ^ expected one of `.`, `;`, `?`, `else`, or an operator - | - = note: type ascription syntax has been removed, see issue #101728 error: expected one of `!`, `(`, `.`, `::`, `;`, `<`, `?`, or `else`, found `:` --> $DIR/issue-35813-postfix-after-cast.rs:43:21 | LL | let _ = 0 as i32: i32.count_ones(); | ^ expected one of 8 possible tokens - | - = note: type ascription syntax has been removed, see issue #101728 error: expected one of `.`, `;`, `?`, `else`, or an operator, found `:` --> $DIR/issue-35813-postfix-after-cast.rs:47:17 | LL | let _ = 0i32: i32 as i32.count_ones(); | ^ expected one of `.`, `;`, `?`, `else`, or an operator - | - = note: type ascription syntax has been removed, see issue #101728 error: cast cannot be followed by a method call --> $DIR/issue-35813-postfix-after-cast.rs:51:13 @@ -84,16 +78,12 @@ error: expected one of `.`, `;`, `?`, `else`, or an operator, found `:` | LL | let _ = 0i32: i32: i32 as u32 as i32.count_ones(); | ^ expected one of `.`, `;`, `?`, `else`, or an operator - | - = note: type ascription syntax has been removed, see issue #101728 error: expected one of `.`, `;`, `?`, `else`, or an operator, found `:` --> $DIR/issue-35813-postfix-after-cast.rs:60:17 | LL | let _ = 0i32: i32.count_ones(): u32; | ^ expected one of `.`, `;`, `?`, `else`, or an operator - | - = note: type ascription syntax has been removed, see issue #101728 error: cast cannot be followed by a method call --> $DIR/issue-35813-postfix-after-cast.rs:64:13 @@ -111,16 +101,12 @@ error: expected one of `.`, `;`, `?`, or `else`, found `:` | LL | let _ = 0 as i32.count_ones(): u32; | ^ expected one of `.`, `;`, `?`, or `else` - | - = note: type ascription syntax has been removed, see issue #101728 error: expected one of `.`, `;`, `?`, `else`, or an operator, found `:` --> $DIR/issue-35813-postfix-after-cast.rs:69:17 | LL | let _ = 0i32: i32.count_ones() as u32; | ^ expected one of `.`, `;`, `?`, `else`, or an operator - | - = note: type ascription syntax has been removed, see issue #101728 error: cast cannot be followed by a method call --> $DIR/issue-35813-postfix-after-cast.rs:73:13 @@ -138,8 +124,6 @@ error: expected one of `.`, `;`, `?`, `else`, or an operator, found `:` | LL | let _ = 0i32: i32: i32.count_ones() as u32 as i32; | ^ expected one of `.`, `;`, `?`, `else`, or an operator - | - = note: type ascription syntax has been removed, see issue #101728 error: cast cannot be followed by a method call --> $DIR/issue-35813-postfix-after-cast.rs:82:13 @@ -262,8 +246,6 @@ error: expected identifier, found `:` | LL | drop_ptr: F(); | ^ expected identifier - | - = note: type ascription syntax has been removed, see issue #101728 error: expected one of `!`, `.`, `::`, `;`, `?`, `{`, `}`, or an operator, found `:` --> $DIR/issue-35813-postfix-after-cast.rs:160:13 diff --git a/tests/ui/parser/recover/turbofish-arg-with-stray-colon.stderr b/tests/ui/parser/recover/turbofish-arg-with-stray-colon.stderr index 583b98c650f03..c0f9db9184c0b 100644 --- a/tests/ui/parser/recover/turbofish-arg-with-stray-colon.stderr +++ b/tests/ui/parser/recover/turbofish-arg-with-stray-colon.stderr @@ -4,7 +4,6 @@ error: expected one of `!`, `.`, `::`, `;`, `?`, `else`, `{`, or an operator, fo LL | let x = Tr; | ^ expected one of 8 possible tokens | - = note: type ascription syntax has been removed, see issue #101728 help: maybe write a path separator here | LL | let x = Tr; diff --git a/tests/ui/parser/ternary_operator.stderr b/tests/ui/parser/ternary_operator.stderr index 6635e1672f781..e12a7ff3718e0 100644 --- a/tests/ui/parser/ternary_operator.stderr +++ b/tests/ui/parser/ternary_operator.stderr @@ -33,8 +33,6 @@ error: expected one of `.`, `;`, `?`, `else`, or an operator, found `:` | LL | let x = 5 > 2 ? { let x = vec![]: Vec; x } : { false }; | ^ expected one of `.`, `;`, `?`, `else`, or an operator - | - = note: type ascription syntax has been removed, see issue #101728 error: Rust has no ternary operator --> $DIR/ternary_operator.rs:26:19 diff --git a/tests/ui/pattern/bindings-after-at/nested-type-ascription-syntactically-invalid.stderr b/tests/ui/pattern/bindings-after-at/nested-type-ascription-syntactically-invalid.stderr index 6ce8f6d31a031..1847e407f6ba0 100644 --- a/tests/ui/pattern/bindings-after-at/nested-type-ascription-syntactically-invalid.stderr +++ b/tests/ui/pattern/bindings-after-at/nested-type-ascription-syntactically-invalid.stderr @@ -11,8 +11,6 @@ error: expected one of `)`, `,`, `@`, `if`, or `|`, found `:` | LL | let a @ (b: u8); | ^ expected one of `)`, `,`, `@`, `if`, or `|` - | - = note: type ascription syntax has been removed, see issue #101728 error: expected one of `!`, `(`, `+`, `::`, `;`, `<`, or `=`, found `@` --> $DIR/nested-type-ascription-syntactically-invalid.rs:30:15 diff --git a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.stderr b/tests/ui/suggestions/argument-list-from-path-sep-error-129273.stderr index 92947e3b177f0..713b071a625a0 100644 --- a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.stderr +++ b/tests/ui/suggestions/argument-list-from-path-sep-error-129273.stderr @@ -4,7 +4,6 @@ error: path separator must be a double colon LL | fn fmt(&self, f: &mut fmt:Formatter) -> fmt::Result { | ^ | - = note: if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 help: use a double colon instead | LL | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { diff --git a/tests/ui/suggestions/many-type-ascription.stderr b/tests/ui/suggestions/many-type-ascription.stderr index feddc7d62a754..47e19c508ef90 100644 --- a/tests/ui/suggestions/many-type-ascription.stderr +++ b/tests/ui/suggestions/many-type-ascription.stderr @@ -3,8 +3,6 @@ error: expected one of `.`, `;`, `?`, `else`, or an operator, found `:` | LL | let _ = 0: i32; | ^ expected one of `.`, `;`, `?`, `else`, or an operator - | - = note: type ascription syntax has been removed, see issue #101728 error: aborting due to 1 previous error diff --git a/tests/ui/suggestions/struct-field-type-including-single-colon.stderr b/tests/ui/suggestions/struct-field-type-including-single-colon.stderr index ce16aca1e14a2..b9302b0453d5b 100644 --- a/tests/ui/suggestions/struct-field-type-including-single-colon.stderr +++ b/tests/ui/suggestions/struct-field-type-including-single-colon.stderr @@ -4,7 +4,6 @@ error: path separator must be a double colon LL | a: foo:A, | ^ | - = note: if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 help: use a double colon instead | LL | a: foo::A, @@ -16,7 +15,6 @@ error: path separator must be a double colon LL | b: foo::bar:B, | ^ | - = note: if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 help: use a double colon instead | LL | b: foo::bar::B, diff --git a/tests/ui/suggestions/type-ascription-instead-of-method.stderr b/tests/ui/suggestions/type-ascription-instead-of-method.stderr index 0bef1c185db63..6dc7b5e18ef80 100644 --- a/tests/ui/suggestions/type-ascription-instead-of-method.stderr +++ b/tests/ui/suggestions/type-ascription-instead-of-method.stderr @@ -4,7 +4,6 @@ error: path separator must be a double colon LL | let _ = Box:new("foo".to_string()); | ^ | - = note: if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 help: use a double colon instead | LL | let _ = Box::new("foo".to_string()); diff --git a/tests/ui/suggestions/type-ascription-instead-of-path-2.stderr b/tests/ui/suggestions/type-ascription-instead-of-path-2.stderr index 0b37bf9a57bb7..79dffc0cf9b08 100644 --- a/tests/ui/suggestions/type-ascription-instead-of-path-2.stderr +++ b/tests/ui/suggestions/type-ascription-instead-of-path-2.stderr @@ -4,7 +4,6 @@ error: expected one of `(`, `.`, `::`, `;`, `?`, `else`, or an operator, found ` LL | let _ = vec![Ok(2)].into_iter().collect:,_>>()?; | ^ expected one of 7 possible tokens | - = note: type ascription syntax has been removed, see issue #101728 help: maybe write a path separator here | LL | let _ = vec![Ok(2)].into_iter().collect::,_>>()?; diff --git a/tests/ui/suggestions/type-ascription-instead-of-path.stderr b/tests/ui/suggestions/type-ascription-instead-of-path.stderr index 8c16acff79947..a8364611b50c3 100644 --- a/tests/ui/suggestions/type-ascription-instead-of-path.stderr +++ b/tests/ui/suggestions/type-ascription-instead-of-path.stderr @@ -4,7 +4,6 @@ error: path separator must be a double colon LL | std:io::stdin(); | ^ | - = note: if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 help: use a double colon instead | LL | std::io::stdin(); diff --git a/tests/ui/suggestions/type-ascription-instead-of-variant.stderr b/tests/ui/suggestions/type-ascription-instead-of-variant.stderr index f0b31722e40ef..e836b37c100dc 100644 --- a/tests/ui/suggestions/type-ascription-instead-of-variant.stderr +++ b/tests/ui/suggestions/type-ascription-instead-of-variant.stderr @@ -4,7 +4,6 @@ error: path separator must be a double colon LL | let _ = Option:Some(""); | ^ | - = note: if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 help: use a double colon instead | LL | let _ = Option::Some(""); diff --git a/tests/ui/type/ascription/issue-47666.stderr b/tests/ui/type/ascription/issue-47666.stderr index fd825e86675d3..6568845fe5de2 100644 --- a/tests/ui/type/ascription/issue-47666.stderr +++ b/tests/ui/type/ascription/issue-47666.stderr @@ -4,7 +4,6 @@ error: path separator must be a double colon LL | let _ = Option:Some(vec![0, 1]); | ^ | - = note: if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 help: use a double colon instead | LL | let _ = Option::Some(vec![0, 1]); diff --git a/tests/ui/type/ascription/issue-54516.stderr b/tests/ui/type/ascription/issue-54516.stderr index 64fdc1fa24a63..925080e9050b6 100644 --- a/tests/ui/type/ascription/issue-54516.stderr +++ b/tests/ui/type/ascription/issue-54516.stderr @@ -4,7 +4,6 @@ error: path separator must be a double colon LL | println!("{}", std::mem:size_of::>()); | ^ | - = note: if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 help: use a double colon instead | LL | println!("{}", std::mem::size_of::>()); diff --git a/tests/ui/type/ascription/issue-60933.stderr b/tests/ui/type/ascription/issue-60933.stderr index c68394d0504af..7b55935b35ba2 100644 --- a/tests/ui/type/ascription/issue-60933.stderr +++ b/tests/ui/type/ascription/issue-60933.stderr @@ -4,7 +4,6 @@ error: path separator must be a double colon LL | let _: usize = std::mem:size_of::(); | ^ | - = note: if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 help: use a double colon instead | LL | let _: usize = std::mem::size_of::(); diff --git a/tests/ui/type/missing-let-in-binding.stderr b/tests/ui/type/missing-let-in-binding.stderr index a9d766e4c3cf5..dee3d56dc51e9 100644 --- a/tests/ui/type/missing-let-in-binding.stderr +++ b/tests/ui/type/missing-let-in-binding.stderr @@ -4,7 +4,6 @@ error: expected identifier, found `:` LL | _foo: i32 = 4; | ^ expected identifier | - = note: type ascription syntax has been removed, see issue #101728 help: you might have meant to introduce a new binding | LL | let _foo: i32 = 4; diff --git a/tests/ui/type/type-ascription-instead-of-statement-end.stderr b/tests/ui/type/type-ascription-instead-of-statement-end.stderr index 34759b413d89d..82b7fd23a4d9c 100644 --- a/tests/ui/type/type-ascription-instead-of-statement-end.stderr +++ b/tests/ui/type/type-ascription-instead-of-statement-end.stderr @@ -4,7 +4,6 @@ error: statements are terminated with a semicolon LL | println!("test"): | ^ | - = note: if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 help: use a semicolon instead | LL - println!("test"): diff --git a/tests/ui/type/type-ascription-precedence.stderr b/tests/ui/type/type-ascription-precedence.stderr index 09cdc370309dc..f7ae612ef60fb 100644 --- a/tests/ui/type/type-ascription-precedence.stderr +++ b/tests/ui/type/type-ascription-precedence.stderr @@ -33,8 +33,6 @@ error: expected identifier, found `:` | LL | S .. S: S; | ^ expected identifier - | - = note: type ascription syntax has been removed, see issue #101728 error: expected one of `.`, `;`, `?`, `}`, or an operator, found `:` --> $DIR/type-ascription-precedence.rs:53:13 diff --git a/tests/ui/type/type-ascription-with-fn-call.stderr b/tests/ui/type/type-ascription-with-fn-call.stderr index 4222762373dcc..803c9f1c302ee 100644 --- a/tests/ui/type/type-ascription-with-fn-call.stderr +++ b/tests/ui/type/type-ascription-with-fn-call.stderr @@ -4,7 +4,6 @@ error: statements are terminated with a semicolon LL | f() : | ^ | - = note: if you meant to annotate an expression with a type, the type ascription syntax has been removed, see issue #101728 help: use a semicolon instead | LL - f() : From face4716ee0015c489c3108b9180d81865aca4b6 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 16 Apr 2025 14:48:20 +0200 Subject: [PATCH 143/266] replace some #[rustc_intrinsic] usage with use of the libcore declarations --- tests/codegen/intrinsic-no-unnamed-attr.rs | 5 +-- tests/ui/intrinsics/intrinsic-atomics.rs | 51 +--------------------- 2 files changed, 4 insertions(+), 52 deletions(-) diff --git a/tests/codegen/intrinsic-no-unnamed-attr.rs b/tests/codegen/intrinsic-no-unnamed-attr.rs index 35eb025ab6bb6..4bec579831dc4 100644 --- a/tests/codegen/intrinsic-no-unnamed-attr.rs +++ b/tests/codegen/intrinsic-no-unnamed-attr.rs @@ -1,9 +1,8 @@ //@ compile-flags: -C no-prepopulate-passes -#![feature(intrinsics)] +#![feature(core_intrinsics)] -#[rustc_intrinsic] -unsafe fn sqrtf32(x: f32) -> f32; +use std::intrinsics::sqrtf32; // CHECK: @llvm.sqrt.f32(float) #{{[0-9]*}} diff --git a/tests/ui/intrinsics/intrinsic-atomics.rs b/tests/ui/intrinsics/intrinsic-atomics.rs index 6bc3f8d884db1..9127cc649e66d 100644 --- a/tests/ui/intrinsics/intrinsic-atomics.rs +++ b/tests/ui/intrinsics/intrinsic-atomics.rs @@ -1,53 +1,6 @@ //@ run-pass -#![feature(intrinsics)] - -mod rusti { - - #[rustc_intrinsic] - pub unsafe fn atomic_cxchg_seqcst_seqcst(dst: *mut T, old: T, src: T) -> (T, bool); - #[rustc_intrinsic] - pub unsafe fn atomic_cxchg_acquire_acquire(dst: *mut T, old: T, src: T) -> (T, bool); - #[rustc_intrinsic] - pub unsafe fn atomic_cxchg_release_relaxed(dst: *mut T, old: T, src: T) -> (T, bool); - - #[rustc_intrinsic] - pub unsafe fn atomic_cxchgweak_seqcst_seqcst(dst: *mut T, old: T, src: T) -> (T, bool); - #[rustc_intrinsic] - pub unsafe fn atomic_cxchgweak_acquire_acquire(dst: *mut T, old: T, src: T) -> (T, bool); - #[rustc_intrinsic] - pub unsafe fn atomic_cxchgweak_release_relaxed(dst: *mut T, old: T, src: T) -> (T, bool); - - #[rustc_intrinsic] - pub unsafe fn atomic_load_seqcst(src: *const T) -> T; - #[rustc_intrinsic] - pub unsafe fn atomic_load_acquire(src: *const T) -> T; - - #[rustc_intrinsic] - pub unsafe fn atomic_store_seqcst(dst: *mut T, val: T); - #[rustc_intrinsic] - pub unsafe fn atomic_store_release(dst: *mut T, val: T); - - #[rustc_intrinsic] - pub unsafe fn atomic_xchg_seqcst(dst: *mut T, src: T) -> T; - #[rustc_intrinsic] - pub unsafe fn atomic_xchg_acquire(dst: *mut T, src: T) -> T; - #[rustc_intrinsic] - pub unsafe fn atomic_xchg_release(dst: *mut T, src: T) -> T; - - #[rustc_intrinsic] - pub unsafe fn atomic_xadd_seqcst(dst: *mut T, src: T) -> T; - #[rustc_intrinsic] - pub unsafe fn atomic_xadd_acquire(dst: *mut T, src: T) -> T; - #[rustc_intrinsic] - pub unsafe fn atomic_xadd_release(dst: *mut T, src: T) -> T; - - #[rustc_intrinsic] - pub unsafe fn atomic_xsub_seqcst(dst: *mut T, src: T) -> T; - #[rustc_intrinsic] - pub unsafe fn atomic_xsub_acquire(dst: *mut T, src: T) -> T; - #[rustc_intrinsic] - pub unsafe fn atomic_xsub_release(dst: *mut T, src: T) -> T; -} +#![feature(core_intrinsics)] +use std::intrinsics as rusti; pub fn main() { unsafe { From 299877e280bbe02f0170742396c38ab0b20bab59 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Wed, 16 Apr 2025 14:52:08 +0200 Subject: [PATCH 144/266] Update stdarch submodule --- library/stdarch | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/stdarch b/library/stdarch index 9426bb56586c6..4666c7376f25a 160000 --- a/library/stdarch +++ b/library/stdarch @@ -1 +1 @@ -Subproject commit 9426bb56586c6ae4095a2dcbd66c570253e6fb32 +Subproject commit 4666c7376f25a265c74535585d622da3da6dfeb1 From 2f0ba6791944fbbc9236ea4138389039ebbffd4a Mon Sep 17 00:00:00 2001 From: Lyndon Brown Date: Wed, 16 Apr 2025 14:42:11 +0100 Subject: [PATCH 145/266] fix incorrect type in cstr `to_string_lossy()` docs Restoring what it said prior to commit 67065fe in which it was changed incorrectly with no supporting explanation. Closes #139835. --- library/alloc/src/ffi/c_str.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/alloc/src/ffi/c_str.rs b/library/alloc/src/ffi/c_str.rs index f6743c6571095..ef8548d24293d 100644 --- a/library/alloc/src/ffi/c_str.rs +++ b/library/alloc/src/ffi/c_str.rs @@ -1116,7 +1116,7 @@ impl CStr { /// with the corresponding &[str] slice. Otherwise, it will /// replace any invalid UTF-8 sequences with /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a - /// [Cow]::[Owned]\(&[str]) with the result. + /// [Cow]::[Owned]\([String]) with the result. /// /// [str]: prim@str "str" /// [Borrowed]: Cow::Borrowed From 7ce21e4fb39e9d288f3fe96ad48f8bc8ec973588 Mon Sep 17 00:00:00 2001 From: Spencer Date: Tue, 15 Apr 2025 20:04:04 -0600 Subject: [PATCH 146/266] Cleaned up base tests for `isize` and `usize` in `tests/ui/numbers-arithmetic` --- tests/ui/numbers-arithmetic/int.rs | 6 ------ tests/ui/numbers-arithmetic/isize-base.rs | 25 +++++++++++++++++++++++ tests/ui/numbers-arithmetic/uint.rs | 6 ------ tests/ui/numbers-arithmetic/usize-base.rs | 25 +++++++++++++++++++++++ 4 files changed, 50 insertions(+), 12 deletions(-) delete mode 100644 tests/ui/numbers-arithmetic/int.rs create mode 100644 tests/ui/numbers-arithmetic/isize-base.rs delete mode 100644 tests/ui/numbers-arithmetic/uint.rs create mode 100644 tests/ui/numbers-arithmetic/usize-base.rs diff --git a/tests/ui/numbers-arithmetic/int.rs b/tests/ui/numbers-arithmetic/int.rs deleted file mode 100644 index 42f8e50d6efaf..0000000000000 --- a/tests/ui/numbers-arithmetic/int.rs +++ /dev/null @@ -1,6 +0,0 @@ -//@ run-pass - - - - -pub fn main() { let _x: isize = 10; } diff --git a/tests/ui/numbers-arithmetic/isize-base.rs b/tests/ui/numbers-arithmetic/isize-base.rs new file mode 100644 index 0000000000000..412e7ac7a2e92 --- /dev/null +++ b/tests/ui/numbers-arithmetic/isize-base.rs @@ -0,0 +1,25 @@ +//! Tests basic `isize` functionality + +//@ run-pass + +pub fn main() { + // Literal matches assignment type + let a: isize = 42isize; + // Literal cast + let b: isize = 42 as isize; + // Literal type inference from assignment type + let c: isize = 42; + // Assignment type inference from literal (and later comparison) + let d = 42isize; + // Function return value type inference + let e = return_val(); + + assert_eq!(a, b); + assert_eq!(a, c); + assert_eq!(a, d); + assert_eq!(a, e); +} + +fn return_val() -> isize { + 42 +} diff --git a/tests/ui/numbers-arithmetic/uint.rs b/tests/ui/numbers-arithmetic/uint.rs deleted file mode 100644 index c2087b5a06c63..0000000000000 --- a/tests/ui/numbers-arithmetic/uint.rs +++ /dev/null @@ -1,6 +0,0 @@ -//@ run-pass - - - - -pub fn main() { let _x: usize = 10 as usize; } diff --git a/tests/ui/numbers-arithmetic/usize-base.rs b/tests/ui/numbers-arithmetic/usize-base.rs new file mode 100644 index 0000000000000..833fc0497989d --- /dev/null +++ b/tests/ui/numbers-arithmetic/usize-base.rs @@ -0,0 +1,25 @@ +//! Tests basic `usize` functionality + +//@ run-pass + +pub fn main() { + // Literal matches assignment type + let a: usize = 42usize; + // Literal cast + let b: usize = 42 as usize; + // Literal type inference from assignment type + let c: usize = 42; + // Assignment type inference from literal (and later comparison) + let d = 42usize; + // Function return value type inference + let e = return_val(); + + assert_eq!(a, b); + assert_eq!(a, c); + assert_eq!(a, d); + assert_eq!(a, e); +} + +fn return_val() -> usize { + 42 +} From a870bba0d6b7b304e819ab820900496425ace96b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 16 Apr 2025 17:38:37 +0200 Subject: [PATCH 147/266] Add a warning when combining LLD with external LLVM config --- src/bootstrap/src/core/build_steps/compile.rs | 2 +- src/bootstrap/src/core/config/config.rs | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index f78539b47816b..6a5b38dd50435 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -155,7 +155,7 @@ impl Step for Std { // When using `download-rustc`, we already have artifacts for the host available. Don't // recompile them. - if builder.download_rustc() && builder.config.is_builder_target(target) + if builder.download_rustc() && builder.config.is_host_target(target) // NOTE: the beta compiler may generate different artifacts than the downloaded compiler, so // its artifacts can't be reused. && compiler.stage != 0 diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 12e157a34ae3e..1668443b04d87 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -2397,6 +2397,12 @@ impl Config { ); } + if config.lld_enabled && config.is_system_llvm(config.build) { + eprintln!( + "Warning: LLD is enabled when using external llvm-config. LLD will not be built and copied to the sysroot." + ); + } + let default_std_features = BTreeSet::from([String::from("panic-unwind")]); config.rust_std_features = std_features.unwrap_or(default_std_features); From 96984c014962cbdb760dfbf12fddec51fe0a722b Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Tue, 15 Apr 2025 18:26:16 +0530 Subject: [PATCH 148/266] add retry support to recursive_remove --- src/build_helper/src/fs/mod.rs | 50 +++++++++++++++++++++++++------- src/build_helper/src/fs/tests.rs | 2 +- 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/src/build_helper/src/fs/mod.rs b/src/build_helper/src/fs/mod.rs index 02029846fd147..a7ddc0dba864a 100644 --- a/src/build_helper/src/fs/mod.rs +++ b/src/build_helper/src/fs/mod.rs @@ -22,21 +22,27 @@ where /// A wrapper around [`std::fs::remove_dir_all`] that can also be used on *non-directory entries*, /// including files and symbolic links. /// -/// - This will produce an error if the target path is not found. +/// - This will not produce an error if the target path is not found. /// - Like [`std::fs::remove_dir_all`], this helper does not traverse symbolic links, will remove /// symbolic link itself. /// - This helper is **not** robust against races on the underlying filesystem, behavior is /// unspecified if this helper is called concurrently. /// - This helper is not robust against TOCTOU problems. /// -/// FIXME: this implementation is insufficiently robust to replace bootstrap's clean `rm_rf` -/// implementation: -/// -/// - This implementation currently does not perform retries. +/// FIXME: Audit whether this implementation is robust enough to replace bootstrap's clean `rm_rf`. #[track_caller] pub fn recursive_remove>(path: P) -> io::Result<()> { let path = path.as_ref(); - let metadata = fs::symlink_metadata(path)?; + + // If the path doesn't exist, we treat it as a successful no-op. + // From the caller's perspective, the goal is simply "ensure this file/dir is gone" — + // if it's already not there, that's a success, not an error. + let metadata = match fs::symlink_metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(e), + }; + #[cfg(windows)] let is_dir_like = |meta: &fs::Metadata| { use std::os::windows::fs::FileTypeExt; @@ -45,11 +51,35 @@ pub fn recursive_remove>(path: P) -> io::Result<()> { #[cfg(not(windows))] let is_dir_like = fs::Metadata::is_dir; - if is_dir_like(&metadata) { - fs::remove_dir_all(path) - } else { - try_remove_op_set_perms(fs::remove_file, path, metadata) + const MAX_RETRIES: usize = 5; + const RETRY_DELAY_MS: u64 = 100; + + let try_remove = || { + if is_dir_like(&metadata) { + fs::remove_dir_all(path) + } else { + try_remove_op_set_perms(fs::remove_file, path, metadata.clone()) + } + }; + + // Retry deletion a few times to handle transient filesystem errors. + // This is unusual for local file operations, but it's a mitigation + // against unlikely events where malware scanners may be holding a + // file beyond our control, to give the malware scanners some opportunity + // to release their hold. + for attempt in 0..MAX_RETRIES { + match try_remove() { + Ok(()) => return Ok(()), + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(_) if attempt < MAX_RETRIES - 1 => { + std::thread::sleep(std::time::Duration::from_millis(RETRY_DELAY_MS)); + continue; + } + Err(e) => return Err(e), + } } + + Ok(()) } fn try_remove_op_set_perms<'p, Op>(mut op: Op, path: &'p Path, metadata: Metadata) -> io::Result<()> diff --git a/src/build_helper/src/fs/tests.rs b/src/build_helper/src/fs/tests.rs index 1e694393127cb..7ce1d8928d1cb 100644 --- a/src/build_helper/src/fs/tests.rs +++ b/src/build_helper/src/fs/tests.rs @@ -14,7 +14,7 @@ mod recursive_remove_tests { let tmpdir = env::temp_dir(); let path = tmpdir.join("__INTERNAL_BOOTSTRAP_nonexistent_path"); assert!(fs::symlink_metadata(&path).is_err_and(|e| e.kind() == io::ErrorKind::NotFound)); - assert!(recursive_remove(&path).is_err_and(|e| e.kind() == io::ErrorKind::NotFound)); + assert!(recursive_remove(&path).is_ok()); } #[test] From 003d633dde66d9b3d3045cf60d9ee90e34452752 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Tue, 15 Apr 2025 18:26:42 +0530 Subject: [PATCH 149/266] add remove_and_create_dir_all in build_helper --- src/build_helper/src/fs/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/build_helper/src/fs/mod.rs b/src/build_helper/src/fs/mod.rs index a7ddc0dba864a..123df76e6a2e9 100644 --- a/src/build_helper/src/fs/mod.rs +++ b/src/build_helper/src/fs/mod.rs @@ -97,3 +97,9 @@ where Err(e) => Err(e), } } + +pub fn remove_and_create_dir_all>(path: P) -> io::Result<()> { + let path = path.as_ref(); + recursive_remove(path)?; + fs::create_dir_all(path) +} From d4eab8a3732cd2154b79d42fc0f1e059c6883475 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Tue, 15 Apr 2025 19:31:16 +0530 Subject: [PATCH 150/266] remove old remove_and_create_dir_all and use build_helpers remove_and_create_dir_all --- src/tools/compiletest/src/runtest.rs | 31 ++++++++++++------- src/tools/compiletest/src/runtest/rustdoc.rs | 4 ++- .../compiletest/src/runtest/rustdoc_json.rs | 4 ++- 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 24fc2ddb74104..e1a5fe523fe1e 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -9,6 +9,7 @@ use std::process::{Child, Command, ExitStatus, Output, Stdio}; use std::sync::Arc; use std::{env, iter, str}; +use build_helper::fs::remove_and_create_dir_all; use camino::{Utf8Path, Utf8PathBuf}; use colored::Colorize; use regex::{Captures, Regex}; @@ -207,12 +208,6 @@ pub fn compute_stamp_hash(config: &Config) -> String { format!("{:x}", hash.finish()) } -fn remove_and_create_dir_all(path: &Utf8Path) { - let path = path.as_std_path(); - let _ = fs::remove_dir_all(path); - fs::create_dir_all(path).unwrap(); -} - #[derive(Copy, Clone, Debug)] struct TestCx<'test> { config: &'test Config, @@ -523,7 +518,9 @@ impl<'test> TestCx<'test> { let mut rustc = Command::new(&self.config.rustc_path); let out_dir = self.output_base_name().with_extension("pretty-out"); - remove_and_create_dir_all(&out_dir); + remove_and_create_dir_all(&out_dir).unwrap_or_else(|e| { + panic!("failed to remove and recreate output directory `{out_dir}`: {e}") + }); let target = if self.props.force_host { &*self.config.host } else { &*self.config.target }; @@ -1098,13 +1095,19 @@ impl<'test> TestCx<'test> { let aux_dir = self.aux_output_dir_name(); if !self.props.aux.builds.is_empty() { - remove_and_create_dir_all(&aux_dir); + remove_and_create_dir_all(&aux_dir).unwrap_or_else(|e| { + panic!("failed to remove and recreate output directory `{aux_dir}`: {e}") + }); } if !self.props.aux.bins.is_empty() { let aux_bin_dir = self.aux_bin_output_dir_name(); - remove_and_create_dir_all(&aux_dir); - remove_and_create_dir_all(&aux_bin_dir); + remove_and_create_dir_all(&aux_dir).unwrap_or_else(|e| { + panic!("failed to remove and recreate output directory `{aux_dir}`: {e}") + }); + remove_and_create_dir_all(&aux_bin_dir).unwrap_or_else(|e| { + panic!("failed to remove and recreate output directory `{aux_bin_dir}`: {e}") + }); } aux_dir @@ -1509,7 +1512,9 @@ impl<'test> TestCx<'test> { let set_mir_dump_dir = |rustc: &mut Command| { let mir_dump_dir = self.get_mir_dump_dir(); - remove_and_create_dir_all(&mir_dump_dir); + remove_and_create_dir_all(&mir_dump_dir).unwrap_or_else(|e| { + panic!("failed to remove and recreate output directory `{mir_dump_dir}`: {e}") + }); let mut dir_opt = "-Zdump-mir-dir=".to_string(); dir_opt.push_str(mir_dump_dir.as_str()); debug!("dir_opt: {:?}", dir_opt); @@ -1969,7 +1974,9 @@ impl<'test> TestCx<'test> { let suffix = self.safe_revision().map_or("nightly".into(), |path| path.to_owned() + "-nightly"); let compare_dir = output_base_dir(self.config, self.testpaths, Some(&suffix)); - remove_and_create_dir_all(&compare_dir); + remove_and_create_dir_all(&compare_dir).unwrap_or_else(|e| { + panic!("failed to remove and recreate output directory `{compare_dir}`: {e}") + }); // We need to create a new struct for the lifetimes on `config` to work. let new_rustdoc = TestCx { diff --git a/src/tools/compiletest/src/runtest/rustdoc.rs b/src/tools/compiletest/src/runtest/rustdoc.rs index 2583ae96a6788..637ea833357a2 100644 --- a/src/tools/compiletest/src/runtest/rustdoc.rs +++ b/src/tools/compiletest/src/runtest/rustdoc.rs @@ -7,7 +7,9 @@ impl TestCx<'_> { assert!(self.revision.is_none(), "revisions not relevant here"); let out_dir = self.output_base_dir(); - remove_and_create_dir_all(&out_dir); + remove_and_create_dir_all(&out_dir).unwrap_or_else(|e| { + panic!("failed to remove and recreate output directory `{out_dir}`: {e}") + }); let proc_res = self.document(&out_dir, &self.testpaths); if !proc_res.status.success() { diff --git a/src/tools/compiletest/src/runtest/rustdoc_json.rs b/src/tools/compiletest/src/runtest/rustdoc_json.rs index bf7eb2e109a46..9f88faca89268 100644 --- a/src/tools/compiletest/src/runtest/rustdoc_json.rs +++ b/src/tools/compiletest/src/runtest/rustdoc_json.rs @@ -9,7 +9,9 @@ impl TestCx<'_> { assert!(self.revision.is_none(), "revisions not relevant here"); let out_dir = self.output_base_dir(); - remove_and_create_dir_all(&out_dir); + remove_and_create_dir_all(&out_dir).unwrap_or_else(|e| { + panic!("failed to remove and recreate output directory `{out_dir}`: {e}") + }); let proc_res = self.document(&out_dir, &self.testpaths); if !proc_res.status.success() { From 2024e26881ea8bdfb41f53e257464be4332abc79 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 15 Apr 2025 01:01:51 +0000 Subject: [PATCH 151/266] Don't canonicalize crate paths --- compiler/rustc_metadata/src/locator.rs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index 112954eca0dfe..f0a898d678cae 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -427,12 +427,21 @@ impl<'a> CrateLocator<'a> { let (rlibs, rmetas, dylibs) = candidates.entry(hash.to_string()).or_default(); - let path = - try_canonicalize(&spf.path).unwrap_or_else(|_| spf.path.to_path_buf()); - if seen_paths.contains(&path) { - continue; - }; - seen_paths.insert(path.clone()); + { + // As a perforamnce optimisation we canonicalize the path and skip + // ones we've already seeen. This allows us to ignore crates + // we know are exactual equal to ones we've already found. + // Going to the same crate through different symlinks does not change the result. + let path = try_canonicalize(&spf.path) + .unwrap_or_else(|_| spf.path.to_path_buf()); + if seen_paths.contains(&path) { + continue; + }; + seen_paths.insert(path); + } + // Use the original path (potentially with unresolved symlinks), + // filesystem code should not care, but this is nicer for diagnostics. + let path = spf.path.to_path_buf(); match kind { CrateFlavor::Rlib => rlibs.insert(path, search_path.kind), CrateFlavor::Rmeta => rmetas.insert(path, search_path.kind), From 52f35d013116559035621eb83d0e9680ecf74a49 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 15 Apr 2025 12:55:33 +0000 Subject: [PATCH 152/266] Test for relative paths in crate path diagnostics --- .../crateresolve1-1.rs | 6 ++++ .../crateresolve1-2.rs | 6 ++++ .../multiple-candidates.rs | 3 ++ .../multiple-candidates.stderr | 12 +++++++ .../rmake.rs | 34 +++++++++++++++++++ 5 files changed, 61 insertions(+) create mode 100644 tests/run-make/crate-loading-multiple-candidates/crateresolve1-1.rs create mode 100644 tests/run-make/crate-loading-multiple-candidates/crateresolve1-2.rs create mode 100644 tests/run-make/crate-loading-multiple-candidates/multiple-candidates.rs create mode 100644 tests/run-make/crate-loading-multiple-candidates/multiple-candidates.stderr create mode 100644 tests/run-make/crate-loading-multiple-candidates/rmake.rs diff --git a/tests/run-make/crate-loading-multiple-candidates/crateresolve1-1.rs b/tests/run-make/crate-loading-multiple-candidates/crateresolve1-1.rs new file mode 100644 index 0000000000000..fe00f041a862e --- /dev/null +++ b/tests/run-make/crate-loading-multiple-candidates/crateresolve1-1.rs @@ -0,0 +1,6 @@ +#![crate_name = "crateresolve1"] +#![crate_type = "lib"] + +pub fn f() -> isize { + 10 +} diff --git a/tests/run-make/crate-loading-multiple-candidates/crateresolve1-2.rs b/tests/run-make/crate-loading-multiple-candidates/crateresolve1-2.rs new file mode 100644 index 0000000000000..0fb8591b3a52e --- /dev/null +++ b/tests/run-make/crate-loading-multiple-candidates/crateresolve1-2.rs @@ -0,0 +1,6 @@ +#![crate_name = "crateresolve1"] +#![crate_type = "lib"] + +pub fn f() -> isize { + 20 +} diff --git a/tests/run-make/crate-loading-multiple-candidates/multiple-candidates.rs b/tests/run-make/crate-loading-multiple-candidates/multiple-candidates.rs new file mode 100644 index 0000000000000..27cd7ca5c2039 --- /dev/null +++ b/tests/run-make/crate-loading-multiple-candidates/multiple-candidates.rs @@ -0,0 +1,3 @@ +extern crate crateresolve1; + +fn main() {} diff --git a/tests/run-make/crate-loading-multiple-candidates/multiple-candidates.stderr b/tests/run-make/crate-loading-multiple-candidates/multiple-candidates.stderr new file mode 100644 index 0000000000000..de7fc3b0feb93 --- /dev/null +++ b/tests/run-make/crate-loading-multiple-candidates/multiple-candidates.stderr @@ -0,0 +1,12 @@ +error[E0464]: multiple candidates for `rlib` dependency `crateresolve1` found + --> multiple-candidates.rs:1:1 + | +LL | extern crate crateresolve1; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: candidate #1: ./mylibs/libcrateresolve1-1.rlib + = note: candidate #2: ./mylibs/libcrateresolve1-2.rlib + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0464`. diff --git a/tests/run-make/crate-loading-multiple-candidates/rmake.rs b/tests/run-make/crate-loading-multiple-candidates/rmake.rs new file mode 100644 index 0000000000000..ce090850500b8 --- /dev/null +++ b/tests/run-make/crate-loading-multiple-candidates/rmake.rs @@ -0,0 +1,34 @@ +//@ needs-symlink +//@ ignore-cross-compile + +// Tests that the multiple candidate dependencies diagnostic prints relative +// paths if a relative library path was passed in. + +use run_make_support::{bare_rustc, diff, rfs, rustc}; + +fn main() { + // Check that relative paths are preserved in the diagnostic + rfs::create_dir("mylibs"); + rustc().input("crateresolve1-1.rs").out_dir("mylibs").extra_filename("-1").run(); + rustc().input("crateresolve1-2.rs").out_dir("mylibs").extra_filename("-2").run(); + check("./mylibs"); + + // Check that symlinks aren't followed when printing the diagnostic + rfs::rename("mylibs", "original"); + rfs::symlink_dir("original", "mylibs"); + check("./mylibs"); +} + +fn check(library_path: &str) { + let out = rustc() + .input("multiple-candidates.rs") + .library_search_path(library_path) + .ui_testing() + .run_fail() + .stderr_utf8(); + diff() + .expected_file("multiple-candidates.stderr") + .normalize(r"\\", "/") + .actual_text("(rustc)", &out) + .run(); +} From 827047895a4c036f652b7105443f6305164f0e25 Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Wed, 16 Apr 2025 20:53:51 +0300 Subject: [PATCH 153/266] resolve config include FIXME Signed-off-by: onur-ozkan --- src/bootstrap/src/core/config/config.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index e15aab4ad506e..0c221abc9698d 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -814,9 +814,7 @@ impl Merge for TomlConfig { exit!(2); }); - // FIXME: Similar to `Config::parse_inner`, allow passing a custom `get_toml` from the caller to - // improve testability since `Config::get_toml` does nothing when `cfg(test)` is enabled. - let included_toml = Config::get_toml(&include_path).unwrap_or_else(|e| { + let included_toml = Config::get_toml_inner(&include_path).unwrap_or_else(|e| { eprintln!("ERROR: Failed to parse '{}': {e}", include_path.display()); exit!(2); }); @@ -1424,13 +1422,15 @@ impl Config { Self::get_toml(&builder_config_path) } - #[cfg(test)] - pub(crate) fn get_toml(_: &Path) -> Result { - Ok(TomlConfig::default()) + pub(crate) fn get_toml(file: &Path) -> Result { + #[cfg(test)] + return Ok(TomlConfig::default()); + + #[cfg(not(test))] + Self::get_toml_inner(file) } - #[cfg(not(test))] - pub(crate) fn get_toml(file: &Path) -> Result { + fn get_toml_inner(file: &Path) -> Result { let contents = t!(fs::read_to_string(file), format!("config file {} not found", file.display())); // Deserialize to Value and then TomlConfig to prevent the Deserialize impl of From b4b9cfbbd3d06b3b025205837a6e602dcf1e311b Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Wed, 16 Apr 2025 12:40:59 -0700 Subject: [PATCH 154/266] Upgrade to `rustc-rayon-core` 0.5.1 * [Fix a race with deadlock detection](https://github.com/rust-lang/rustc-rayon/pull/15) * [Cherry-pick changes from upstream rayon-core](https://github.com/rust-lang/rustc-rayon/pull/16) - This also removes a few dependencies from rustc's tidy list. --- Cargo.lock | 6 ++---- src/tools/tidy/src/deps.rs | 3 --- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3d0e294217912..684dfbca6f153 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3199,14 +3199,12 @@ dependencies = [ [[package]] name = "rustc-rayon-core" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67668daaf00e359c126f6dcb40d652d89b458a008c8afa727a42a2d20fca0b7f" +checksum = "2f42932dcd3bcbe484b38a3ccf79b7906fac41c02d408b5b1bac26da3416efdb" dependencies = [ - "crossbeam-channel", "crossbeam-deque", "crossbeam-utils", - "num_cpus", ] [[package]] diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 88c2a02798ace..13f85da46f781 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -259,7 +259,6 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "constant_time_eq", "cpufeatures", "crc32fast", - "crossbeam-channel", "crossbeam-deque", "crossbeam-epoch", "crossbeam-utils", @@ -294,7 +293,6 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "gimli", "gsgdt", "hashbrown", - "hermit-abi", "icu_list", "icu_list_data", "icu_locid", @@ -328,7 +326,6 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "miniz_oxide", "nix", "nu-ansi-term", - "num_cpus", "object", "odht", "once_cell", From 01cfa9aad5d8de34f968f41ef196e0cb0292a942 Mon Sep 17 00:00:00 2001 From: Obei Sideg Date: Tue, 8 Apr 2025 05:30:21 +0300 Subject: [PATCH 155/266] Add hard error for `extern` without explicit ABI --- compiler/rustc_ast_passes/messages.ftl | 4 ++++ compiler/rustc_ast_passes/src/ast_validation.rs | 12 +++++++----- compiler/rustc_ast_passes/src/errors.rs | 9 +++++++++ compiler/rustc_lint/messages.ftl | 2 +- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_ast_passes/messages.ftl b/compiler/rustc_ast_passes/messages.ftl index 25944392a52a9..80754a8f65a69 100644 --- a/compiler/rustc_ast_passes/messages.ftl +++ b/compiler/rustc_ast_passes/messages.ftl @@ -79,6 +79,10 @@ ast_passes_extern_types_cannot = `type`s inside `extern` blocks cannot have {$de .suggestion = remove the {$remove_descr} .label = `extern` block begins here +ast_passes_extern_without_abi = `extern` declarations without an explicit ABI are disallowed + .suggestion = specify an ABI + .help = prior to Rust 2024, a default ABI was inferred + ast_passes_feature_on_non_nightly = `#![feature]` may not be used on the {$channel} release channel .suggestion = remove the attribute .stable_since = the feature `{$name}` has been stable since `{$since}` and no longer requires an attribute to enable diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index dc77e7b283442..9a7b7daabbf1d 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -684,7 +684,7 @@ impl<'a> AstValidator<'a> { self.dcx().emit_err(errors::PatternFnPointer { span }); }); if let Extern::Implicit(extern_span) = bfty.ext { - self.maybe_lint_missing_abi(extern_span, ty.id); + self.handle_missing_abi(extern_span, ty.id); } } TyKind::TraitObject(bounds, ..) => { @@ -717,10 +717,12 @@ impl<'a> AstValidator<'a> { } } - fn maybe_lint_missing_abi(&mut self, span: Span, id: NodeId) { + fn handle_missing_abi(&mut self, span: Span, id: NodeId) { // FIXME(davidtwco): This is a hack to detect macros which produce spans of the // call site which do not have a macro backtrace. See #61963. - if self + if span.edition().at_least_edition_future() && self.features.explicit_extern_abis() { + self.dcx().emit_err(errors::MissingAbi { span }); + } else if self .sess .source_map() .span_to_snippet(span) @@ -996,7 +998,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } if abi.is_none() { - self.maybe_lint_missing_abi(*extern_span, item.id); + self.handle_missing_abi(*extern_span, item.id); } self.with_in_extern_mod(*safety, |this| { visit::walk_item(this, item); @@ -1370,7 +1372,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { }, ) = fk { - self.maybe_lint_missing_abi(*extern_span, id); + self.handle_missing_abi(*extern_span, id); } // Functions without bodies cannot have patterns. diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index 8e53e600f7ac6..2373a7d223e80 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -823,3 +823,12 @@ pub(crate) struct DuplicatePreciseCapturing { #[label] pub bound2: Span, } + +#[derive(Diagnostic)] +#[diag(ast_passes_extern_without_abi)] +#[help] +pub(crate) struct MissingAbi { + #[primary_span] + #[suggestion(code = "extern \"\"", applicability = "has-placeholders")] + pub span: Span, +} diff --git a/compiler/rustc_lint/messages.ftl b/compiler/rustc_lint/messages.ftl index 782d328a95102..60c183bd56b1f 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -271,7 +271,7 @@ lint_expectation = this lint expectation is unfulfilled lint_extern_crate_not_idiomatic = `extern crate` is not idiomatic in the new edition .suggestion = convert it to a `use` -lint_extern_without_abi = extern declarations without an explicit ABI are deprecated +lint_extern_without_abi = `extern` declarations without an explicit ABI are deprecated .label = ABI should be specified here .suggestion = explicitly specify the {$default_abi} ABI From d17c04e4a220d6f7bf170eeb0f90498e215555fa Mon Sep 17 00:00:00 2001 From: Obei Sideg Date: Tue, 8 Apr 2025 05:31:24 +0300 Subject: [PATCH 156/266] Add test for `extern` without explicit ABI --- ...re-gate-explicit-extern-abis.current.fixed | 45 +++++++++++++++++++ ...e-gate-explicit-extern-abis.current.stderr | 22 +++++++++ ...explicit-extern-abis.current_feature.fixed | 45 +++++++++++++++++++ ...xplicit-extern-abis.current_feature.stderr | 22 +++++++++ ...ure-gate-explicit-extern-abis.future.fixed | 45 +++++++++++++++++++ ...re-gate-explicit-extern-abis.future.stderr | 22 +++++++++ ...explicit-extern-abis.future_feature.stderr | 26 +++++++++++ .../feature-gate-explicit-extern-abis.rs | 45 +++++++++++++++++++ .../suggest-libname-only-1.rs | 2 +- .../suggest-libname-only-1.stderr | 2 +- .../suggest-libname-only-2.rs | 2 +- .../suggest-libname-only-2.stderr | 2 +- .../lint/cli-lint-override.forbid_warn.stderr | 2 +- .../cli-lint-override.force_warn_deny.stderr | 2 +- tests/ui/lint/cli-lint-override.rs | 6 +-- .../lint/cli-lint-override.warn_deny.stderr | 2 +- tests/ui/parser/bad-lit-suffixes.stderr | 4 +- tests/ui/parser/lit-err-in-macro.stderr | 2 +- tests/ui/proc-macro/inner-attrs.rs | 2 +- tests/ui/proc-macro/inner-attrs.stderr | 2 +- 20 files changed, 287 insertions(+), 15 deletions(-) create mode 100644 tests/ui/feature-gates/feature-gate-explicit-extern-abis.current.fixed create mode 100644 tests/ui/feature-gates/feature-gate-explicit-extern-abis.current.stderr create mode 100644 tests/ui/feature-gates/feature-gate-explicit-extern-abis.current_feature.fixed create mode 100644 tests/ui/feature-gates/feature-gate-explicit-extern-abis.current_feature.stderr create mode 100644 tests/ui/feature-gates/feature-gate-explicit-extern-abis.future.fixed create mode 100644 tests/ui/feature-gates/feature-gate-explicit-extern-abis.future.stderr create mode 100644 tests/ui/feature-gates/feature-gate-explicit-extern-abis.future_feature.stderr create mode 100644 tests/ui/feature-gates/feature-gate-explicit-extern-abis.rs diff --git a/tests/ui/feature-gates/feature-gate-explicit-extern-abis.current.fixed b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.current.fixed new file mode 100644 index 0000000000000..525f78d162fc0 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.current.fixed @@ -0,0 +1,45 @@ +// The purpose of this feature gate is to make something into a hard error in a +// future edition. Consequently, this test differs from most other feature gate +// tests. Instead of verifying that an error occurs when the feature gate is +// missing, it ensures that the hard error is only produced with the feature +// gate is present in the `future` edition -- and otherwise that only a warning +// is emitted. + +//@ revisions: current current_feature future future_feature + +//@ [current] run-rustfix +//@ [current] check-pass + +//@ [current_feature] run-rustfix +//@ [current_feature] check-pass + +//@ [future] edition: future +//@ [future] compile-flags: -Z unstable-options +//@ [future] run-rustfix +//@ [future] check-pass + +//@ [future_feature] edition: future +//@ [future_feature] compile-flags: -Z unstable-options + +#![cfg_attr(future_feature, feature(explicit_extern_abis))] +#![cfg_attr(current_feature, feature(explicit_extern_abis))] + +extern "C" fn _foo() {} +//[current]~^ WARN `extern` declarations without an explicit ABI are deprecated +//[current_feature]~^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future]~^^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future_feature]~^^^^ ERROR `extern` declarations without an explicit ABI are disallowed + +unsafe extern "C" fn _bar() {} +//[current]~^ WARN `extern` declarations without an explicit ABI are deprecated +//[current_feature]~^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future]~^^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future_feature]~^^^^ ERROR `extern` declarations without an explicit ABI are disallowed + +unsafe extern "C" {} +//[current]~^ WARN `extern` declarations without an explicit ABI are deprecated +//[current_feature]~^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future]~^^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future_feature]~^^^^ ERROR `extern` declarations without an explicit ABI are disallowed + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-explicit-extern-abis.current.stderr b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.current.stderr new file mode 100644 index 0000000000000..cf927807c7c3c --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.current.stderr @@ -0,0 +1,22 @@ +warning: `extern` declarations without an explicit ABI are deprecated + --> $DIR/feature-gate-explicit-extern-abis.rs:27:1 + | +LL | extern fn _foo() {} + | ^^^^^^ help: explicitly specify the "C" ABI: `extern "C"` + | + = note: `#[warn(missing_abi)]` on by default + +warning: `extern` declarations without an explicit ABI are deprecated + --> $DIR/feature-gate-explicit-extern-abis.rs:33:8 + | +LL | unsafe extern fn _bar() {} + | ^^^^^^ help: explicitly specify the "C" ABI: `extern "C"` + +warning: `extern` declarations without an explicit ABI are deprecated + --> $DIR/feature-gate-explicit-extern-abis.rs:39:8 + | +LL | unsafe extern {} + | ^^^^^^ help: explicitly specify the "C" ABI: `extern "C"` + +warning: 3 warnings emitted + diff --git a/tests/ui/feature-gates/feature-gate-explicit-extern-abis.current_feature.fixed b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.current_feature.fixed new file mode 100644 index 0000000000000..525f78d162fc0 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.current_feature.fixed @@ -0,0 +1,45 @@ +// The purpose of this feature gate is to make something into a hard error in a +// future edition. Consequently, this test differs from most other feature gate +// tests. Instead of verifying that an error occurs when the feature gate is +// missing, it ensures that the hard error is only produced with the feature +// gate is present in the `future` edition -- and otherwise that only a warning +// is emitted. + +//@ revisions: current current_feature future future_feature + +//@ [current] run-rustfix +//@ [current] check-pass + +//@ [current_feature] run-rustfix +//@ [current_feature] check-pass + +//@ [future] edition: future +//@ [future] compile-flags: -Z unstable-options +//@ [future] run-rustfix +//@ [future] check-pass + +//@ [future_feature] edition: future +//@ [future_feature] compile-flags: -Z unstable-options + +#![cfg_attr(future_feature, feature(explicit_extern_abis))] +#![cfg_attr(current_feature, feature(explicit_extern_abis))] + +extern "C" fn _foo() {} +//[current]~^ WARN `extern` declarations without an explicit ABI are deprecated +//[current_feature]~^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future]~^^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future_feature]~^^^^ ERROR `extern` declarations without an explicit ABI are disallowed + +unsafe extern "C" fn _bar() {} +//[current]~^ WARN `extern` declarations without an explicit ABI are deprecated +//[current_feature]~^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future]~^^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future_feature]~^^^^ ERROR `extern` declarations without an explicit ABI are disallowed + +unsafe extern "C" {} +//[current]~^ WARN `extern` declarations without an explicit ABI are deprecated +//[current_feature]~^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future]~^^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future_feature]~^^^^ ERROR `extern` declarations without an explicit ABI are disallowed + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-explicit-extern-abis.current_feature.stderr b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.current_feature.stderr new file mode 100644 index 0000000000000..cf927807c7c3c --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.current_feature.stderr @@ -0,0 +1,22 @@ +warning: `extern` declarations without an explicit ABI are deprecated + --> $DIR/feature-gate-explicit-extern-abis.rs:27:1 + | +LL | extern fn _foo() {} + | ^^^^^^ help: explicitly specify the "C" ABI: `extern "C"` + | + = note: `#[warn(missing_abi)]` on by default + +warning: `extern` declarations without an explicit ABI are deprecated + --> $DIR/feature-gate-explicit-extern-abis.rs:33:8 + | +LL | unsafe extern fn _bar() {} + | ^^^^^^ help: explicitly specify the "C" ABI: `extern "C"` + +warning: `extern` declarations without an explicit ABI are deprecated + --> $DIR/feature-gate-explicit-extern-abis.rs:39:8 + | +LL | unsafe extern {} + | ^^^^^^ help: explicitly specify the "C" ABI: `extern "C"` + +warning: 3 warnings emitted + diff --git a/tests/ui/feature-gates/feature-gate-explicit-extern-abis.future.fixed b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.future.fixed new file mode 100644 index 0000000000000..525f78d162fc0 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.future.fixed @@ -0,0 +1,45 @@ +// The purpose of this feature gate is to make something into a hard error in a +// future edition. Consequently, this test differs from most other feature gate +// tests. Instead of verifying that an error occurs when the feature gate is +// missing, it ensures that the hard error is only produced with the feature +// gate is present in the `future` edition -- and otherwise that only a warning +// is emitted. + +//@ revisions: current current_feature future future_feature + +//@ [current] run-rustfix +//@ [current] check-pass + +//@ [current_feature] run-rustfix +//@ [current_feature] check-pass + +//@ [future] edition: future +//@ [future] compile-flags: -Z unstable-options +//@ [future] run-rustfix +//@ [future] check-pass + +//@ [future_feature] edition: future +//@ [future_feature] compile-flags: -Z unstable-options + +#![cfg_attr(future_feature, feature(explicit_extern_abis))] +#![cfg_attr(current_feature, feature(explicit_extern_abis))] + +extern "C" fn _foo() {} +//[current]~^ WARN `extern` declarations without an explicit ABI are deprecated +//[current_feature]~^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future]~^^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future_feature]~^^^^ ERROR `extern` declarations without an explicit ABI are disallowed + +unsafe extern "C" fn _bar() {} +//[current]~^ WARN `extern` declarations without an explicit ABI are deprecated +//[current_feature]~^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future]~^^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future_feature]~^^^^ ERROR `extern` declarations without an explicit ABI are disallowed + +unsafe extern "C" {} +//[current]~^ WARN `extern` declarations without an explicit ABI are deprecated +//[current_feature]~^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future]~^^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future_feature]~^^^^ ERROR `extern` declarations without an explicit ABI are disallowed + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-explicit-extern-abis.future.stderr b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.future.stderr new file mode 100644 index 0000000000000..cf927807c7c3c --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.future.stderr @@ -0,0 +1,22 @@ +warning: `extern` declarations without an explicit ABI are deprecated + --> $DIR/feature-gate-explicit-extern-abis.rs:27:1 + | +LL | extern fn _foo() {} + | ^^^^^^ help: explicitly specify the "C" ABI: `extern "C"` + | + = note: `#[warn(missing_abi)]` on by default + +warning: `extern` declarations without an explicit ABI are deprecated + --> $DIR/feature-gate-explicit-extern-abis.rs:33:8 + | +LL | unsafe extern fn _bar() {} + | ^^^^^^ help: explicitly specify the "C" ABI: `extern "C"` + +warning: `extern` declarations without an explicit ABI are deprecated + --> $DIR/feature-gate-explicit-extern-abis.rs:39:8 + | +LL | unsafe extern {} + | ^^^^^^ help: explicitly specify the "C" ABI: `extern "C"` + +warning: 3 warnings emitted + diff --git a/tests/ui/feature-gates/feature-gate-explicit-extern-abis.future_feature.stderr b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.future_feature.stderr new file mode 100644 index 0000000000000..096a6f4341699 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.future_feature.stderr @@ -0,0 +1,26 @@ +error: `extern` declarations without an explicit ABI are disallowed + --> $DIR/feature-gate-explicit-extern-abis.rs:27:1 + | +LL | extern fn _foo() {} + | ^^^^^^ help: specify an ABI: `extern ""` + | + = help: prior to Rust 2024, a default ABI was inferred + +error: `extern` declarations without an explicit ABI are disallowed + --> $DIR/feature-gate-explicit-extern-abis.rs:33:8 + | +LL | unsafe extern fn _bar() {} + | ^^^^^^ help: specify an ABI: `extern ""` + | + = help: prior to Rust 2024, a default ABI was inferred + +error: `extern` declarations without an explicit ABI are disallowed + --> $DIR/feature-gate-explicit-extern-abis.rs:39:8 + | +LL | unsafe extern {} + | ^^^^^^ help: specify an ABI: `extern ""` + | + = help: prior to Rust 2024, a default ABI was inferred + +error: aborting due to 3 previous errors + diff --git a/tests/ui/feature-gates/feature-gate-explicit-extern-abis.rs b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.rs new file mode 100644 index 0000000000000..379c45f589907 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-explicit-extern-abis.rs @@ -0,0 +1,45 @@ +// The purpose of this feature gate is to make something into a hard error in a +// future edition. Consequently, this test differs from most other feature gate +// tests. Instead of verifying that an error occurs when the feature gate is +// missing, it ensures that the hard error is only produced with the feature +// gate is present in the `future` edition -- and otherwise that only a warning +// is emitted. + +//@ revisions: current current_feature future future_feature + +//@ [current] run-rustfix +//@ [current] check-pass + +//@ [current_feature] run-rustfix +//@ [current_feature] check-pass + +//@ [future] edition: future +//@ [future] compile-flags: -Z unstable-options +//@ [future] run-rustfix +//@ [future] check-pass + +//@ [future_feature] edition: future +//@ [future_feature] compile-flags: -Z unstable-options + +#![cfg_attr(future_feature, feature(explicit_extern_abis))] +#![cfg_attr(current_feature, feature(explicit_extern_abis))] + +extern fn _foo() {} +//[current]~^ WARN `extern` declarations without an explicit ABI are deprecated +//[current_feature]~^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future]~^^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future_feature]~^^^^ ERROR `extern` declarations without an explicit ABI are disallowed + +unsafe extern fn _bar() {} +//[current]~^ WARN `extern` declarations without an explicit ABI are deprecated +//[current_feature]~^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future]~^^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future_feature]~^^^^ ERROR `extern` declarations without an explicit ABI are disallowed + +unsafe extern {} +//[current]~^ WARN `extern` declarations without an explicit ABI are deprecated +//[current_feature]~^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future]~^^^ WARN `extern` declarations without an explicit ABI are deprecated +//[future_feature]~^^^^ ERROR `extern` declarations without an explicit ABI are disallowed + +fn main() {} diff --git a/tests/ui/link-native-libs/suggest-libname-only-1.rs b/tests/ui/link-native-libs/suggest-libname-only-1.rs index c69949d1fdb36..8699e4819e623 100644 --- a/tests/ui/link-native-libs/suggest-libname-only-1.rs +++ b/tests/ui/link-native-libs/suggest-libname-only-1.rs @@ -2,7 +2,7 @@ //@ compile-flags: --crate-type rlib #[link(name = "libfoo.a", kind = "static")] -extern { } //~ WARN extern declarations without an explicit ABI are deprecated +extern { } //~ WARN `extern` declarations without an explicit ABI are deprecated //~| HELP explicitly specify the "C" ABI pub fn main() { } diff --git a/tests/ui/link-native-libs/suggest-libname-only-1.stderr b/tests/ui/link-native-libs/suggest-libname-only-1.stderr index 0320294a8004b..59bd99f619a0f 100644 --- a/tests/ui/link-native-libs/suggest-libname-only-1.stderr +++ b/tests/ui/link-native-libs/suggest-libname-only-1.stderr @@ -1,4 +1,4 @@ -warning: extern declarations without an explicit ABI are deprecated +warning: `extern` declarations without an explicit ABI are deprecated --> $DIR/suggest-libname-only-1.rs:5:1 | LL | extern { } diff --git a/tests/ui/link-native-libs/suggest-libname-only-2.rs b/tests/ui/link-native-libs/suggest-libname-only-2.rs index d5150c327cd5e..87373f563d090 100644 --- a/tests/ui/link-native-libs/suggest-libname-only-2.rs +++ b/tests/ui/link-native-libs/suggest-libname-only-2.rs @@ -2,7 +2,7 @@ //@ compile-flags: --crate-type rlib #[link(name = "bar.lib", kind = "static")] -extern { } //~ WARN extern declarations without an explicit ABI are deprecated +extern { } //~ WARN `extern` declarations without an explicit ABI are deprecated //~| HELP explicitly specify the "C" ABI pub fn main() { } diff --git a/tests/ui/link-native-libs/suggest-libname-only-2.stderr b/tests/ui/link-native-libs/suggest-libname-only-2.stderr index e492aea27b455..298a9ced17076 100644 --- a/tests/ui/link-native-libs/suggest-libname-only-2.stderr +++ b/tests/ui/link-native-libs/suggest-libname-only-2.stderr @@ -1,4 +1,4 @@ -warning: extern declarations without an explicit ABI are deprecated +warning: `extern` declarations without an explicit ABI are deprecated --> $DIR/suggest-libname-only-2.rs:5:1 | LL | extern { } diff --git a/tests/ui/lint/cli-lint-override.forbid_warn.stderr b/tests/ui/lint/cli-lint-override.forbid_warn.stderr index fb8779ad4f15d..fe3437ae3d752 100644 --- a/tests/ui/lint/cli-lint-override.forbid_warn.stderr +++ b/tests/ui/lint/cli-lint-override.forbid_warn.stderr @@ -1,4 +1,4 @@ -error: extern declarations without an explicit ABI are deprecated +error: `extern` declarations without an explicit ABI are deprecated --> $DIR/cli-lint-override.rs:12:1 | LL | extern fn foo() {} diff --git a/tests/ui/lint/cli-lint-override.force_warn_deny.stderr b/tests/ui/lint/cli-lint-override.force_warn_deny.stderr index 10fc13e3f52f8..f48fca4bd9f37 100644 --- a/tests/ui/lint/cli-lint-override.force_warn_deny.stderr +++ b/tests/ui/lint/cli-lint-override.force_warn_deny.stderr @@ -1,4 +1,4 @@ -warning: extern declarations without an explicit ABI are deprecated +warning: `extern` declarations without an explicit ABI are deprecated --> $DIR/cli-lint-override.rs:12:1 | LL | extern fn foo() {} diff --git a/tests/ui/lint/cli-lint-override.rs b/tests/ui/lint/cli-lint-override.rs index 4b3fd0d9c01c9..b733872166aa2 100644 --- a/tests/ui/lint/cli-lint-override.rs +++ b/tests/ui/lint/cli-lint-override.rs @@ -10,8 +10,8 @@ extern fn foo() {} -//[warn_deny]~^ ERROR extern declarations without an explicit ABI are deprecated -//[forbid_warn]~^^ ERROR extern declarations without an explicit ABI are deprecated -//[force_warn_deny]~^^^ WARN extern declarations without an explicit ABI are deprecated +//[warn_deny]~^ ERROR `extern` declarations without an explicit ABI are deprecated +//[forbid_warn]~^^ ERROR `extern` declarations without an explicit ABI are deprecated +//[force_warn_deny]~^^^ WARN `extern` declarations without an explicit ABI are deprecated fn main() {} diff --git a/tests/ui/lint/cli-lint-override.warn_deny.stderr b/tests/ui/lint/cli-lint-override.warn_deny.stderr index 979ca22324f1e..91baad1f9f870 100644 --- a/tests/ui/lint/cli-lint-override.warn_deny.stderr +++ b/tests/ui/lint/cli-lint-override.warn_deny.stderr @@ -1,4 +1,4 @@ -error: extern declarations without an explicit ABI are deprecated +error: `extern` declarations without an explicit ABI are deprecated --> $DIR/cli-lint-override.rs:12:1 | LL | extern fn foo() {} diff --git a/tests/ui/parser/bad-lit-suffixes.stderr b/tests/ui/parser/bad-lit-suffixes.stderr index d6b50b0e0d1fe..86ef35bf7833f 100644 --- a/tests/ui/parser/bad-lit-suffixes.stderr +++ b/tests/ui/parser/bad-lit-suffixes.stderr @@ -51,7 +51,7 @@ LL | #[rustc_layout_scalar_valid_range_start(0suffix)] | = help: the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.) -warning: extern declarations without an explicit ABI are deprecated +warning: `extern` declarations without an explicit ABI are deprecated --> $DIR/bad-lit-suffixes.rs:3:1 | LL | extern @@ -59,7 +59,7 @@ LL | extern | = note: `#[warn(missing_abi)]` on by default -warning: extern declarations without an explicit ABI are deprecated +warning: `extern` declarations without an explicit ABI are deprecated --> $DIR/bad-lit-suffixes.rs:7:1 | LL | extern diff --git a/tests/ui/parser/lit-err-in-macro.stderr b/tests/ui/parser/lit-err-in-macro.stderr index 9422f22f9c8fe..08fe58643d40a 100644 --- a/tests/ui/parser/lit-err-in-macro.stderr +++ b/tests/ui/parser/lit-err-in-macro.stderr @@ -4,7 +4,7 @@ error: suffixes on string literals are invalid LL | f!("Foo"__); | ^^^^^^^ invalid suffix `__` -warning: extern declarations without an explicit ABI are deprecated +warning: `extern` declarations without an explicit ABI are deprecated --> $DIR/lit-err-in-macro.rs:3:9 | LL | extern $abi fn f() {} diff --git a/tests/ui/proc-macro/inner-attrs.rs b/tests/ui/proc-macro/inner-attrs.rs index c541e93f9041d..ca4b2029a3384 100644 --- a/tests/ui/proc-macro/inner-attrs.rs +++ b/tests/ui/proc-macro/inner-attrs.rs @@ -82,7 +82,7 @@ fn bar() { } -extern { //~ WARN extern declarations without an explicit ABI are deprecated +extern { //~ WARN `extern` declarations without an explicit ABI are deprecated fn weird_extern() { #![print_target_and_args_consume(tenth)] } diff --git a/tests/ui/proc-macro/inner-attrs.stderr b/tests/ui/proc-macro/inner-attrs.stderr index 4e7825c0d007c..54cccae8da082 100644 --- a/tests/ui/proc-macro/inner-attrs.stderr +++ b/tests/ui/proc-macro/inner-attrs.stderr @@ -22,7 +22,7 @@ error: expected non-macro inner attribute, found attribute macro `print_attr` LL | #![print_attr] | ^^^^^^^^^^ not a non-macro inner attribute -warning: extern declarations without an explicit ABI are deprecated +warning: `extern` declarations without an explicit ABI are deprecated --> $DIR/inner-attrs.rs:85:1 | LL | extern { From 3863018d960ad8bf6dd631f31f9d487e4a9880f1 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 16 Apr 2025 19:47:56 +0000 Subject: [PATCH 157/266] Fix replacing supertrait aliases in ReplaceProjectionWith --- .../src/solve/assembly/mod.rs | 24 +-- .../src/solve/assembly/structural_traits.rs | 157 ++++++++++++------ .../src/solve/trait_goals.rs | 2 +- .../src/solve/inspect/analyse.rs | 8 +- .../rustc_trait_selection/src/solve/select.rs | 2 +- compiler/rustc_type_ir/src/solve/inspect.rs | 10 +- .../traits/next-solver/supertrait-alias-1.rs | 22 +++ .../traits/next-solver/supertrait-alias-2.rs | 25 +++ .../traits/next-solver/supertrait-alias-3.rs | 32 ++++ .../traits/next-solver/supertrait-alias-4.rs | 24 +++ 10 files changed, 238 insertions(+), 68 deletions(-) create mode 100644 tests/ui/traits/next-solver/supertrait-alias-1.rs create mode 100644 tests/ui/traits/next-solver/supertrait-alias-2.rs create mode 100644 tests/ui/traits/next-solver/supertrait-alias-3.rs create mode 100644 tests/ui/traits/next-solver/supertrait-alias-4.rs diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs index ee000b1174866..83b2465d05aa7 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs @@ -92,16 +92,20 @@ where let ty::Dynamic(bounds, _, _) = goal.predicate.self_ty().kind() else { panic!("expected object type in `probe_and_consider_object_bound_candidate`"); }; - ecx.add_goals( - GoalSource::ImplWhereBound, - structural_traits::predicates_for_object_candidate( - ecx, - goal.param_env, - goal.predicate.trait_ref(cx), - bounds, - ), - ); - ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) + match structural_traits::predicates_for_object_candidate( + ecx, + goal.param_env, + goal.predicate.trait_ref(cx), + bounds, + ) { + Ok(requirements) => { + ecx.add_goals(GoalSource::ImplWhereBound, requirements); + ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) + } + Err(_) => { + ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS) + } + } }) } diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs index c2fb592c3f3aa..46ec8897fa5ec 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs @@ -5,9 +5,10 @@ use derive_where::derive_where; use rustc_type_ir::data_structures::HashMap; use rustc_type_ir::inherent::*; use rustc_type_ir::lang_items::TraitSolverLangItem; +use rustc_type_ir::solve::inspect::ProbeKind; use rustc_type_ir::{ - self as ty, Interner, Movability, Mutability, TypeFoldable, TypeFolder, TypeSuperFoldable, - Upcast as _, elaborate, + self as ty, FallibleTypeFolder, Interner, Movability, Mutability, TypeFoldable, + TypeSuperFoldable, Upcast as _, elaborate, }; use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; use tracing::instrument; @@ -822,7 +823,7 @@ pub(in crate::solve) fn const_conditions_for_destruct( /// impl Baz for dyn Foo {} /// ``` /// -/// However, in order to make such impls well-formed, we need to do an +/// However, in order to make such impls non-cyclical, we need to do an /// additional step of eagerly folding the associated types in the where /// clauses of the impl. In this example, that means replacing /// `::Bar` with `Ty` in the first impl. @@ -833,11 +834,11 @@ pub(in crate::solve) fn const_conditions_for_destruct( // normalize eagerly here. See https://github.com/lcnr/solver-woes/issues/9 // for more details. pub(in crate::solve) fn predicates_for_object_candidate( - ecx: &EvalCtxt<'_, D>, + ecx: &mut EvalCtxt<'_, D>, param_env: I::ParamEnv, trait_ref: ty::TraitRef, object_bounds: I::BoundExistentialPredicates, -) -> Vec> +) -> Result>, Ambiguous> where D: SolverDelegate, I: Interner, @@ -871,72 +872,130 @@ where .extend(cx.item_bounds(associated_type_def_id).iter_instantiated(cx, trait_ref.args)); } - let mut replace_projection_with = HashMap::default(); + let mut replace_projection_with: HashMap<_, Vec<_>> = HashMap::default(); for bound in object_bounds.iter() { if let ty::ExistentialPredicate::Projection(proj) = bound.skip_binder() { + // FIXME: We *probably* should replace this with a dummy placeholder, + // b/c don't want to replace literal instances of this dyn type that + // show up in the bounds, but just ones that come from substituting + // `Self` with the dyn type. let proj = proj.with_self_ty(cx, trait_ref.self_ty()); - let old_ty = replace_projection_with.insert(proj.def_id(), bound.rebind(proj)); - assert_eq!( - old_ty, - None, - "{:?} has two generic parameters: {:?} and {:?}", - proj.projection_term, - proj.term, - old_ty.unwrap() - ); + replace_projection_with.entry(proj.def_id()).or_default().push(bound.rebind(proj)); } } - let mut folder = - ReplaceProjectionWith { ecx, param_env, mapping: replace_projection_with, nested: vec![] }; - let folded_requirements = requirements.fold_with(&mut folder); + let mut folder = ReplaceProjectionWith { + ecx, + param_env, + self_ty: trait_ref.self_ty(), + mapping: &replace_projection_with, + nested: vec![], + }; - folder + let requirements = requirements.try_fold_with(&mut folder)?; + Ok(folder .nested .into_iter() - .chain(folded_requirements.into_iter().map(|clause| Goal::new(cx, param_env, clause))) - .collect() + .chain(requirements.into_iter().map(|clause| Goal::new(cx, param_env, clause))) + .collect()) } -struct ReplaceProjectionWith<'a, D: SolverDelegate, I: Interner> { - ecx: &'a EvalCtxt<'a, D>, +struct ReplaceProjectionWith<'a, 'b, I: Interner, D: SolverDelegate> { + ecx: &'a mut EvalCtxt<'b, D>, param_env: I::ParamEnv, - mapping: HashMap>>, + self_ty: I::Ty, + mapping: &'a HashMap>>>, nested: Vec>, } -impl, I: Interner> TypeFolder - for ReplaceProjectionWith<'_, D, I> +impl ReplaceProjectionWith<'_, '_, I, D> +where + D: SolverDelegate, + I: Interner, +{ + fn projection_may_match( + &mut self, + source_projection: ty::Binder>, + target_projection: ty::AliasTerm, + ) -> bool { + source_projection.item_def_id() == target_projection.def_id + && self + .ecx + .probe(|_| ProbeKind::ProjectionCompatibility) + .enter(|ecx| -> Result<_, NoSolution> { + let source_projection = ecx.instantiate_binder_with_infer(source_projection); + ecx.eq(self.param_env, source_projection.projection_term, target_projection)?; + ecx.try_evaluate_added_goals() + }) + .is_ok() + } + + /// Try to replace an alias with the term present in the projection bounds of the self type. + /// Returns `Ok` if this alias is not eligible to be replaced, or bail with + /// `Err(Ambiguous)` if it's uncertain which projection bound to replace the term with due + /// to multiple bounds applying. + fn try_eagerly_replace_alias( + &mut self, + alias_term: ty::AliasTerm, + ) -> Result, Ambiguous> { + if alias_term.self_ty() != self.self_ty { + return Ok(None); + } + + let Some(replacements) = self.mapping.get(&alias_term.def_id) else { + return Ok(None); + }; + + // This is quite similar to the `projection_may_match` we use in unsizing, + // but here we want to unify a projection predicate against an alias term + // so we can replace it with the the projection predicate's term. + let mut matching_projections = replacements + .iter() + .filter(|source_projection| self.projection_may_match(**source_projection, alias_term)); + let Some(replacement) = matching_projections.next() else { + // This shouldn't happen. + panic!("could not replace {alias_term:?} with term from from {:?}", self.self_ty); + }; + // FIXME: This *may* have issues with duplicated projections. + if matching_projections.next().is_some() { + // If there's more than one projection that we can unify here, then we + // need to stall until inference constrains things so that there's only + // one choice. + return Err(Ambiguous); + } + + let replacement = self.ecx.instantiate_binder_with_infer(*replacement); + self.nested.extend( + self.ecx + .eq_and_get_goals(self.param_env, alias_term, replacement.projection_term) + .expect("expected to be able to unify goal projection with dyn's projection"), + ); + + Ok(Some(replacement.term)) + } +} + +/// Marker for bailing with ambiguity. +pub(crate) struct Ambiguous; + +impl FallibleTypeFolder for ReplaceProjectionWith<'_, '_, I, D> +where + D: SolverDelegate, + I: Interner, { + type Error = Ambiguous; + fn cx(&self) -> I { self.ecx.cx() } - fn fold_ty(&mut self, ty: I::Ty) -> I::Ty { + fn try_fold_ty(&mut self, ty: I::Ty) -> Result { if let ty::Alias(ty::Projection, alias_ty) = ty.kind() { - if let Some(replacement) = self.mapping.get(&alias_ty.def_id) { - // We may have a case where our object type's projection bound is higher-ranked, - // but the where clauses we instantiated are not. We can solve this by instantiating - // the binder at the usage site. - let proj = self.ecx.instantiate_binder_with_infer(*replacement); - // FIXME: Technically this equate could be fallible... - self.nested.extend( - self.ecx - .eq_and_get_goals( - self.param_env, - alias_ty, - proj.projection_term.expect_ty(self.ecx.cx()), - ) - .expect( - "expected to be able to unify goal projection with dyn's projection", - ), - ); - proj.term.expect_ty() - } else { - ty.super_fold_with(self) + if let Some(term) = self.try_eagerly_replace_alias(alias_ty.into())? { + return Ok(term.expect_ty()); } - } else { - ty.super_fold_with(self) } + + ty.try_super_fold_with(self) } } diff --git a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs index 9262da2906d08..409af8568d7a3 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -944,7 +944,7 @@ where target_projection: ty::Binder>| { source_projection.item_def_id() == target_projection.item_def_id() && ecx - .probe(|_| ProbeKind::UpcastProjectionCompatibility) + .probe(|_| ProbeKind::ProjectionCompatibility) .enter(|ecx| -> Result<_, NoSolution> { ecx.enter_forall(target_projection, |ecx, target_projection| { let source_projection = diff --git a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs index 48a05ad29fbd9..24b87000e32bc 100644 --- a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs +++ b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs @@ -292,7 +292,7 @@ impl<'a, 'tcx> InspectGoal<'a, 'tcx> { inspect::ProbeStep::NestedProbe(ref probe) => { match probe.kind { // These never assemble candidates for the goal we're trying to solve. - inspect::ProbeKind::UpcastProjectionCompatibility + inspect::ProbeKind::ProjectionCompatibility | inspect::ProbeKind::ShadowedEnvProbing => continue, inspect::ProbeKind::NormalizedSelfTyAssembly @@ -314,8 +314,10 @@ impl<'a, 'tcx> InspectGoal<'a, 'tcx> { } match probe.kind { - inspect::ProbeKind::UpcastProjectionCompatibility - | inspect::ProbeKind::ShadowedEnvProbing => bug!(), + inspect::ProbeKind::ProjectionCompatibility + | inspect::ProbeKind::ShadowedEnvProbing => { + bug!() + } inspect::ProbeKind::NormalizedSelfTyAssembly | inspect::ProbeKind::UnsizeAssembly => {} diff --git a/compiler/rustc_trait_selection/src/solve/select.rs b/compiler/rustc_trait_selection/src/solve/select.rs index 4437fc5b0295f..4fdaf740287ba 100644 --- a/compiler/rustc_trait_selection/src/solve/select.rs +++ b/compiler/rustc_trait_selection/src/solve/select.rs @@ -177,7 +177,7 @@ fn to_selection<'tcx>( }, ProbeKind::NormalizedSelfTyAssembly | ProbeKind::UnsizeAssembly - | ProbeKind::UpcastProjectionCompatibility + | ProbeKind::ProjectionCompatibility | ProbeKind::OpaqueTypeStorageLookup { result: _ } | ProbeKind::Root { result: _ } | ProbeKind::ShadowedEnvProbing diff --git a/compiler/rustc_type_ir/src/solve/inspect.rs b/compiler/rustc_type_ir/src/solve/inspect.rs index 18fb71dd290e7..b10641b287d4a 100644 --- a/compiler/rustc_type_ir/src/solve/inspect.rs +++ b/compiler/rustc_type_ir/src/solve/inspect.rs @@ -118,10 +118,12 @@ pub enum ProbeKind { /// Used in the probe that wraps normalizing the non-self type for the unsize /// trait, which is also structurally matched on. UnsizeAssembly, - /// During upcasting from some source object to target object type, used to - /// do a probe to find out what projection type(s) may be used to prove that - /// the source type upholds all of the target type's object bounds. - UpcastProjectionCompatibility, + /// Used to do a probe to find out what projection type(s) match a given + /// alias bound or projection predicate. For trait upcasting, this is used + /// to prove that the source type upholds all of the target type's object + /// bounds. For object type bounds, this is used when eagerly replacing + /// supertrait aliases. + ProjectionCompatibility, /// Looking for param-env candidates that satisfy the trait ref for a projection. ShadowedEnvProbing, /// Try to unify an opaque type with an existing key in the storage. diff --git a/tests/ui/traits/next-solver/supertrait-alias-1.rs b/tests/ui/traits/next-solver/supertrait-alias-1.rs new file mode 100644 index 0000000000000..579a44677c2ee --- /dev/null +++ b/tests/ui/traits/next-solver/supertrait-alias-1.rs @@ -0,0 +1,22 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +// Regression test for . +// Tests that we don't try to replace `::Output` when replacing projections in the +// required bounds for `dyn Trait`, b/c `V` is not relevant to the dyn type, which we were +// previously encountering b/c we were walking into the existential projection bounds of the dyn +// type itself. + +pub trait Trait: Super {} + +pub trait Super { + type Output; +} + +fn bound() {} + +fn visit_simd_operator() { + bound::::Output>>(); +} + +fn main() {} diff --git a/tests/ui/traits/next-solver/supertrait-alias-2.rs b/tests/ui/traits/next-solver/supertrait-alias-2.rs new file mode 100644 index 0000000000000..a0f3e038dca63 --- /dev/null +++ b/tests/ui/traits/next-solver/supertrait-alias-2.rs @@ -0,0 +1,25 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +// Regression test for . +// Tests that we don't try to replace `::Assoc` when replacing projections in the +// required bounds for `dyn Foo`, b/c `T` is not relevant to the dyn type, which we were +// encountering when walking through the elaborated supertraits of `dyn Foo`. + +trait Other {} + +trait Foo>: Other<>::Assoc> { + type Assoc; +} + +impl Foo for T { + type Assoc = (); +} + +impl Other<()> for T {} + +fn is_foo + ?Sized>() {} + +fn main() { + is_foo::>(); +} diff --git a/tests/ui/traits/next-solver/supertrait-alias-3.rs b/tests/ui/traits/next-solver/supertrait-alias-3.rs new file mode 100644 index 0000000000000..78182bbc41568 --- /dev/null +++ b/tests/ui/traits/next-solver/supertrait-alias-3.rs @@ -0,0 +1,32 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +// Regression test for . +// Exercises a case where structural equality is insufficient when replacing projections in a dyn's +// bounds. In this case, the bound will contain `:Assoc>::Assoc`, but +// the existential projections from the dyn will have `>::Assoc` because as an +// optimization we eagerly normalize aliases in goals. + +trait Other {} +impl Other for T {} + +trait Super { + type Assoc; +} + +trait Mirror { + type Assoc; +} +impl Mirror for T { + type Assoc = T; +} + +trait Foo: Super<::Assoc, Assoc = A> { + type FooAssoc: Other<::Assoc>>::Assoc>; +} + +fn is_foo + ?Sized, T, U>() {} + +fn main() { + is_foo::, _, _>(); +} diff --git a/tests/ui/traits/next-solver/supertrait-alias-4.rs b/tests/ui/traits/next-solver/supertrait-alias-4.rs new file mode 100644 index 0000000000000..919a768fcf281 --- /dev/null +++ b/tests/ui/traits/next-solver/supertrait-alias-4.rs @@ -0,0 +1,24 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +// Exercises the ambiguity that comes from replacing the associated types within the bounds +// that are required for a `impl Trait for dyn Trait` built-in object impl to hold. + +trait Sup { + type Assoc; +} + +trait Foo: Sup + Sup { + type Other: Bar<>::Assoc>; +} + +trait Bar {} +impl Bar for () {} + +fn foo(x: &(impl Foo + ?Sized)) {} + +fn main() { + let x: &dyn Foo<_, _, Other = ()> = todo!(); + foo(x); + let y: &dyn Foo = x; +} From e1936d22ed6c686bc9f2c92634fba9246bd86b9d Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 14 Apr 2025 20:57:46 +0000 Subject: [PATCH 158/266] Remove FIXME that is no longer relevant --- .../src/solve/assembly/structural_traits.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs index 46ec8897fa5ec..1526049719ea0 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs @@ -827,12 +827,6 @@ pub(in crate::solve) fn const_conditions_for_destruct( /// additional step of eagerly folding the associated types in the where /// clauses of the impl. In this example, that means replacing /// `::Bar` with `Ty` in the first impl. -/// -// FIXME: This is only necessary as `::Assoc: ItemBound` -// bounds in impls are trivially proven using the item bound candidates. -// This is unsound in general and once that is fixed, we don't need to -// normalize eagerly here. See https://github.com/lcnr/solver-woes/issues/9 -// for more details. pub(in crate::solve) fn predicates_for_object_candidate( ecx: &mut EvalCtxt<'_, D>, param_env: I::ParamEnv, From bb3c98165cca752ba93927f19fa3f78c48caccc7 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 16 Apr 2025 18:30:33 +0000 Subject: [PATCH 159/266] Don't require rigid alias's trait to hold --- .../src/solve/normalizes_to/mod.rs | 1 - tests/ui/coroutine/higher-ranked-rigid.rs | 41 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 tests/ui/coroutine/higher-ranked-rigid.rs diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs index 2d027f16e5d96..fdeb276a58e69 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs @@ -45,7 +45,6 @@ where goal, goal.predicate.alias, ); - this.add_goal(GoalSource::AliasWellFormed, goal.with(cx, trait_ref)); this.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) }) }) diff --git a/tests/ui/coroutine/higher-ranked-rigid.rs b/tests/ui/coroutine/higher-ranked-rigid.rs new file mode 100644 index 0000000000000..23a7d51300c9f --- /dev/null +++ b/tests/ui/coroutine/higher-ranked-rigid.rs @@ -0,0 +1,41 @@ +//@ edition: 2024 +//@ revisions: current next +//@ ignore-compare-mode-next-solver (explicit revisions) +//@[next] compile-flags: -Znext-solver +//@ check-pass + +// Regression test for . +// Coroutines erase all free lifetimes from their interior types, replacing them with higher- +// ranked regions which act as universals, to properly represent the fact that we don't know what +// the value of the region is within the coroutine. +// +// In the future in `from_request`, that means that the `'r` lifetime is being replaced in +// `>::Assoc`, which is in present in the existential bounds of the +// `dyn Future` that it's awaiting. Normalizing this associated type, with its free lifetimes +// replaced, means proving `T: FromRequest<'!0>`, which doesn't hold without constraining the +// `'!0` lifetime, which we don't do today. + +// Proving `T: Trait` holds when `::Assoc` is rigid is not necessary for soundness, +// at least not *yet*, and it's not even necessary for diagnostics since we have other special +// casing for, e.g., AliasRelate goals failing in the BestObligation folder. + +// The old solver unintentioanlly avoids this by never checking that `T: Trait` holds when +// `::Assoc` is rigid. Introducing this additional requirement when projecting rigidly +// in the old solver causes this (and tons of production crates) to fail. See the fallout from the +// crater run at . + +use std::future::Future; +use std::pin::Pin; + +pub trait FromRequest<'r> { + type Assoc; + fn from_request() -> Pin + Send>>; +} + +fn test<'r, T: FromRequest<'r>>() -> Pin + Send>> { + Box::pin(async move { + T::from_request().await; + }) +} + +fn main() {} From a68ae0cbc1d923b69ef690f32b651ecf583ff27f Mon Sep 17 00:00:00 2001 From: Manuel Drehwald Date: Sat, 5 Apr 2025 03:10:19 -0400 Subject: [PATCH 160/266] working dupv and dupvonly for fwd mode --- .../rustc_ast/src/expand/autodiff_attrs.rs | 40 ++++++++++++------- compiler/rustc_builtin_macros/src/autodiff.rs | 23 ++++++++--- compiler/rustc_codegen_llvm/src/builder.rs | 2 +- .../src/builder/autodiff.rs | 38 +++++++++++++++--- .../src/partitioning/autodiff.rs | 32 ++++++++++++++- 5 files changed, 107 insertions(+), 28 deletions(-) diff --git a/compiler/rustc_ast/src/expand/autodiff_attrs.rs b/compiler/rustc_ast/src/expand/autodiff_attrs.rs index 13a7c5a180576..2f918faaf752b 100644 --- a/compiler/rustc_ast/src/expand/autodiff_attrs.rs +++ b/compiler/rustc_ast/src/expand/autodiff_attrs.rs @@ -50,8 +50,16 @@ pub enum DiffActivity { /// with it. Dual, /// Forward Mode, Compute derivatives for this input/output and *overwrite* the shadow argument + /// with it. It expects the shadow argument to be `width` times larger than the original + /// input/output. + Dualv, + /// Forward Mode, Compute derivatives for this input/output and *overwrite* the shadow argument /// with it. Drop the code which updates the original input/output for maximum performance. DualOnly, + /// Forward Mode, Compute derivatives for this input/output and *overwrite* the shadow argument + /// with it. Drop the code which updates the original input/output for maximum performance. + /// It expects the shadow argument to be `width` times larger than the original input/output. + DualvOnly, /// Reverse Mode, Compute derivatives for this &T or *T input and *add* it to the shadow argument. Duplicated, /// Reverse Mode, Compute derivatives for this &T or *T input and *add* it to the shadow argument. @@ -59,7 +67,15 @@ pub enum DiffActivity { DuplicatedOnly, /// All Integers must be Const, but these are used to mark the integer which represents the /// length of a slice/vec. This is used for safety checks on slices. - FakeActivitySize, + /// The integer (if given) specifies the size of the slice element in bytes. + FakeActivitySize(Option), +} + +impl DiffActivity { + pub fn is_dual_or_const(&self) -> bool { + use DiffActivity::*; + matches!(self, |Dual| DualOnly | Dualv | DualvOnly | Const) + } } /// We generate one of these structs for each `#[autodiff(...)]` attribute. #[derive(Clone, Eq, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] @@ -131,11 +147,7 @@ pub fn valid_ret_activity(mode: DiffMode, activity: DiffActivity) -> bool { match mode { DiffMode::Error => false, DiffMode::Source => false, - DiffMode::Forward => { - activity == DiffActivity::Dual - || activity == DiffActivity::DualOnly - || activity == DiffActivity::Const - } + DiffMode::Forward => activity.is_dual_or_const(), DiffMode::Reverse => { activity == DiffActivity::Const || activity == DiffActivity::Active @@ -153,10 +165,8 @@ pub fn valid_ret_activity(mode: DiffMode, activity: DiffActivity) -> bool { pub fn valid_ty_for_activity(ty: &P, activity: DiffActivity) -> bool { use DiffActivity::*; // It's always allowed to mark something as Const, since we won't compute derivatives wrt. it. - if matches!(activity, Const) { - return true; - } - if matches!(activity, Dual | DualOnly) { + // Dual variants also support all types. + if activity.is_dual_or_const() { return true; } // FIXME(ZuseZ4) We should make this more robust to also @@ -172,9 +182,7 @@ pub fn valid_input_activity(mode: DiffMode, activity: DiffActivity) -> bool { return match mode { DiffMode::Error => false, DiffMode::Source => false, - DiffMode::Forward => { - matches!(activity, Dual | DualOnly | Const) - } + DiffMode::Forward => activity.is_dual_or_const(), DiffMode::Reverse => { matches!(activity, Active | ActiveOnly | Duplicated | DuplicatedOnly | Const) } @@ -189,10 +197,12 @@ impl Display for DiffActivity { DiffActivity::Active => write!(f, "Active"), DiffActivity::ActiveOnly => write!(f, "ActiveOnly"), DiffActivity::Dual => write!(f, "Dual"), + DiffActivity::Dualv => write!(f, "Dualv"), DiffActivity::DualOnly => write!(f, "DualOnly"), + DiffActivity::DualvOnly => write!(f, "DualvOnly"), DiffActivity::Duplicated => write!(f, "Duplicated"), DiffActivity::DuplicatedOnly => write!(f, "DuplicatedOnly"), - DiffActivity::FakeActivitySize => write!(f, "FakeActivitySize"), + DiffActivity::FakeActivitySize(s) => write!(f, "FakeActivitySize({:?})", s), } } } @@ -220,7 +230,9 @@ impl FromStr for DiffActivity { "ActiveOnly" => Ok(DiffActivity::ActiveOnly), "Const" => Ok(DiffActivity::Const), "Dual" => Ok(DiffActivity::Dual), + "Dualv" => Ok(DiffActivity::Dualv), "DualOnly" => Ok(DiffActivity::DualOnly), + "DualvOnly" => Ok(DiffActivity::DualvOnly), "Duplicated" => Ok(DiffActivity::Duplicated), "DuplicatedOnly" => Ok(DiffActivity::DuplicatedOnly), _ => Err(()), diff --git a/compiler/rustc_builtin_macros/src/autodiff.rs b/compiler/rustc_builtin_macros/src/autodiff.rs index 351413dea493c..44ee78ebe6883 100644 --- a/compiler/rustc_builtin_macros/src/autodiff.rs +++ b/compiler/rustc_builtin_macros/src/autodiff.rs @@ -799,8 +799,19 @@ mod llvm_enzyme { d_inputs.push(shadow_arg.clone()); } } - DiffActivity::Dual | DiffActivity::DualOnly => { - for i in 0..x.width { + DiffActivity::Dual + | DiffActivity::DualOnly + | DiffActivity::Dualv + | DiffActivity::DualvOnly => { + // the *v variants get lowered to enzyme_dupv and enzyme_dupnoneedv, which cause + // Enzyme to not expect N arguments, but one argument (which is instead larger). + let iterations = + if matches!(activity, DiffActivity::Dualv | DiffActivity::DualvOnly) { + 1 + } else { + x.width + }; + for i in 0..iterations { let mut shadow_arg = arg.clone(); let old_name = if let PatKind::Ident(_, ident, _) = arg.pat.kind { ident.name @@ -823,7 +834,7 @@ mod llvm_enzyme { DiffActivity::Const => { // Nothing to do here. } - DiffActivity::None | DiffActivity::FakeActivitySize => { + DiffActivity::None | DiffActivity::FakeActivitySize(_) => { panic!("Should not happen"); } } @@ -887,8 +898,8 @@ mod llvm_enzyme { } }; - if let DiffActivity::Dual = x.ret_activity { - let kind = if x.width == 1 { + if matches!(x.ret_activity, DiffActivity::Dual | DiffActivity::Dualv) { + let kind = if x.width == 1 || matches!(x.ret_activity, DiffActivity::Dualv) { // Dual can only be used for f32/f64 ret. // In that case we return now a tuple with two floats. TyKind::Tup(thin_vec![ty.clone(), ty.clone()]) @@ -903,7 +914,7 @@ mod llvm_enzyme { let ty = P(rustc_ast::Ty { kind, id: ty.id, span: ty.span, tokens: None }); d_decl.output = FnRetTy::Ty(ty); } - if let DiffActivity::DualOnly = x.ret_activity { + if matches!(x.ret_activity, DiffActivity::DualOnly | DiffActivity::DualvOnly) { // No need to change the return type, // we will just return the shadow in place of the primal return. // However, if we have a width > 1, then we don't return -> T, but -> [T; width] diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 35134e9f5a050..27f7f95f100e2 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -123,7 +123,7 @@ impl<'a, 'll, CX: Borrow>> GenericBuilder<'a, 'll, CX> { /// Empty string, to be used where LLVM expects an instruction name, indicating /// that the instruction is to be left unnamed (i.e. numbered, in textual IR). // FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer. -const UNNAMED: *const c_char = c"".as_ptr(); +pub(crate) const UNNAMED: *const c_char = c"".as_ptr(); impl<'ll, CX: Borrow>> BackendTypes for GenericBuilder<'_, 'll, CX> { type Value = as BackendTypes>::Value; diff --git a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs index 5e7ef27143b14..e7c071d05aa8f 100644 --- a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs +++ b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs @@ -10,7 +10,7 @@ use rustc_middle::bug; use tracing::{debug, trace}; use crate::back::write::llvm_err; -use crate::builder::SBuilder; +use crate::builder::{SBuilder, UNNAMED}; use crate::context::SimpleCx; use crate::declare::declare_simple_fn; use crate::errors::{AutoDiffWithoutEnable, LlvmError}; @@ -51,6 +51,7 @@ fn has_sret(fnc: &Value) -> bool { // using iterators and peek()? fn match_args_from_caller_to_enzyme<'ll>( cx: &SimpleCx<'ll>, + builder: &SBuilder<'ll, 'll>, width: u32, args: &mut Vec<&'ll llvm::Value>, inputs: &[DiffActivity], @@ -78,7 +79,9 @@ fn match_args_from_caller_to_enzyme<'ll>( let enzyme_const = cx.create_metadata("enzyme_const".to_string()).unwrap(); let enzyme_out = cx.create_metadata("enzyme_out".to_string()).unwrap(); let enzyme_dup = cx.create_metadata("enzyme_dup".to_string()).unwrap(); + let enzyme_dupv = cx.create_metadata("enzyme_dupv".to_string()).unwrap(); let enzyme_dupnoneed = cx.create_metadata("enzyme_dupnoneed".to_string()).unwrap(); + let enzyme_dupnoneedv = cx.create_metadata("enzyme_dupnoneedv".to_string()).unwrap(); while activity_pos < inputs.len() { let diff_activity = inputs[activity_pos as usize]; @@ -90,13 +93,34 @@ fn match_args_from_caller_to_enzyme<'ll>( DiffActivity::Active => (enzyme_out, false), DiffActivity::ActiveOnly => (enzyme_out, false), DiffActivity::Dual => (enzyme_dup, true), + DiffActivity::Dualv => (enzyme_dupv, true), DiffActivity::DualOnly => (enzyme_dupnoneed, true), + DiffActivity::DualvOnly => (enzyme_dupnoneedv, true), DiffActivity::Duplicated => (enzyme_dup, true), DiffActivity::DuplicatedOnly => (enzyme_dupnoneed, true), - DiffActivity::FakeActivitySize => (enzyme_const, false), + DiffActivity::FakeActivitySize(_) => (enzyme_const, false), }; let outer_arg = outer_args[outer_pos]; args.push(cx.get_metadata_value(activity)); + if matches!(diff_activity, DiffActivity::Dualv) { + let next_outer_arg = outer_args[outer_pos + 1]; + let elem_bytes_size: u64 = match inputs[activity_pos + 1] { + DiffActivity::FakeActivitySize(Some(s)) => s.into(), + _ => bug!("incorrect Dualv handling recognized."), + }; + // stride: sizeof(T) * n_elems. + // n_elems is the next integer. + // Now we multiply `4 * next_outer_arg` to get the stride. + let mul = unsafe { + llvm::LLVMBuildMul( + builder.llbuilder, + cx.get_const_i64(elem_bytes_size), + next_outer_arg, + UNNAMED, + ) + }; + args.push(mul); + } args.push(outer_arg); if duplicated { // We know that duplicated args by construction have a following argument, @@ -114,7 +138,7 @@ fn match_args_from_caller_to_enzyme<'ll>( } else { let next_activity = inputs[activity_pos + 1]; // We analyze the MIR types and add this dummy activity if we visit a slice. - next_activity == DiffActivity::FakeActivitySize + matches!(next_activity, DiffActivity::FakeActivitySize(_)) } }; if slice { @@ -125,7 +149,10 @@ fn match_args_from_caller_to_enzyme<'ll>( // int2 >= int1, which means the shadow vector is large enough to store the gradient. assert_eq!(cx.type_kind(next_outer_ty), TypeKind::Integer); - for i in 0..(width as usize) { + let iterations = + if matches!(diff_activity, DiffActivity::Dualv) { 1 } else { width as usize }; + + for i in 0..iterations { let next_outer_arg2 = outer_args[outer_pos + 2 * (i + 1)]; let next_outer_ty2 = cx.val_ty(next_outer_arg2); assert_eq!(cx.type_kind(next_outer_ty2), TypeKind::Pointer); @@ -136,7 +163,7 @@ fn match_args_from_caller_to_enzyme<'ll>( } args.push(cx.get_metadata_value(enzyme_const)); args.push(next_outer_arg); - outer_pos += 2 + 2 * width as usize; + outer_pos += 2 + 2 * iterations; activity_pos += 2; } else { // A duplicated pointer will have the following two outer_fn arguments: @@ -360,6 +387,7 @@ fn generate_enzyme_call<'ll>( let outer_args: Vec<&llvm::Value> = get_params(outer_fn); match_args_from_caller_to_enzyme( &cx, + &builder, attrs.width, &mut args, &attrs.input_activity, diff --git a/compiler/rustc_monomorphize/src/partitioning/autodiff.rs b/compiler/rustc_monomorphize/src/partitioning/autodiff.rs index ebe0b258c1b6a..22d593b80b895 100644 --- a/compiler/rustc_monomorphize/src/partitioning/autodiff.rs +++ b/compiler/rustc_monomorphize/src/partitioning/autodiff.rs @@ -2,7 +2,7 @@ use rustc_ast::expand::autodiff_attrs::{AutoDiffItem, DiffActivity}; use rustc_hir::def_id::LOCAL_CRATE; use rustc_middle::bug; use rustc_middle::mir::mono::MonoItem; -use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; +use rustc_middle::ty::{self, Instance, PseudoCanonicalInput, Ty, TyCtxt, TypingEnv}; use rustc_symbol_mangling::symbol_name_for_instance_in_crate; use tracing::{debug, trace}; @@ -22,23 +22,51 @@ fn adjust_activity_to_abi<'tcx>(tcx: TyCtxt<'tcx>, fn_ty: Ty<'tcx>, da: &mut Vec for (i, ty) in sig.inputs().iter().enumerate() { if let Some(inner_ty) = ty.builtin_deref(true) { if inner_ty.is_slice() { + // Now we need to figure out the size of each slice element in memory to allow + // safety checks and usability improvements in the backend. + let sty = match inner_ty.builtin_index() { + Some(sty) => sty, + None => { + panic!("slice element type unknown"); + } + }; + let pci = PseudoCanonicalInput { + typing_env: TypingEnv::fully_monomorphized(), + value: sty, + }; + + let layout = tcx.layout_of(pci); + let elem_size = match layout { + Ok(layout) => layout.size, + Err(_) => { + bug!("autodiff failed to compute slice element size"); + } + }; + let elem_size: u32 = elem_size.bytes() as u32; + // We know that the length will be passed as extra arg. if !da.is_empty() { // We are looking at a slice. The length of that slice will become an // extra integer on llvm level. Integers are always const. // However, if the slice get's duplicated, we want to know to later check the // size. So we mark the new size argument as FakeActivitySize. + // There is one FakeActivitySize per slice, so for convenience we store the + // slice element size in bytes in it. We will use the size in the backend. let activity = match da[i] { DiffActivity::DualOnly | DiffActivity::Dual + | DiffActivity::Dualv | DiffActivity::DuplicatedOnly - | DiffActivity::Duplicated => DiffActivity::FakeActivitySize, + | DiffActivity::Duplicated => { + DiffActivity::FakeActivitySize(Some(elem_size)) + } DiffActivity::Const => DiffActivity::Const, _ => bug!("unexpected activity for ptr/ref"), }; new_activities.push(activity); new_positions.push(i + 1); } + continue; } } From d7c0c328275fdcd5b6bba7f9ed7c97528103aca8 Mon Sep 17 00:00:00 2001 From: Manuel Drehwald Date: Tue, 8 Apr 2025 20:59:17 -0400 Subject: [PATCH 161/266] passing test for dualv --- tests/codegen/autodiffv2.rs | 113 ++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 tests/codegen/autodiffv2.rs diff --git a/tests/codegen/autodiffv2.rs b/tests/codegen/autodiffv2.rs new file mode 100644 index 0000000000000..a40d19d3be3a8 --- /dev/null +++ b/tests/codegen/autodiffv2.rs @@ -0,0 +1,113 @@ +//@ compile-flags: -Zautodiff=Enable -C opt-level=3 -Clto=fat +//@ no-prefer-dynamic +//@ needs-enzyme +// +// In Enzyme, we test against a large range of LLVM versions (5+) and don't have overly many +// breakages. One benefit is that we match the IR generated by Enzyme only after running it +// through LLVM's O3 pipeline, which will remove most of the noise. +// However, our integration test could also be affected by changes in how rustc lowers MIR into +// LLVM-IR, which could cause additional noise and thus breakages. If that's the case, we should +// reduce this test to only match the first lines and the ret instructions. +// +// The function tested here has 4 inputs and 5 outputs, so we could either call forward-mode +// autodiff 4 times, or reverse mode 5 times. Since a forward-mode call is usually faster than +// reverse mode, we prefer it here. This file also tests a new optimization (batch mode), which +// allows us to call forward-mode autodiff only once, and get all 5 outputs in a single call. +// +// We support 2 different batch modes. `d_square2` has the same interface as scalar forward-mode, +// but each shadow argument is `width` times larger (thus 16 and 20 elements here). +// `d_square3` instead takes `width` (4) shadow arguments, which are all the same size as the +// original function arguments. +// +// FIXME(autodiff): We currently can't test `d_square1` and `d_square3` in the same file, since they +// generate the same dummy functions which get merged by LLVM, breaking pieces of our pipeline which +// try to rewrite the dummy functions later. We should consider to change to pure declarations both +// in our frontend and in the llvm backend to avoid these issues. + +#![feature(autodiff)] + +use std::autodiff::autodiff; + +#[no_mangle] +//#[autodiff(d_square1, Forward, Dual, Dual)] +#[autodiff(d_square2, Forward, 4, Dualv, Dualv)] +#[autodiff(d_square3, Forward, 4, Dual, Dual)] +fn square(x: &[f32], y: &mut [f32]) { + assert!(x.len() >= 4); + assert!(y.len() >= 5); + y[0] = 4.3 * x[0] + 1.2 * x[1] + 3.4 * x[2] + 2.1 * x[3]; + y[1] = 2.3 * x[0] + 4.5 * x[1] + 1.7 * x[2] + 6.4 * x[3]; + y[2] = 1.1 * x[0] + 3.3 * x[1] + 2.5 * x[2] + 4.7 * x[3]; + y[3] = 5.2 * x[0] + 1.4 * x[1] + 2.6 * x[2] + 3.8 * x[3]; + y[4] = 1.0 * x[0] + 2.0 * x[1] + 3.0 * x[2] + 4.0 * x[3]; +} + +fn main() { + let x1 = std::hint::black_box(vec![0.0, 1.0, 2.0, 3.0]); + + let dx1 = std::hint::black_box(vec![1.0; 12]); + + let z1 = std::hint::black_box(vec![1.0, 0.0, 0.0, 0.0]); + let z2 = std::hint::black_box(vec![0.0, 1.0, 0.0, 0.0]); + let z3 = std::hint::black_box(vec![0.0, 0.0, 1.0, 0.0]); + let z4 = std::hint::black_box(vec![0.0, 0.0, 0.0, 1.0]); + + let z5 = std::hint::black_box(vec![ + 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, + ]); + + let mut y1 = std::hint::black_box(vec![0.0; 5]); + let mut y2 = std::hint::black_box(vec![0.0; 5]); + let mut y3 = std::hint::black_box(vec![0.0; 5]); + let mut y4 = std::hint::black_box(vec![0.0; 5]); + + let mut y5 = std::hint::black_box(vec![0.0; 5]); + + let mut y6 = std::hint::black_box(vec![0.0; 5]); + + let mut dy1_1 = std::hint::black_box(vec![0.0; 5]); + let mut dy1_2 = std::hint::black_box(vec![0.0; 5]); + let mut dy1_3 = std::hint::black_box(vec![0.0; 5]); + let mut dy1_4 = std::hint::black_box(vec![0.0; 5]); + + let mut dy2 = std::hint::black_box(vec![0.0; 20]); + + let mut dy3_1 = std::hint::black_box(vec![0.0; 5]); + let mut dy3_2 = std::hint::black_box(vec![0.0; 5]); + let mut dy3_3 = std::hint::black_box(vec![0.0; 5]); + let mut dy3_4 = std::hint::black_box(vec![0.0; 5]); + + // scalar. + //d_square1(&x1, &z1, &mut y1, &mut dy1_1); + //d_square1(&x1, &z2, &mut y2, &mut dy1_2); + //d_square1(&x1, &z3, &mut y3, &mut dy1_3); + //d_square1(&x1, &z4, &mut y4, &mut dy1_4); + + // assert y1 == y2 == y3 == y4 + //for i in 0..5 { + // assert_eq!(y1[i], y2[i]); + // assert_eq!(y1[i], y3[i]); + // assert_eq!(y1[i], y4[i]); + //} + + // batch mode A) + d_square2(&x1, &z5, &mut y5, &mut dy2); + + // assert y1 == y2 == y3 == y4 == y5 + //for i in 0..5 { + // assert_eq!(y1[i], y5[i]); + //} + + // batch mode B) + d_square3(&x1, &z1, &z2, &z3, &z4, &mut y6, &mut dy3_1, &mut dy3_2, &mut dy3_3, &mut dy3_4); + for i in 0..5 { + assert_eq!(y5[i], y6[i]); + } + + for i in 0..5 { + assert_eq!(dy2[0..5][i], dy3_1[i]); + assert_eq!(dy2[5..10][i], dy3_2[i]); + assert_eq!(dy2[10..15][i], dy3_3[i]); + assert_eq!(dy2[15..20][i], dy3_4[i]); + } +} From cb6c499bc98a8b6db85856f200ffba2f47b8b73a Mon Sep 17 00:00:00 2001 From: dianne Date: Sun, 23 Feb 2025 19:39:19 -0800 Subject: [PATCH 162/266] lower implicit deref patterns to THIR Since this uses `pat_adjustments`, I've also tweaked the documentation to mention implicit deref patterns and made sure the pattern migration diagnostic logic accounts for it. I'll adjust `ExprUseVisitor` in a later commit and add some tests there for closure capture inference. --- .../rustc_middle/src/ty/typeck_results.rs | 15 ++++++++--- .../src/thir/pattern/migration.rs | 16 +++++------- .../rustc_mir_build/src/thir/pattern/mod.rs | 26 ++++++++++++------- 3 files changed, 36 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index ee8113b0f7627..4c5c669771fb5 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -77,8 +77,8 @@ pub struct TypeckResults<'tcx> { /// to a form valid in all Editions, either as a lint diagnostic or hard error. rust_2024_migration_desugared_pats: ItemLocalMap, - /// Stores the types which were implicitly dereferenced in pattern binding modes - /// for later usage in THIR lowering. For example, + /// Stores the types which were implicitly dereferenced in pattern binding modes or deref + /// patterns for later usage in THIR lowering. For example, /// /// ``` /// match &&Some(5i32) { @@ -86,7 +86,16 @@ pub struct TypeckResults<'tcx> { /// _ => {}, /// } /// ``` - /// leads to a `vec![&&Option, &Option]`. Empty vectors are not stored. + /// leads to a `vec![&&Option, &Option]` and + /// + /// ``` + /// #![feature(deref_patterns)] + /// match &Box::new(Some(5i32)) { + /// Some(n) => {}, + /// _ => {}, + /// } + /// ``` + /// leads to a `vec![&Box>, Box>]`. Empty vectors are not stored. /// /// See: /// diff --git a/compiler/rustc_mir_build/src/thir/pattern/migration.rs b/compiler/rustc_mir_build/src/thir/pattern/migration.rs index c688b6f2848c4..12c457f13fc12 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/migration.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/migration.rs @@ -4,7 +4,6 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_errors::MultiSpan; use rustc_hir::{BindingMode, ByRef, HirId, Mutability}; use rustc_lint as lint; -use rustc_middle::span_bug; use rustc_middle::ty::{self, Rust2024IncompatiblePatInfo, TyCtxt}; use rustc_span::{Ident, Span}; @@ -87,19 +86,18 @@ impl<'a> PatMigration<'a> { } /// Tracks when we're lowering a pattern that implicitly dereferences the scrutinee. - /// This should only be called when the pattern type adjustments list `adjustments` is - /// non-empty. Returns the prior default binding mode; this should be followed by a call to - /// [`PatMigration::leave_ref`] to restore it when we leave the pattern. + /// This should only be called when the pattern type adjustments list `adjustments` contains an + /// implicit deref of a reference type. Returns the prior default binding mode; this should be + /// followed by a call to [`PatMigration::leave_ref`] to restore it when we leave the pattern. pub(super) fn visit_implicit_derefs<'tcx>( &mut self, pat_span: Span, adjustments: &[ty::adjustment::PatAdjustment<'tcx>], ) -> Option<(Span, Mutability)> { - let implicit_deref_mutbls = adjustments.iter().map(|adjust| { - let &ty::Ref(_, _, mutbl) = adjust.source.kind() else { - span_bug!(pat_span, "pattern implicitly dereferences a non-ref type"); - }; - mutbl + // Implicitly dereferencing references changes the default binding mode, but implicit derefs + // of smart pointers do not. Thus, we only consider implicit derefs of reference types. + let implicit_deref_mutbls = adjustments.iter().filter_map(|adjust| { + if let &ty::Ref(_, _, mutbl) = adjust.source.kind() { Some(mutbl) } else { None } }); if !self.info.suggest_eliding_modes { diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index f682581d763be..8f058efdfacdb 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -18,7 +18,7 @@ use rustc_middle::mir::interpret::LitToConstInput; use rustc_middle::thir::{ Ascription, FieldPat, LocalVarId, Pat, PatKind, PatRange, PatRangeBoundary, }; -use rustc_middle::ty::adjustment::PatAdjustment; +use rustc_middle::ty::adjustment::{PatAdjust, PatAdjustment}; use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt, TypingMode}; use rustc_middle::{bug, span_bug}; @@ -68,9 +68,11 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { self.typeck_results.pat_adjustments().get(pat.hir_id).map_or(&[], |v| &**v); // Track the default binding mode for the Rust 2024 migration suggestion. + // Implicitly dereferencing references changes the default binding mode, but implicit deref + // patterns do not. Only track binding mode changes if a ref type is in the adjustments. let mut opt_old_mode_span = None; if let Some(s) = &mut self.rust_2024_migration - && !adjustments.is_empty() + && adjustments.iter().any(|adjust| adjust.kind == PatAdjust::BuiltinDeref) { opt_old_mode_span = s.visit_implicit_derefs(pat.span, adjustments); } @@ -104,16 +106,22 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { }; let adjusted_pat = adjustments.iter().rev().fold(unadjusted_pat, |thir_pat, adjust| { - debug!("{:?}: wrapping pattern with type {:?}", thir_pat, adjust); - Box::new(Pat { - span: thir_pat.span, - ty: adjust.source, - kind: PatKind::Deref { subpattern: thir_pat }, - }) + debug!("{:?}: wrapping pattern with adjustment {:?}", thir_pat, adjust); + let span = thir_pat.span; + let kind = match adjust.kind { + PatAdjust::BuiltinDeref => PatKind::Deref { subpattern: thir_pat }, + PatAdjust::OverloadedDeref => { + let mutable = self.typeck_results.pat_has_ref_mut_binding(pat); + let mutability = + if mutable { hir::Mutability::Mut } else { hir::Mutability::Not }; + PatKind::DerefPattern { subpattern: thir_pat, mutability } + } + }; + Box::new(Pat { span, ty: adjust.source, kind }) }); if let Some(s) = &mut self.rust_2024_migration - && !adjustments.is_empty() + && adjustments.iter().any(|adjust| adjust.kind == PatAdjust::BuiltinDeref) { s.leave_ref(opt_old_mode_span); } From e4b7b3d820b6db4f4a37a1a09b700bc9a39d80ba Mon Sep 17 00:00:00 2001 From: dianne Date: Sat, 8 Mar 2025 21:07:11 -0800 Subject: [PATCH 163/266] pattern typing for immutable implicit deref patterns --- compiler/rustc_hir_typeck/src/pat.rs | 116 ++++++++++++++---- tests/ui/pattern/deref-patterns/bindings.rs | 27 ++++ tests/ui/pattern/deref-patterns/branch.rs | 22 ++++ .../cant_move_out_of_pattern.rs | 18 +++ .../cant_move_out_of_pattern.stderr | 36 +++++- tests/ui/pattern/deref-patterns/typeck.rs | 6 + .../ui/pattern/deref-patterns/typeck_fail.rs | 11 ++ .../pattern/deref-patterns/typeck_fail.stderr | 36 +++++- .../deref-patterns/unsatisfied-bounds.rs | 21 ++++ .../deref-patterns/unsatisfied-bounds.stderr | 9 ++ 10 files changed, 272 insertions(+), 30 deletions(-) create mode 100644 tests/ui/pattern/deref-patterns/unsatisfied-bounds.rs create mode 100644 tests/ui/pattern/deref-patterns/unsatisfied-bounds.stderr diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index c19d8cf6dc546..11ed7db9eb7f4 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -162,12 +162,27 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Mode for adjusting the expected type and binding mode. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum AdjustMode { - /// Peel off all immediate reference types. - Peel, + /// Peel off all immediate reference types. If the `deref_patterns` feature is enabled, this + /// also peels smart pointer ADTs. + Peel { kind: PeelKind }, /// Pass on the input binding mode and expected type. Pass, } +/// Restrictions on what types to peel when adjusting the expected type and binding mode. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PeelKind { + /// Only peel reference types. This is used for explicit `deref!(_)` patterns, which dereference + /// any number of `&`/`&mut` references, plus a single smart pointer. + ExplicitDerefPat, + /// Implicitly peel any number of references, and if `deref_patterns` is enabled, smart pointer + /// ADTs. In order to peel only as much as necessary for the pattern to match, the `until_adt` + /// field contains the ADT def that the pattern is a constructor for, if applicable, so that we + /// don't peel it. See [`ResolvedPat`] for more information. + // TODO: add `ResolvedPat` and `until_adt`. + Implicit, +} + /// `ref mut` bindings (explicit or match-ergonomics) are not allowed behind an `&` reference. /// Normally, the borrow checker enforces this, but for (currently experimental) match ergonomics, /// we track this when typing patterns for two purposes: @@ -390,7 +405,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } // Resolve type if needed. - let expected = if let AdjustMode::Peel = adjust_mode + let expected = if let AdjustMode::Peel { .. } = adjust_mode && pat.default_binding_modes { self.try_structurally_resolve_type(pat.span, expected) @@ -403,7 +418,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match pat.kind { // Peel off a `&` or `&mut` from the scrutinee type. See the examples in // `tests/ui/rfcs/rfc-2005-default-binding-mode`. - _ if let AdjustMode::Peel = adjust_mode + _ if let AdjustMode::Peel { .. } = adjust_mode && pat.default_binding_modes && let ty::Ref(_, inner_ty, inner_mutability) = *expected.kind() => { @@ -443,6 +458,45 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Recurse with the new expected type. self.check_pat_inner(pat, opt_path_res, adjust_mode, inner_ty, new_pat_info) } + // If `deref_patterns` is enabled, peel a smart pointer from the scrutinee type. See the + // examples in `tests/ui/pattern/deref_patterns/`. + _ if self.tcx.features().deref_patterns() + && let AdjustMode::Peel { kind: PeelKind::Implicit } = adjust_mode + && pat.default_binding_modes + // For simplicity, only apply overloaded derefs if `expected` is a known ADT. + // FIXME(deref_patterns): we'll get better diagnostics for users trying to + // implicitly deref generics if we allow them here, but primitives, tuples, and + // inference vars definitely should be stopped. Figure out what makes most sense. + // TODO: stop peeling if the pattern is a constructor for the scrutinee type + && expected.is_adt() + // At this point, the pattern isn't able to match `expected` without peeling. Check + // that it implements `Deref` before assuming it's a smart pointer, to get a normal + // type error instead of a missing impl error if not. This only checks for `Deref`, + // not `DerefPure`: we require that too, but we want a trait error if it's missing. + && let Some(deref_trait) = self.tcx.lang_items().deref_trait() + && self + .type_implements_trait(deref_trait, [expected], self.param_env) + .may_apply() => + { + debug!("scrutinee ty {expected:?} is a smart pointer, inserting overloaded deref"); + // The scrutinee is a smart pointer; implicitly dereference it. This adds a + // requirement that `expected: DerefPure`. + let inner_ty = self.deref_pat_target(pat.span, expected); + // Once we've checked `pat`, we'll add a `DerefMut` bound if it contains any + // `ref mut` bindings. TODO: implement that, then reference here. + + // Preserve the smart pointer type for THIR lowering and upvar analysis. + self.typeck_results + .borrow_mut() + .pat_adjustments_mut() + .entry(pat.hir_id) + .or_default() + .push(PatAdjustment { kind: PatAdjust::OverloadedDeref, source: expected }); + + // Recurse, using the old pat info to keep `current_depth` to its old value. + // Peeling smart pointers does not update the default binding mode. + self.check_pat_inner(pat, opt_path_res, adjust_mode, inner_ty, old_pat_info) + } PatKind::Missing | PatKind::Wild | PatKind::Err(_) => expected, // We allow any type here; we ensure that the type is uninhabited during match checking. PatKind::Never => expected, @@ -505,12 +559,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { PatKind::Struct(..) | PatKind::TupleStruct(..) | PatKind::Tuple(..) - | PatKind::Box(_) - | PatKind::Deref(_) | PatKind::Range(..) - | PatKind::Slice(..) => AdjustMode::Peel, + | PatKind::Slice(..) => AdjustMode::Peel { kind: PeelKind::Implicit }, + // When checking an explicit deref pattern, only peel reference types. + // FIXME(deref_patterns): If box patterns and deref patterns need to coexist, box + // patterns may want `PeelKind::Implicit`, stopping on encountering a box. + | PatKind::Box(_) + | PatKind::Deref(_) => AdjustMode::Peel { kind: PeelKind::ExplicitDerefPat }, // A never pattern behaves somewhat like a literal or unit variant. - PatKind::Never => AdjustMode::Peel, + PatKind::Never => AdjustMode::Peel { kind: PeelKind::Implicit }, PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), .. }) => match opt_path_res.unwrap() { // These constants can be of a reference type, e.g. `const X: &u8 = &0;`. // Peeling the reference types too early will cause type checking failures. @@ -520,7 +577,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // could successfully compile. The former being `Self` requires a unit struct. // In either case, and unlike constants, the pattern itself cannot be // a reference type wherefore peeling doesn't give up any expressiveness. - _ => AdjustMode::Peel, + _ => AdjustMode::Peel { kind: PeelKind::Implicit }, }, // String and byte-string literals result in types `&str` and `&[u8]` respectively. @@ -530,7 +587,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Call `resolve_vars_if_possible` here for inline const blocks. PatKind::Expr(lt) => match self.resolve_vars_if_possible(self.check_pat_expr_unadjusted(lt)).kind() { ty::Ref(..) => AdjustMode::Pass, - _ => AdjustMode::Peel, + _ => AdjustMode::Peel { kind: PeelKind::Implicit }, }, // Ref patterns are complicated, we handle them in `check_pat_ref`. @@ -2256,31 +2313,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> Ty<'tcx> { - let tcx = self.tcx; - // Register a `DerefPure` bound, which is required by all `deref!()` pats. - self.register_bound( - expected, - tcx.require_lang_item(hir::LangItem::DerefPure, Some(span)), - self.misc(span), - ); - // ::Target - let ty = Ty::new_projection( - tcx, - tcx.require_lang_item(hir::LangItem::DerefTarget, Some(span)), - [expected], - ); - let ty = self.normalize(span, ty); - let ty = self.try_structurally_resolve_type(span, ty); - self.check_pat(inner, ty, pat_info); + let target_ty = self.deref_pat_target(span, expected); + self.check_pat(inner, target_ty, pat_info); // Check if the pattern has any `ref mut` bindings, which would require // `DerefMut` to be emitted in MIR building instead of just `Deref`. // We do this *after* checking the inner pattern, since we want to make // sure to apply any match-ergonomics adjustments. + // TODO: move this to a separate definition to share it with implicit deref pats if self.typeck_results.borrow().pat_has_ref_mut_binding(inner) { self.register_bound( expected, - tcx.require_lang_item(hir::LangItem::DerefMut, Some(span)), + self.tcx.require_lang_item(hir::LangItem::DerefMut, Some(span)), self.misc(span), ); } @@ -2288,6 +2332,24 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected } + fn deref_pat_target(&self, span: Span, source_ty: Ty<'tcx>) -> Ty<'tcx> { + // Register a `DerefPure` bound, which is required by all `deref!()` pats. + let tcx = self.tcx; + self.register_bound( + source_ty, + tcx.require_lang_item(hir::LangItem::DerefPure, Some(span)), + self.misc(span), + ); + // The expected type for the deref pat's inner pattern is `::Target`. + let target_ty = Ty::new_projection( + tcx, + tcx.require_lang_item(hir::LangItem::DerefTarget, Some(span)), + [source_ty], + ); + let target_ty = self.normalize(span, target_ty); + self.try_structurally_resolve_type(span, target_ty) + } + // Precondition: Pat is Ref(inner) fn check_pat_ref( &self, diff --git a/tests/ui/pattern/deref-patterns/bindings.rs b/tests/ui/pattern/deref-patterns/bindings.rs index 5881e4166a46f..ce10cd5439e16 100644 --- a/tests/ui/pattern/deref-patterns/bindings.rs +++ b/tests/ui/pattern/deref-patterns/bindings.rs @@ -1,7 +1,9 @@ +//@ revisions: explicit implicit //@ run-pass #![feature(deref_patterns)] #![allow(incomplete_features)] +#[cfg(explicit)] fn simple_vec(vec: Vec) -> u32 { match vec { deref!([]) => 100, @@ -13,6 +15,19 @@ fn simple_vec(vec: Vec) -> u32 { } } +#[cfg(implicit)] +fn simple_vec(vec: Vec) -> u32 { + match vec { + [] => 100, + [x] if x == 4 => x + 4, + [x] => x, + [1, x] => x + 200, + deref!(ref slice) => slice.iter().sum(), + _ => 2000, + } +} + +#[cfg(explicit)] fn nested_vec(vecvec: Vec>) -> u32 { match vecvec { deref!([]) => 0, @@ -24,6 +39,18 @@ fn nested_vec(vecvec: Vec>) -> u32 { } } +#[cfg(implicit)] +fn nested_vec(vecvec: Vec>) -> u32 { + match vecvec { + [] => 0, + [[x]] => x, + [[0, x] | [1, x]] => x, + [ref x] => x.iter().sum(), + [[], [1, x, y]] => y - x, + _ => 2000, + } +} + fn ref_mut(val: u32) -> u32 { let mut b = Box::new(0u32); match &mut b { diff --git a/tests/ui/pattern/deref-patterns/branch.rs b/tests/ui/pattern/deref-patterns/branch.rs index 1bac1006d9dc0..9d72b35fd2f1c 100644 --- a/tests/ui/pattern/deref-patterns/branch.rs +++ b/tests/ui/pattern/deref-patterns/branch.rs @@ -1,8 +1,10 @@ +//@ revisions: explicit implicit //@ run-pass // Test the execution of deref patterns. #![feature(deref_patterns)] #![allow(incomplete_features)] +#[cfg(explicit)] fn branch(vec: Vec) -> u32 { match vec { deref!([]) => 0, @@ -12,6 +14,17 @@ fn branch(vec: Vec) -> u32 { } } +#[cfg(implicit)] +fn branch(vec: Vec) -> u32 { + match vec { + [] => 0, + [1, _, 3] => 1, + [2, ..] => 2, + _ => 1000, + } +} + +#[cfg(explicit)] fn nested(vec: Vec>) -> u32 { match vec { deref!([deref!([]), ..]) => 1, @@ -20,6 +33,15 @@ fn nested(vec: Vec>) -> u32 { } } +#[cfg(implicit)] +fn nested(vec: Vec>) -> u32 { + match vec { + [[], ..] => 1, + [[0, ..], [1, ..]] => 2, + _ => 1000, + } +} + fn main() { assert!(matches!(Vec::::new(), deref!([]))); assert!(matches!(vec![1], deref!([1]))); diff --git a/tests/ui/pattern/deref-patterns/cant_move_out_of_pattern.rs b/tests/ui/pattern/deref-patterns/cant_move_out_of_pattern.rs index 84b5ec09dc7d8..791776be5acad 100644 --- a/tests/ui/pattern/deref-patterns/cant_move_out_of_pattern.rs +++ b/tests/ui/pattern/deref-patterns/cant_move_out_of_pattern.rs @@ -21,4 +21,22 @@ fn cant_move_out_rc(rc: Rc) -> Struct { } } +struct Container(Struct); + +fn cant_move_out_box_implicit(b: Box) -> Struct { + match b { + //~^ ERROR: cannot move out of a shared reference + Container(x) => x, + _ => unreachable!(), + } +} + +fn cant_move_out_rc_implicit(rc: Rc) -> Struct { + match rc { + //~^ ERROR: cannot move out of a shared reference + Container(x) => x, + _ => unreachable!(), + } +} + fn main() {} diff --git a/tests/ui/pattern/deref-patterns/cant_move_out_of_pattern.stderr b/tests/ui/pattern/deref-patterns/cant_move_out_of_pattern.stderr index 2cf435b117999..1887800fc38a8 100644 --- a/tests/ui/pattern/deref-patterns/cant_move_out_of_pattern.stderr +++ b/tests/ui/pattern/deref-patterns/cant_move_out_of_pattern.stderr @@ -32,6 +32,40 @@ help: consider borrowing the pattern binding LL | deref!(ref x) => x, | +++ -error: aborting due to 2 previous errors +error[E0507]: cannot move out of a shared reference + --> $DIR/cant_move_out_of_pattern.rs:27:11 + | +LL | match b { + | ^ +LL | +LL | Container(x) => x, + | - + | | + | data moved here + | move occurs because `x` has type `Struct`, which does not implement the `Copy` trait + | +help: consider borrowing the pattern binding + | +LL | Container(ref x) => x, + | +++ + +error[E0507]: cannot move out of a shared reference + --> $DIR/cant_move_out_of_pattern.rs:35:11 + | +LL | match rc { + | ^^ +LL | +LL | Container(x) => x, + | - + | | + | data moved here + | move occurs because `x` has type `Struct`, which does not implement the `Copy` trait + | +help: consider borrowing the pattern binding + | +LL | Container(ref x) => x, + | +++ + +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0507`. diff --git a/tests/ui/pattern/deref-patterns/typeck.rs b/tests/ui/pattern/deref-patterns/typeck.rs index f23f7042cd892..3a7ce9d1deb3d 100644 --- a/tests/ui/pattern/deref-patterns/typeck.rs +++ b/tests/ui/pattern/deref-patterns/typeck.rs @@ -10,26 +10,32 @@ fn main() { let vec: Vec = Vec::new(); match vec { deref!([..]) => {} + [..] => {} _ => {} } match Box::new(true) { deref!(true) => {} + true => {} _ => {} } match &Box::new(true) { deref!(true) => {} + true => {} _ => {} } match &Rc::new(0) { deref!(1..) => {} + 1.. => {} _ => {} } let _: &Struct = match &Rc::new(Struct) { deref!(x) => x, + Struct => &Struct, _ => unreachable!(), }; let _: &[Struct] = match &Rc::new(vec![Struct]) { deref!(deref!(x)) => x, + [Struct] => &[Struct], _ => unreachable!(), }; } diff --git a/tests/ui/pattern/deref-patterns/typeck_fail.rs b/tests/ui/pattern/deref-patterns/typeck_fail.rs index 040118449ecca..4b9ad7d25f090 100644 --- a/tests/ui/pattern/deref-patterns/typeck_fail.rs +++ b/tests/ui/pattern/deref-patterns/typeck_fail.rs @@ -7,11 +7,22 @@ fn main() { match "foo".to_string() { deref!("foo") => {} //~^ ERROR: mismatched types + "foo" => {} + //~^ ERROR: mismatched types _ => {} } match &"foo".to_string() { deref!("foo") => {} //~^ ERROR: mismatched types + "foo" => {} + //~^ ERROR: mismatched types + _ => {} + } + + // Make sure we don't try implicitly dereferncing any ADT. + match Some(0) { + Ok(0) => {} + //~^ ERROR: mismatched types _ => {} } } diff --git a/tests/ui/pattern/deref-patterns/typeck_fail.stderr b/tests/ui/pattern/deref-patterns/typeck_fail.stderr index 1c14802745a0c..3e2f356188220 100644 --- a/tests/ui/pattern/deref-patterns/typeck_fail.stderr +++ b/tests/ui/pattern/deref-patterns/typeck_fail.stderr @@ -7,13 +7,45 @@ LL | deref!("foo") => {} | ^^^^^ expected `str`, found `&str` error[E0308]: mismatched types - --> $DIR/typeck_fail.rs:13:16 + --> $DIR/typeck_fail.rs:10:9 + | +LL | match "foo".to_string() { + | ----------------- this expression has type `String` +... +LL | "foo" => {} + | ^^^^^ expected `String`, found `&str` + +error[E0308]: mismatched types + --> $DIR/typeck_fail.rs:15:16 | LL | match &"foo".to_string() { | ------------------ this expression has type `&String` LL | deref!("foo") => {} | ^^^^^ expected `str`, found `&str` -error: aborting due to 2 previous errors +error[E0308]: mismatched types + --> $DIR/typeck_fail.rs:17:9 + | +LL | match &"foo".to_string() { + | ------------------ this expression has type `&String` +... +LL | "foo" => {} + | ^^^^^ expected `&String`, found `&str` + | + = note: expected reference `&String` + found reference `&'static str` + +error[E0308]: mismatched types + --> $DIR/typeck_fail.rs:24:9 + | +LL | match Some(0) { + | ------- this expression has type `Option<{integer}>` +LL | Ok(0) => {} + | ^^^^^ expected `Option<{integer}>`, found `Result<_, _>` + | + = note: expected enum `Option<{integer}>` + found enum `Result<_, _>` + +error: aborting due to 5 previous errors For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/pattern/deref-patterns/unsatisfied-bounds.rs b/tests/ui/pattern/deref-patterns/unsatisfied-bounds.rs new file mode 100644 index 0000000000000..00064b2320c8d --- /dev/null +++ b/tests/ui/pattern/deref-patterns/unsatisfied-bounds.rs @@ -0,0 +1,21 @@ +#![feature(deref_patterns)] +#![allow(incomplete_features)] + +struct MyPointer; + +impl std::ops::Deref for MyPointer { + type Target = (); + fn deref(&self) -> &() { + &() + } +} + +fn main() { + // Test that we get a trait error if a user attempts implicit deref pats on their own impls. + // FIXME(deref_patterns): there should be a special diagnostic for missing `DerefPure`. + match MyPointer { + () => {} + //~^ the trait bound `MyPointer: DerefPure` is not satisfied + _ => {} + } +} diff --git a/tests/ui/pattern/deref-patterns/unsatisfied-bounds.stderr b/tests/ui/pattern/deref-patterns/unsatisfied-bounds.stderr new file mode 100644 index 0000000000000..983ce27865c99 --- /dev/null +++ b/tests/ui/pattern/deref-patterns/unsatisfied-bounds.stderr @@ -0,0 +1,9 @@ +error[E0277]: the trait bound `MyPointer: DerefPure` is not satisfied + --> $DIR/unsatisfied-bounds.rs:17:9 + | +LL | () => {} + | ^^ the trait `DerefPure` is not implemented for `MyPointer` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. From 91d0b579f020964bfe6bcaa86fbfc8fd493ae4db Mon Sep 17 00:00:00 2001 From: dianne Date: Sun, 9 Mar 2025 00:06:00 -0800 Subject: [PATCH 164/266] register `DerefMut` bounds for implicit mutable derefs --- compiler/rustc_hir_typeck/src/pat.rs | 53 +++++++++++++------ tests/ui/pattern/deref-patterns/bindings.rs | 28 ++++++++++ .../ui/pattern/deref-patterns/fake_borrows.rs | 7 +++ .../deref-patterns/fake_borrows.stderr | 11 +++- tests/ui/pattern/deref-patterns/ref-mut.rs | 9 ++++ .../ui/pattern/deref-patterns/ref-mut.stderr | 10 +++- 6 files changed, 100 insertions(+), 18 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 11ed7db9eb7f4..f33e270c357e1 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -344,6 +344,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ty = self.check_pat_inner(pat, opt_path_res, adjust_mode, expected, pat_info); self.write_ty(pat.hir_id, ty); + // If we implicitly inserted overloaded dereferences before matching, check the pattern to + // see if the dereferenced types need `DerefMut` bounds. + if let Some(derefed_tys) = self.typeck_results.borrow().pat_adjustments().get(pat.hir_id) + && derefed_tys.iter().any(|adjust| adjust.kind == PatAdjust::OverloadedDeref) + { + self.register_deref_mut_bounds_if_needed( + pat.span, + pat, + derefed_tys.iter().filter_map(|adjust| match adjust.kind { + PatAdjust::OverloadedDeref => Some(adjust.source), + PatAdjust::BuiltinDeref => None, + }), + ); + } + // (note_1): In most of the cases where (note_1) is referenced // (literals and constants being the exception), we relate types // using strict equality, even though subtyping would be sufficient. @@ -483,7 +498,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // requirement that `expected: DerefPure`. let inner_ty = self.deref_pat_target(pat.span, expected); // Once we've checked `pat`, we'll add a `DerefMut` bound if it contains any - // `ref mut` bindings. TODO: implement that, then reference here. + // `ref mut` bindings. See `Self::register_deref_mut_bounds_if_needed`. // Preserve the smart pointer type for THIR lowering and upvar analysis. self.typeck_results @@ -2315,20 +2330,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Ty<'tcx> { let target_ty = self.deref_pat_target(span, expected); self.check_pat(inner, target_ty, pat_info); - - // Check if the pattern has any `ref mut` bindings, which would require - // `DerefMut` to be emitted in MIR building instead of just `Deref`. - // We do this *after* checking the inner pattern, since we want to make - // sure to apply any match-ergonomics adjustments. - // TODO: move this to a separate definition to share it with implicit deref pats - if self.typeck_results.borrow().pat_has_ref_mut_binding(inner) { - self.register_bound( - expected, - self.tcx.require_lang_item(hir::LangItem::DerefMut, Some(span)), - self.misc(span), - ); - } - + self.register_deref_mut_bounds_if_needed(span, inner, [expected]); expected } @@ -2350,6 +2352,27 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.try_structurally_resolve_type(span, target_ty) } + /// Check if the interior of a deref pattern (either explicit or implicit) has any `ref mut` + /// bindings, which would require `DerefMut` to be emitted in MIR building instead of just + /// `Deref`. We do this *after* checking the inner pattern, since we want to make sure to + /// account for `ref mut` binding modes inherited from implicitly dereferencing `&mut` refs. + fn register_deref_mut_bounds_if_needed( + &self, + span: Span, + inner: &'tcx Pat<'tcx>, + derefed_tys: impl IntoIterator>, + ) { + if self.typeck_results.borrow().pat_has_ref_mut_binding(inner) { + for mutably_derefed_ty in derefed_tys { + self.register_bound( + mutably_derefed_ty, + self.tcx.require_lang_item(hir::LangItem::DerefMut, Some(span)), + self.misc(span), + ); + } + } + } + // Precondition: Pat is Ref(inner) fn check_pat_ref( &self, diff --git a/tests/ui/pattern/deref-patterns/bindings.rs b/tests/ui/pattern/deref-patterns/bindings.rs index ce10cd5439e16..c14d57f3f24e6 100644 --- a/tests/ui/pattern/deref-patterns/bindings.rs +++ b/tests/ui/pattern/deref-patterns/bindings.rs @@ -51,6 +51,7 @@ fn nested_vec(vecvec: Vec>) -> u32 { } } +#[cfg(explicit)] fn ref_mut(val: u32) -> u32 { let mut b = Box::new(0u32); match &mut b { @@ -64,6 +65,21 @@ fn ref_mut(val: u32) -> u32 { *x } +#[cfg(implicit)] +fn ref_mut(val: u32) -> u32 { + let mut b = Box::new((0u32,)); + match &mut b { + (_x,) if false => unreachable!(), + (x,) => { + *x = val; + } + _ => unreachable!(), + } + let (x,) = &b else { unreachable!() }; + *x +} + +#[cfg(explicit)] #[rustfmt::skip] fn or_and_guard(tuple: (u32, u32)) -> u32 { let mut sum = 0; @@ -75,6 +91,18 @@ fn or_and_guard(tuple: (u32, u32)) -> u32 { sum } +#[cfg(implicit)] +#[rustfmt::skip] +fn or_and_guard(tuple: (u32, u32)) -> u32 { + let mut sum = 0; + let b = Box::new(tuple); + match b { + (x, _) | (_, x) if { sum += x; false } => {}, + _ => {}, + } + sum +} + fn main() { assert_eq!(simple_vec(vec![1]), 1); assert_eq!(simple_vec(vec![1, 2]), 202); diff --git a/tests/ui/pattern/deref-patterns/fake_borrows.rs b/tests/ui/pattern/deref-patterns/fake_borrows.rs index 35fa9cbf7d859..bf614d7d66fda 100644 --- a/tests/ui/pattern/deref-patterns/fake_borrows.rs +++ b/tests/ui/pattern/deref-patterns/fake_borrows.rs @@ -11,4 +11,11 @@ fn main() { deref!(false) => {} _ => {}, } + match b { + true => {} + _ if { *b = true; false } => {} + //~^ ERROR cannot assign `*b` in match guard + false => {} + _ => {}, + } } diff --git a/tests/ui/pattern/deref-patterns/fake_borrows.stderr b/tests/ui/pattern/deref-patterns/fake_borrows.stderr index 6a591e6416c5d..8c060236d0dfe 100644 --- a/tests/ui/pattern/deref-patterns/fake_borrows.stderr +++ b/tests/ui/pattern/deref-patterns/fake_borrows.stderr @@ -7,6 +7,15 @@ LL | deref!(true) => {} LL | _ if { *b = true; false } => {} | ^^^^^^^^^ cannot assign -error: aborting due to 1 previous error +error[E0510]: cannot assign `*b` in match guard + --> $DIR/fake_borrows.rs:16:16 + | +LL | match b { + | - value is immutable in match guard +LL | true => {} +LL | _ if { *b = true; false } => {} + | ^^^^^^^^^ cannot assign + +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0510`. diff --git a/tests/ui/pattern/deref-patterns/ref-mut.rs b/tests/ui/pattern/deref-patterns/ref-mut.rs index 1918008a761a7..43738671346d3 100644 --- a/tests/ui/pattern/deref-patterns/ref-mut.rs +++ b/tests/ui/pattern/deref-patterns/ref-mut.rs @@ -8,10 +8,19 @@ fn main() { deref!(x) => {} _ => {} } + match &mut vec![1] { + [x] => {} + _ => {} + } match &mut Rc::new(1) { deref!(x) => {} //~^ ERROR the trait bound `Rc<{integer}>: DerefMut` is not satisfied _ => {} } + match &mut Rc::new((1,)) { + (x,) => {} + //~^ ERROR the trait bound `Rc<({integer},)>: DerefMut` is not satisfied + _ => {} + } } diff --git a/tests/ui/pattern/deref-patterns/ref-mut.stderr b/tests/ui/pattern/deref-patterns/ref-mut.stderr index 41f1c3061ce6d..24a35b418e95c 100644 --- a/tests/ui/pattern/deref-patterns/ref-mut.stderr +++ b/tests/ui/pattern/deref-patterns/ref-mut.stderr @@ -8,13 +8,19 @@ LL | #![feature(deref_patterns)] = note: `#[warn(incomplete_features)]` on by default error[E0277]: the trait bound `Rc<{integer}>: DerefMut` is not satisfied - --> $DIR/ref-mut.rs:13:9 + --> $DIR/ref-mut.rs:17:9 | LL | deref!(x) => {} | ^^^^^^^^^ the trait `DerefMut` is not implemented for `Rc<{integer}>` | = note: this error originates in the macro `deref` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 1 previous error; 1 warning emitted +error[E0277]: the trait bound `Rc<({integer},)>: DerefMut` is not satisfied + --> $DIR/ref-mut.rs:22:9 + | +LL | (x,) => {} + | ^^^^ the trait `DerefMut` is not implemented for `Rc<({integer},)>` + +error: aborting due to 2 previous errors; 1 warning emitted For more information about this error, try `rustc --explain E0277`. From d6df469c3d5d87bd5b853812bddae2ca2cbd1cb8 Mon Sep 17 00:00:00 2001 From: dianne Date: Mon, 7 Apr 2025 12:06:03 -0700 Subject: [PATCH 165/266] refactor path pattern checking to get info for peeling See the doc comment on `ResolvedPat` for more information. This and the next couple commits split resolution apart from checking for path, struct, and tuple struct patterns, in order to find the pattern's type before peeling the scrutinee. This helps us avoid peeling the scrutinee when the pattern could match it. The reason this handles errors from resolution after peeling is for struct and tuple struct patterns: we check their subpatterns even when they fail to resolve, to potentially catch more resolution errors. By doing this after peeling, we're able to use the updated `PatInfo`. I don't know if there's currently any observable difference from using the outdated `PatInfo`, but it could potentially be a source of subtle diagnostic bugs in the future, so I'm opting to peel first. --- compiler/rustc_hir_typeck/src/pat.rs | 137 +++++++++++++++++---------- 1 file changed, 89 insertions(+), 48 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index f33e270c357e1..327b2736aab13 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -34,7 +34,7 @@ use ty::adjustment::{PatAdjust, PatAdjustment}; use super::report_unexpected_variant_res; use crate::expectation::Expectation; use crate::gather_locals::DeclOrigin; -use crate::{FnCtxt, LoweredTy, errors}; +use crate::{FnCtxt, errors}; const CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ: &str = "\ This error indicates that a pointer to a trait type cannot be implicitly dereferenced by a \ @@ -258,6 +258,44 @@ enum InheritedRefMatchRule { }, } +/// When checking patterns containing paths, we need to know the path's resolution to determine +/// whether to apply match ergonomics and implicitly dereference the scrutinee. For instance, when +/// the `deref_patterns` feature is enabled and we're matching against a scrutinee of type +/// `Cow<'a, Option>`, we insert an implicit dereference to allow the pattern `Some(_)` to type, +/// but we must not dereference it when checking the pattern `Cow::Borrowed(_)`. +/// +/// `ResolvedPat` contains the information from resolution needed to determine match ergonomics +/// adjustments, and to finish checking the pattern once we know its adjusted type. +#[derive(Clone, Copy, Debug)] +struct ResolvedPat<'tcx> { + /// The type of the pattern, to be checked against the type of the scrutinee after peeling. This + /// is also used to avoid peeling the scrutinee's constructors (see the `Cow` example above). + ty: Ty<'tcx>, + kind: ResolvedPatKind<'tcx>, +} + +#[derive(Clone, Copy, Debug)] +enum ResolvedPatKind<'tcx> { + Path { res: Res, pat_res: Res, segments: &'tcx [hir::PathSegment<'tcx>] }, +} + +impl<'tcx> ResolvedPat<'tcx> { + fn adjust_mode(&self) -> AdjustMode { + let ResolvedPatKind::Path { res, .. } = self.kind; + if matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _)) { + // These constants can be of a reference type, e.g. `const X: &u8 = &0;`. + // Peeling the reference types too early will cause type checking failures. + // Although it would be possible to *also* peel the types of the constants too. + AdjustMode::Pass + } else { + // The remaining possible resolutions for path, struct, and tuple struct patterns are + // ADT constructors. As such, we may peel references freely, but we must not peel the + // ADT itself from the scrutinee if it's a smart pointer. + AdjustMode::Peel { kind: PeelKind::Implicit } + } + } +} + impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Experimental pattern feature: after matching against a shared reference, do we limit the /// default binding mode in subpatterns to be `ref` when it would otherwise be `ref mut`? @@ -334,13 +372,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Conversely, inside this module, `check_pat_top` should never be used. #[instrument(level = "debug", skip(self, pat_info))] fn check_pat(&self, pat: &'tcx Pat<'tcx>, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>) { + // For patterns containing paths, we need the path's resolution to determine whether to + // implicitly dereference the scrutinee before matching. let opt_path_res = match pat.kind { PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), hir_id, span }) => { - Some(self.resolve_ty_and_res_fully_qualified_call(qpath, *hir_id, *span)) + Some(self.resolve_pat_path(*hir_id, *span, qpath)) } _ => None, }; - let adjust_mode = self.calc_adjust_mode(pat, opt_path_res.map(|(res, ..)| res)); + let adjust_mode = self.calc_adjust_mode(pat, opt_path_res); let ty = self.check_pat_inner(pat, opt_path_res, adjust_mode, expected, pat_info); self.write_ty(pat.hir_id, ty); @@ -406,7 +446,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn check_pat_inner( &self, pat: &'tcx Pat<'tcx>, - opt_path_res: Option<(Res, Option>, &'tcx [hir::PathSegment<'tcx>])>, + opt_path_res: Option, ErrorGuaranteed>>, adjust_mode: AdjustMode, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, @@ -515,16 +555,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { PatKind::Missing | PatKind::Wild | PatKind::Err(_) => expected, // We allow any type here; we ensure that the type is uninhabited during match checking. PatKind::Never => expected, - PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), hir_id, span }) => { - let ty = self.check_pat_path( - *hir_id, - pat.hir_id, - *span, - qpath, - opt_path_res.unwrap(), - expected, - &pat_info.top_info, - ); + PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), hir_id, .. }) => { + let ty = match opt_path_res.unwrap() { + Ok(ref pr) => { + self.check_pat_path(pat.hir_id, pat.span, pr, expected, &pat_info.top_info) + } + Err(guar) => Ty::new_error(self.tcx, guar), + }; self.write_ty(*hir_id, ty); ty } @@ -566,8 +603,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// How should the binding mode and expected type be adjusted? /// - /// When the pattern is a path pattern, `opt_path_res` must be `Some(res)`. - fn calc_adjust_mode(&self, pat: &'tcx Pat<'tcx>, opt_path_res: Option) -> AdjustMode { + /// When the pattern contains a path, `opt_path_res` must be `Some(path_res)`. + fn calc_adjust_mode( + &self, + pat: &'tcx Pat<'tcx>, + opt_path_res: Option, ErrorGuaranteed>>, + ) -> AdjustMode { match &pat.kind { // Type checking these product-like types successfully always require // that the expected type be of those types and not reference types. @@ -583,17 +624,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { | PatKind::Deref(_) => AdjustMode::Peel { kind: PeelKind::ExplicitDerefPat }, // A never pattern behaves somewhat like a literal or unit variant. PatKind::Never => AdjustMode::Peel { kind: PeelKind::Implicit }, - PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), .. }) => match opt_path_res.unwrap() { - // These constants can be of a reference type, e.g. `const X: &u8 = &0;`. - // Peeling the reference types too early will cause type checking failures. - // Although it would be possible to *also* peel the types of the constants too. - Res::Def(DefKind::Const | DefKind::AssocConst, _) => AdjustMode::Pass, - // In the `ValueNS`, we have `SelfCtor(..) | Ctor(_, Const), _)` remaining which - // could successfully compile. The former being `Self` requires a unit struct. - // In either case, and unlike constants, the pattern itself cannot be - // a reference type wherefore peeling doesn't give up any expressiveness. - _ => AdjustMode::Peel { kind: PeelKind::Implicit }, - }, + // For patterns with paths, how we peel the scrutinee depends on the path's resolution. + PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), .. }) => { + // If there was an error resolving the path, default to peeling everything. + opt_path_res.unwrap().map_or(AdjustMode::Peel { kind: PeelKind::Implicit }, |pr| pr.adjust_mode()) + } // String and byte-string literals result in types `&str` and `&[u8]` respectively. // All other literals result in non-reference types. @@ -1216,31 +1251,27 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - fn check_pat_path( + fn resolve_pat_path( &self, path_id: HirId, - pat_id_for_diag: HirId, span: Span, - qpath: &hir::QPath<'_>, - path_resolution: (Res, Option>, &'tcx [hir::PathSegment<'tcx>]), - expected: Ty<'tcx>, - ti: &TopInfo<'tcx>, - ) -> Ty<'tcx> { + qpath: &'tcx hir::QPath<'_>, + ) -> Result, ErrorGuaranteed> { let tcx = self.tcx; - // We have already resolved the path. - let (res, opt_ty, segments) = path_resolution; + let (res, opt_ty, segments) = + self.resolve_ty_and_res_fully_qualified_call(qpath, path_id, span); match res { Res::Err => { let e = self.dcx().span_delayed_bug(qpath.span(), "`Res::Err` but no error emitted"); self.set_tainted_by_errors(e); - return Ty::new_error(tcx, e); + return Err(e); } Res::Def(DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Variant, _) => { let expected = "unit struct, unit variant or constant"; let e = report_unexpected_variant_res(tcx, res, None, qpath, span, E0533, expected); - return Ty::new_error(tcx, e); + return Err(e); } Res::SelfCtor(def_id) => { if let ty::Adt(adt_def, _) = *tcx.type_of(def_id).skip_binder().kind() @@ -1258,7 +1289,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { E0533, "unit struct", ); - return Ty::new_error(tcx, e); + return Err(e); } } Res::Def( @@ -1271,15 +1302,26 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => bug!("unexpected pattern resolution: {:?}", res), } - // Type-check the path. + // Find the type of the path pattern, for later checking. let (pat_ty, pat_res) = self.instantiate_value_path(segments, opt_ty, res, span, span, path_id); + Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Path { res, pat_res, segments } }) + } + + fn check_pat_path( + &self, + pat_id_for_diag: HirId, + span: Span, + resolved: &ResolvedPat<'tcx>, + expected: Ty<'tcx>, + ti: &TopInfo<'tcx>, + ) -> Ty<'tcx> { if let Err(err) = - self.demand_suptype_with_origin(&self.pattern_cause(ti, span), expected, pat_ty) + self.demand_suptype_with_origin(&self.pattern_cause(ti, span), expected, resolved.ty) { - self.emit_bad_pat_path(err, pat_id_for_diag, span, res, pat_res, pat_ty, segments); + self.emit_bad_pat_path(err, pat_id_for_diag, span, resolved); } - pat_ty + resolved.ty } fn maybe_suggest_range_literal( @@ -1322,11 +1364,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { mut e: Diag<'_>, hir_id: HirId, pat_span: Span, - res: Res, - pat_res: Res, - pat_ty: Ty<'tcx>, - segments: &'tcx [hir::PathSegment<'tcx>], + resolved_pat: &ResolvedPat<'tcx>, ) { + let ResolvedPatKind::Path { res, pat_res, segments } = resolved_pat.kind; + if let Some(span) = self.tcx.hir_res_span(pat_res) { e.span_label(span, format!("{} defined here", res.descr())); if let [hir::PathSegment { ident, .. }] = &*segments { @@ -1349,7 +1390,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } _ => { - let (type_def_id, item_def_id) = match pat_ty.kind() { + let (type_def_id, item_def_id) = match resolved_pat.ty.kind() { ty::Adt(def, _) => match res { Res::Def(DefKind::Const, def_id) => (Some(def.did()), Some(def_id)), _ => (None, None), From 9196048edddd9eb18294f3eab34453c0f7eb25b3 Mon Sep 17 00:00:00 2001 From: dianne Date: Mon, 3 Mar 2025 16:26:20 -0800 Subject: [PATCH 166/266] refactor struct pattern checking to get info for peeling See the previous commit for details. This doesn't yet extract the struct pat's type's ADT def before peeling, but it should now be possible. --- compiler/rustc_hir_typeck/src/pat.rs | 51 +++++++++++++++++----------- 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 327b2736aab13..c81965967f05e 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -277,12 +277,14 @@ struct ResolvedPat<'tcx> { #[derive(Clone, Copy, Debug)] enum ResolvedPatKind<'tcx> { Path { res: Res, pat_res: Res, segments: &'tcx [hir::PathSegment<'tcx>] }, + Struct { variant: &'tcx VariantDef }, } impl<'tcx> ResolvedPat<'tcx> { fn adjust_mode(&self) -> AdjustMode { - let ResolvedPatKind::Path { res, .. } = self.kind; - if matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _)) { + if let ResolvedPatKind::Path { res, .. } = self.kind + && matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _)) + { // These constants can be of a reference type, e.g. `const X: &u8 = &0;`. // Peeling the reference types too early will cause type checking failures. // Although it would be possible to *also* peel the types of the constants too. @@ -378,6 +380,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), hir_id, span }) => { Some(self.resolve_pat_path(*hir_id, *span, qpath)) } + PatKind::Struct(ref qpath, ..) => Some(self.resolve_pat_struct(pat, qpath)), _ => None, }; let adjust_mode = self.calc_adjust_mode(pat, opt_path_res); @@ -575,9 +578,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { PatKind::TupleStruct(ref qpath, subpats, ddpos) => { self.check_pat_tuple_struct(pat, qpath, subpats, ddpos, expected, pat_info) } - PatKind::Struct(ref qpath, fields, has_rest_pat) => { - self.check_pat_struct(pat, qpath, fields, has_rest_pat, expected, pat_info) - } + PatKind::Struct(_, fields, has_rest_pat) => match opt_path_res.unwrap() { + Ok(ResolvedPat { ty, kind: ResolvedPatKind::Struct { variant } }) => self + .check_pat_struct(pat, fields, has_rest_pat, ty, variant, expected, pat_info), + Err(guar) => { + let ty_err = Ty::new_error(self.tcx, guar); + for field in fields { + self.check_pat(field.pat, ty_err, pat_info); + } + ty_err + } + Ok(pr) => span_bug!(pat.span, "struct pattern resolved to {pr:?}"), + }, PatKind::Guard(pat, cond) => { self.check_pat(pat, expected, pat_info); self.check_expr_has_type_or_error(cond, self.tcx.types.bool, |_| {}); @@ -1220,27 +1232,26 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ok(()) } - fn check_pat_struct( + fn resolve_pat_struct( &self, pat: &'tcx Pat<'tcx>, qpath: &hir::QPath<'tcx>, + ) -> Result, ErrorGuaranteed> { + // Resolve the path and check the definition for errors. + let (variant, pat_ty) = self.check_struct_path(qpath, pat.hir_id)?; + Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Struct { variant } }) + } + + fn check_pat_struct( + &self, + pat: &'tcx Pat<'tcx>, fields: &'tcx [hir::PatField<'tcx>], has_rest_pat: bool, + pat_ty: Ty<'tcx>, + variant: &'tcx VariantDef, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> Ty<'tcx> { - // Resolve the path and check the definition for errors. - let (variant, pat_ty) = match self.check_struct_path(qpath, pat.hir_id) { - Ok(data) => data, - Err(guar) => { - let err = Ty::new_error(self.tcx, guar); - for field in fields { - self.check_pat(field.pat, err, pat_info); - } - return err; - } - }; - // Type-check the path. let _ = self.demand_eqtype_pat(pat.span, expected, pat_ty, &pat_info.top_info); @@ -1366,7 +1377,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pat_span: Span, resolved_pat: &ResolvedPat<'tcx>, ) { - let ResolvedPatKind::Path { res, pat_res, segments } = resolved_pat.kind; + let ResolvedPatKind::Path { res, pat_res, segments } = resolved_pat.kind else { + span_bug!(pat_span, "unexpected resolution for path pattern: {resolved_pat:?}"); + }; if let Some(span) = self.tcx.hir_res_span(pat_res) { e.span_label(span, format!("{} defined here", res.descr())); From 1f40e9aa6a0f0a8e6e4188f15f25d920892bca6a Mon Sep 17 00:00:00 2001 From: dianne Date: Mon, 3 Mar 2025 16:50:53 -0800 Subject: [PATCH 167/266] refactor tuple struct pattern checking to get info for peeling See the previous two commits. --- compiler/rustc_hir_typeck/src/pat.rs | 66 ++++++++++++++++++---------- 1 file changed, 44 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index c81965967f05e..da5153bed12cd 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -278,6 +278,7 @@ struct ResolvedPat<'tcx> { enum ResolvedPatKind<'tcx> { Path { res: Res, pat_res: Res, segments: &'tcx [hir::PathSegment<'tcx>] }, Struct { variant: &'tcx VariantDef }, + TupleStruct { res: Res, variant: &'tcx VariantDef }, } impl<'tcx> ResolvedPat<'tcx> { @@ -381,6 +382,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Some(self.resolve_pat_path(*hir_id, *span, qpath)) } PatKind::Struct(ref qpath, ..) => Some(self.resolve_pat_struct(pat, qpath)), + PatKind::TupleStruct(ref qpath, ..) => Some(self.resolve_pat_tuple_struct(pat, qpath)), _ => None, }; let adjust_mode = self.calc_adjust_mode(pat, opt_path_res); @@ -575,9 +577,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { PatKind::Binding(ba, var_id, ident, sub) => { self.check_pat_ident(pat, ba, var_id, ident, sub, expected, pat_info) } - PatKind::TupleStruct(ref qpath, subpats, ddpos) => { - self.check_pat_tuple_struct(pat, qpath, subpats, ddpos, expected, pat_info) - } + PatKind::TupleStruct(ref qpath, subpats, ddpos) => match opt_path_res.unwrap() { + Ok(ResolvedPat { ty, kind: ResolvedPatKind::TupleStruct { res, variant } }) => self + .check_pat_tuple_struct( + pat, qpath, subpats, ddpos, res, ty, variant, expected, pat_info, + ), + Err(guar) => { + let ty_err = Ty::new_error(self.tcx, guar); + for subpat in subpats { + self.check_pat(subpat, ty_err, pat_info); + } + ty_err + } + Ok(pr) => span_bug!(pat.span, "tuple struct pattern resolved to {pr:?}"), + }, PatKind::Struct(_, fields, has_rest_pat) => match opt_path_res.unwrap() { Ok(ResolvedPat { ty, kind: ResolvedPatKind::Struct { variant } }) => self .check_pat_struct(pat, fields, has_rest_pat, ty, variant, expected, pat_info), @@ -1443,26 +1456,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { e.emit(); } - fn check_pat_tuple_struct( + fn resolve_pat_tuple_struct( &self, pat: &'tcx Pat<'tcx>, qpath: &'tcx hir::QPath<'tcx>, - subpats: &'tcx [Pat<'tcx>], - ddpos: hir::DotDotPos, - expected: Ty<'tcx>, - pat_info: PatInfo<'tcx>, - ) -> Ty<'tcx> { + ) -> Result, ErrorGuaranteed> { let tcx = self.tcx; - let on_error = |e| { - for pat in subpats { - self.check_pat(pat, Ty::new_error(tcx, e), pat_info); - } - }; let report_unexpected_res = |res: Res| { let expected = "tuple struct or tuple variant"; let e = report_unexpected_variant_res(tcx, res, None, qpath, pat.span, E0164, expected); - on_error(e); - e + Err(e) }; // Resolve the path and check the definition for errors. @@ -1471,16 +1474,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if res == Res::Err { let e = self.dcx().span_delayed_bug(pat.span, "`Res::Err` but no error emitted"); self.set_tainted_by_errors(e); - on_error(e); - return Ty::new_error(tcx, e); + return Err(e); } // Type-check the path. let (pat_ty, res) = self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.span, pat.hir_id); if !pat_ty.is_fn() { - let e = report_unexpected_res(res); - return Ty::new_error(tcx, e); + return report_unexpected_res(res); } let variant = match res { @@ -1488,8 +1489,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.dcx().span_bug(pat.span, "`Res::Err` but no error emitted"); } Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) => { - let e = report_unexpected_res(res); - return Ty::new_error(tcx, e); + return report_unexpected_res(res); } Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) => tcx.expect_variant_res(res), _ => bug!("unexpected pattern resolution: {:?}", res), @@ -1499,6 +1499,28 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let pat_ty = pat_ty.fn_sig(tcx).output(); let pat_ty = pat_ty.no_bound_vars().expect("expected fn type"); + Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::TupleStruct { res, variant } }) + } + + fn check_pat_tuple_struct( + &self, + pat: &'tcx Pat<'tcx>, + qpath: &'tcx hir::QPath<'tcx>, + subpats: &'tcx [Pat<'tcx>], + ddpos: hir::DotDotPos, + res: Res, + pat_ty: Ty<'tcx>, + variant: &'tcx VariantDef, + expected: Ty<'tcx>, + pat_info: PatInfo<'tcx>, + ) -> Ty<'tcx> { + let tcx = self.tcx; + let on_error = |e| { + for pat in subpats { + self.check_pat(pat, Ty::new_error(tcx, e), pat_info); + } + }; + // Type-check the tuple struct pattern against the expected type. let diag = self.demand_eqtype_pat_diag(pat.span, expected, pat_ty, &pat_info.top_info); let had_err = diag.map_err(|diag| diag.emit()); From b7fbf20fe1a46c1d5443399f9c624abf00cfb021 Mon Sep 17 00:00:00 2001 From: Joshua Liebow-Feeser Date: Fri, 11 Apr 2025 16:16:12 -0700 Subject: [PATCH 168/266] transmutability: Refactor tests for simplicity --- .../src/maybe_transmutable/tests.rs | 140 +++++++++--------- 1 file changed, 74 insertions(+), 66 deletions(-) diff --git a/compiler/rustc_transmute/src/maybe_transmutable/tests.rs b/compiler/rustc_transmute/src/maybe_transmutable/tests.rs index 4d81382eba02c..69a6b1b77f4b0 100644 --- a/compiler/rustc_transmute/src/maybe_transmutable/tests.rs +++ b/compiler/rustc_transmute/src/maybe_transmutable/tests.rs @@ -1,93 +1,115 @@ use itertools::Itertools; use super::query_context::test::{Def, UltraMinimal}; -use crate::maybe_transmutable::MaybeTransmutableQuery; -use crate::{Reason, layout}; +use crate::{Answer, Assume, Reason, layout}; -mod safety { - use super::*; - use crate::Answer; +type Tree = layout::Tree; +type Dfa = layout::Dfa; - type Tree = layout::Tree; +trait Representation { + fn is_transmutable(src: Self, dst: Self, assume: Assume) -> Answer; +} - const DST_HAS_SAFETY_INVARIANTS: Answer = - Answer::No(crate::Reason::DstMayHaveSafetyInvariants); +impl Representation for Tree { + fn is_transmutable(src: Self, dst: Self, assume: Assume) -> Answer { + crate::maybe_transmutable::MaybeTransmutableQuery::new(src, dst, assume, UltraMinimal) + .answer() + } +} - fn is_transmutable(src: &Tree, dst: &Tree, assume_safety: bool) -> crate::Answer { - let src = src.clone(); - let dst = dst.clone(); - // The only dimension of the transmutability analysis we want to test - // here is the safety analysis. To ensure this, we disable all other - // toggleable aspects of the transmutability analysis. - let assume = crate::Assume { - alignment: true, - lifetimes: true, - validity: true, - safety: assume_safety, - }; +impl Representation for Dfa { + fn is_transmutable(src: Self, dst: Self, assume: Assume) -> Answer { crate::maybe_transmutable::MaybeTransmutableQuery::new(src, dst, assume, UltraMinimal) .answer() } +} + +fn is_transmutable( + src: &R, + dst: &R, + assume: Assume, +) -> crate::Answer { + let src = src.clone(); + let dst = dst.clone(); + // The only dimension of the transmutability analysis we want to test + // here is the safety analysis. To ensure this, we disable all other + // toggleable aspects of the transmutability analysis. + R::is_transmutable(src, dst, assume) +} + +mod safety { + use super::*; + use crate::Answer; + + const DST_HAS_SAFETY_INVARIANTS: Answer = + Answer::No(crate::Reason::DstMayHaveSafetyInvariants); #[test] fn src_safe_dst_safe() { let src = Tree::Def(Def::NoSafetyInvariants).then(Tree::u8()); let dst = Tree::Def(Def::NoSafetyInvariants).then(Tree::u8()); - assert_eq!(is_transmutable(&src, &dst, false), Answer::Yes); - assert_eq!(is_transmutable(&src, &dst, true), Answer::Yes); + assert_eq!(is_transmutable(&src, &dst, Assume::default()), Answer::Yes); + assert_eq!( + is_transmutable(&src, &dst, Assume { safety: true, ..Assume::default() }), + Answer::Yes + ); } #[test] fn src_safe_dst_unsafe() { let src = Tree::Def(Def::NoSafetyInvariants).then(Tree::u8()); let dst = Tree::Def(Def::HasSafetyInvariants).then(Tree::u8()); - assert_eq!(is_transmutable(&src, &dst, false), DST_HAS_SAFETY_INVARIANTS); - assert_eq!(is_transmutable(&src, &dst, true), Answer::Yes); + assert_eq!(is_transmutable(&src, &dst, Assume::default()), DST_HAS_SAFETY_INVARIANTS); + assert_eq!( + is_transmutable(&src, &dst, Assume { safety: true, ..Assume::default() }), + Answer::Yes + ); } #[test] fn src_unsafe_dst_safe() { let src = Tree::Def(Def::HasSafetyInvariants).then(Tree::u8()); let dst = Tree::Def(Def::NoSafetyInvariants).then(Tree::u8()); - assert_eq!(is_transmutable(&src, &dst, false), Answer::Yes); - assert_eq!(is_transmutable(&src, &dst, true), Answer::Yes); + assert_eq!(is_transmutable(&src, &dst, Assume::default()), Answer::Yes); + assert_eq!( + is_transmutable(&src, &dst, Assume { safety: true, ..Assume::default() }), + Answer::Yes + ); } #[test] fn src_unsafe_dst_unsafe() { let src = Tree::Def(Def::HasSafetyInvariants).then(Tree::u8()); let dst = Tree::Def(Def::HasSafetyInvariants).then(Tree::u8()); - assert_eq!(is_transmutable(&src, &dst, false), DST_HAS_SAFETY_INVARIANTS); - assert_eq!(is_transmutable(&src, &dst, true), Answer::Yes); + assert_eq!(is_transmutable(&src, &dst, Assume::default()), DST_HAS_SAFETY_INVARIANTS); + assert_eq!( + is_transmutable(&src, &dst, Assume { safety: true, ..Assume::default() }), + Answer::Yes + ); } } mod bool { use super::*; - use crate::Answer; #[test] fn should_permit_identity_transmutation_tree() { - let answer = crate::maybe_transmutable::MaybeTransmutableQuery::new( - layout::Tree::::bool(), - layout::Tree::::bool(), - crate::Assume { alignment: false, lifetimes: false, validity: true, safety: false }, - UltraMinimal, - ) - .answer(); - assert_eq!(answer, Answer::Yes); + let src = Tree::bool(); + assert_eq!(is_transmutable(&src, &src, Assume::default()), Answer::Yes); + assert_eq!( + is_transmutable(&src, &src, Assume { validity: true, ..Assume::default() }), + Answer::Yes + ); } #[test] fn should_permit_identity_transmutation_dfa() { - let answer = crate::maybe_transmutable::MaybeTransmutableQuery::new( - layout::Dfa::::bool(), - layout::Dfa::::bool(), - crate::Assume { alignment: false, lifetimes: false, validity: true, safety: false }, - UltraMinimal, - ) - .answer(); - assert_eq!(answer, Answer::Yes); + let src = Dfa::bool(); + assert_eq!(is_transmutable(&src, &src, Assume::default()), Answer::Yes); + assert_eq!( + is_transmutable(&src, &src, Assume { validity: true, ..Assume::default() }), + Answer::Yes + ); } #[test] @@ -122,13 +144,7 @@ mod bool { if src_set.is_subset(&dst_set) { assert_eq!( Answer::Yes, - MaybeTransmutableQuery::new( - src_layout.clone(), - dst_layout.clone(), - crate::Assume { validity: false, ..crate::Assume::default() }, - UltraMinimal, - ) - .answer(), + is_transmutable(&src_layout, &dst_layout, Assume::default()), "{:?} SHOULD be transmutable into {:?}", src_layout, dst_layout @@ -136,13 +152,11 @@ mod bool { } else if !src_set.is_disjoint(&dst_set) { assert_eq!( Answer::Yes, - MaybeTransmutableQuery::new( - src_layout.clone(), - dst_layout.clone(), - crate::Assume { validity: true, ..crate::Assume::default() }, - UltraMinimal, - ) - .answer(), + is_transmutable( + &src_layout, + &dst_layout, + Assume { validity: true, ..Assume::default() } + ), "{:?} SHOULD be transmutable (assuming validity) into {:?}", src_layout, dst_layout @@ -150,13 +164,7 @@ mod bool { } else { assert_eq!( Answer::No(Reason::DstIsBitIncompatible), - MaybeTransmutableQuery::new( - src_layout.clone(), - dst_layout.clone(), - crate::Assume { validity: false, ..crate::Assume::default() }, - UltraMinimal, - ) - .answer(), + is_transmutable(&src_layout, &dst_layout, Assume::default()), "{:?} should NOT be transmutable into {:?}", src_layout, dst_layout From 8b09cbba210741a16bedb60d54b7b06b78021ba8 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Tue, 15 Apr 2025 16:27:14 -0400 Subject: [PATCH 169/266] Update cargo * The license exception of sha1_smol with BSD-3-Clause is no longer needed, as `gix-*` doesn't depend on it. * Cargo depends on zlib-rs, which is distributed under Zlib license --- src/tools/cargo | 2 +- src/tools/tidy/src/deps.rs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/tools/cargo b/src/tools/cargo index 864f74d4eadca..d811228b14ae2 160000 --- a/src/tools/cargo +++ b/src/tools/cargo @@ -1 +1 @@ -Subproject commit 864f74d4eadcaea3eeda37a2e7f4d34de233d51e +Subproject commit d811228b14ae2707323f37346aee3f4147e247e6 diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 88c2a02798ace..8eca2eb450390 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -132,15 +132,16 @@ const EXCEPTIONS_CARGO: ExceptionList = &[ ("fiat-crypto", "MIT OR Apache-2.0 OR BSD-1-Clause"), ("foldhash", "Zlib"), ("im-rc", "MPL-2.0+"), + ("libz-rs-sys", "Zlib"), ("normalize-line-endings", "Apache-2.0"), ("openssl", "Apache-2.0"), ("ryu", "Apache-2.0 OR BSL-1.0"), // BSL is not acceptble, but we use it under Apache-2.0 - ("sha1_smol", "BSD-3-Clause"), ("similar", "Apache-2.0"), ("sized-chunks", "MPL-2.0+"), ("subtle", "BSD-3-Clause"), ("supports-hyperlinks", "Apache-2.0"), ("unicode-bom", "Apache-2.0"), + ("zlib-rs", "Zlib"), // tidy-alphabetical-end ]; From 923d95cc9f318a88cde9166dd44f785c8bcdadfb Mon Sep 17 00:00:00 2001 From: dianne Date: Sat, 8 Mar 2025 21:30:48 -0800 Subject: [PATCH 170/266] don't peel ADTs the pattern could match This is the use for the previous commits' refactors; see the messages there for more information. --- compiler/rustc_hir_typeck/src/pat.rs | 49 +++++++++++++------ .../deref-patterns/implicit-const-deref.rs | 19 +++++++ .../implicit-const-deref.stderr | 16 ++++++ .../deref-patterns/implicit-cow-deref.rs | 44 +++++++++++++++++ 4 files changed, 114 insertions(+), 14 deletions(-) create mode 100644 tests/ui/pattern/deref-patterns/implicit-const-deref.rs create mode 100644 tests/ui/pattern/deref-patterns/implicit-const-deref.stderr create mode 100644 tests/ui/pattern/deref-patterns/implicit-cow-deref.rs diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index da5153bed12cd..46916f22d0e29 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -9,6 +9,7 @@ use rustc_errors::{ Applicability, Diag, ErrorGuaranteed, MultiSpan, pluralize, struct_span_code_err, }; use rustc_hir::def::{CtorKind, DefKind, Res}; +use rustc_hir::def_id::DefId; use rustc_hir::pat_util::EnumerateAndAdjustIterator; use rustc_hir::{ self as hir, BindingMode, ByRef, ExprKind, HirId, LangItem, Mutability, Pat, PatExpr, @@ -179,8 +180,16 @@ enum PeelKind { /// ADTs. In order to peel only as much as necessary for the pattern to match, the `until_adt` /// field contains the ADT def that the pattern is a constructor for, if applicable, so that we /// don't peel it. See [`ResolvedPat`] for more information. - // TODO: add `ResolvedPat` and `until_adt`. - Implicit, + Implicit { until_adt: Option }, +} + +impl AdjustMode { + const fn peel_until_adt(opt_adt_def: Option) -> AdjustMode { + AdjustMode::Peel { kind: PeelKind::Implicit { until_adt: opt_adt_def } } + } + const fn peel_all() -> AdjustMode { + AdjustMode::peel_until_adt(None) + } } /// `ref mut` bindings (explicit or match-ergonomics) are not allowed behind an `&` reference. @@ -294,7 +303,7 @@ impl<'tcx> ResolvedPat<'tcx> { // The remaining possible resolutions for path, struct, and tuple struct patterns are // ADT constructors. As such, we may peel references freely, but we must not peel the // ADT itself from the scrutinee if it's a smart pointer. - AdjustMode::Peel { kind: PeelKind::Implicit } + AdjustMode::peel_until_adt(self.ty.ty_adt_def().map(|adt| adt.did())) } } } @@ -521,14 +530,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // If `deref_patterns` is enabled, peel a smart pointer from the scrutinee type. See the // examples in `tests/ui/pattern/deref_patterns/`. _ if self.tcx.features().deref_patterns() - && let AdjustMode::Peel { kind: PeelKind::Implicit } = adjust_mode + && let AdjustMode::Peel { kind: PeelKind::Implicit { until_adt } } = adjust_mode && pat.default_binding_modes // For simplicity, only apply overloaded derefs if `expected` is a known ADT. // FIXME(deref_patterns): we'll get better diagnostics for users trying to // implicitly deref generics if we allow them here, but primitives, tuples, and // inference vars definitely should be stopped. Figure out what makes most sense. - // TODO: stop peeling if the pattern is a constructor for the scrutinee type - && expected.is_adt() + && let ty::Adt(scrutinee_adt, _) = *expected.kind() + // Don't peel if the pattern type already matches the scrutinee. E.g., stop here if + // matching on a `Cow<'a, T>` scrutinee with a `Cow::Owned(_)` pattern. + && until_adt != Some(scrutinee_adt.did()) // At this point, the pattern isn't able to match `expected` without peeling. Check // that it implements `Deref` before assuming it's a smart pointer, to get a normal // type error instead of a missing impl error if not. This only checks for `Deref`, @@ -637,22 +648,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match &pat.kind { // Type checking these product-like types successfully always require // that the expected type be of those types and not reference types. - PatKind::Struct(..) - | PatKind::TupleStruct(..) - | PatKind::Tuple(..) + PatKind::Tuple(..) | PatKind::Range(..) - | PatKind::Slice(..) => AdjustMode::Peel { kind: PeelKind::Implicit }, + | PatKind::Slice(..) => AdjustMode::peel_all(), // When checking an explicit deref pattern, only peel reference types. // FIXME(deref_patterns): If box patterns and deref patterns need to coexist, box // patterns may want `PeelKind::Implicit`, stopping on encountering a box. | PatKind::Box(_) | PatKind::Deref(_) => AdjustMode::Peel { kind: PeelKind::ExplicitDerefPat }, // A never pattern behaves somewhat like a literal or unit variant. - PatKind::Never => AdjustMode::Peel { kind: PeelKind::Implicit }, + PatKind::Never => AdjustMode::peel_all(), // For patterns with paths, how we peel the scrutinee depends on the path's resolution. - PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), .. }) => { + PatKind::Struct(..) + | PatKind::TupleStruct(..) + | PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), .. }) => { // If there was an error resolving the path, default to peeling everything. - opt_path_res.unwrap().map_or(AdjustMode::Peel { kind: PeelKind::Implicit }, |pr| pr.adjust_mode()) + opt_path_res.unwrap().map_or(AdjustMode::peel_all(), |pr| pr.adjust_mode()) } // String and byte-string literals result in types `&str` and `&[u8]` respectively. @@ -662,7 +673,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Call `resolve_vars_if_possible` here for inline const blocks. PatKind::Expr(lt) => match self.resolve_vars_if_possible(self.check_pat_expr_unadjusted(lt)).kind() { ty::Ref(..) => AdjustMode::Pass, - _ => AdjustMode::Peel { kind: PeelKind::Implicit }, + _ => { + // Path patterns have already been handled, and inline const blocks currently + // aren't possible to write, so any handling for them would be untested. + if cfg!(debug_assertions) + && self.tcx.features().deref_patterns() + && !matches!(lt.kind, PatExprKind::Lit { .. }) + { + span_bug!(lt.span, "FIXME(deref_patterns): adjust mode unimplemented for {:?}", lt.kind); + } + AdjustMode::peel_all() + } }, // Ref patterns are complicated, we handle them in `check_pat_ref`. diff --git a/tests/ui/pattern/deref-patterns/implicit-const-deref.rs b/tests/ui/pattern/deref-patterns/implicit-const-deref.rs new file mode 100644 index 0000000000000..70f89629bc228 --- /dev/null +++ b/tests/ui/pattern/deref-patterns/implicit-const-deref.rs @@ -0,0 +1,19 @@ +//! Test that we get an error about structural equality rather than a type error when attempting to +//! use const patterns of library pointer types. Currently there aren't any smart pointers that can +//! be used in constant patterns, but we still need to make sure we don't implicitly dereference the +//! scrutinee and end up with a type error; this would prevent us from reporting that only constants +//! supporting structural equality can be used as patterns. +#![feature(deref_patterns)] +#![allow(incomplete_features)] + +const EMPTY: Vec<()> = Vec::new(); + +fn main() { + // FIXME(inline_const_pat): if `inline_const_pat` is reinstated, there should be a case here for + // inline const block patterns as well; they're checked differently than named constants. + match vec![()] { + EMPTY => {} + //~^ ERROR: constant of non-structural type `Vec<()>` in a pattern + _ => {} + } +} diff --git a/tests/ui/pattern/deref-patterns/implicit-const-deref.stderr b/tests/ui/pattern/deref-patterns/implicit-const-deref.stderr new file mode 100644 index 0000000000000..21d09ec44c4f8 --- /dev/null +++ b/tests/ui/pattern/deref-patterns/implicit-const-deref.stderr @@ -0,0 +1,16 @@ +error: constant of non-structural type `Vec<()>` in a pattern + --> $DIR/implicit-const-deref.rs:15:9 + | +LL | const EMPTY: Vec<()> = Vec::new(); + | -------------------- constant defined here +... +LL | EMPTY => {} + | ^^^^^ constant of non-structural type + --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL + | + = note: `Vec<()>` must be annotated with `#[derive(PartialEq)]` to be usable in patterns + | + = note: see https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html for details + +error: aborting due to 1 previous error + diff --git a/tests/ui/pattern/deref-patterns/implicit-cow-deref.rs b/tests/ui/pattern/deref-patterns/implicit-cow-deref.rs new file mode 100644 index 0000000000000..6a363c58b633b --- /dev/null +++ b/tests/ui/pattern/deref-patterns/implicit-cow-deref.rs @@ -0,0 +1,44 @@ +//@ run-pass +//! Test that implicit deref patterns interact as expected with `Cow` constructor patterns. +#![feature(deref_patterns)] +#![allow(incomplete_features)] + +use std::borrow::Cow; + +fn main() { + let cow: Cow<'static, [u8]> = Cow::from(&[1, 2, 3]); + + match cow { + [..] => {} + _ => unreachable!(), + } + + match cow { + Cow::Borrowed(_) => {} + Cow::Owned(_) => unreachable!(), + } + + match Box::new(&cow) { + Cow::Borrowed { 0: _ } => {} + Cow::Owned { 0: _ } => unreachable!(), + _ => unreachable!(), + } + + let cow_of_cow: Cow<'_, Cow<'static, [u8]>> = Cow::Owned(cow); + + match cow_of_cow { + [..] => {} + _ => unreachable!(), + } + + match cow_of_cow { + Cow::Borrowed(_) => unreachable!(), + Cow::Owned(_) => {} + } + + match Box::new(&cow_of_cow) { + Cow::Borrowed { 0: _ } => unreachable!(), + Cow::Owned { 0: _ } => {} + _ => unreachable!(), + } +} From 977c9ab7a2ead006e06b1b78cc1b6ac63245560b Mon Sep 17 00:00:00 2001 From: dianne Date: Sun, 9 Mar 2025 17:02:34 -0700 Subject: [PATCH 171/266] respect the tcx's recursion limit when peeling --- compiler/rustc_hir_analysis/src/autoderef.rs | 10 +++++-- compiler/rustc_hir_typeck/src/pat.rs | 28 +++++++++++++------ .../pattern/deref-patterns/recursion-limit.rs | 23 +++++++++++++++ .../deref-patterns/recursion-limit.stderr | 18 ++++++++++++ 4 files changed, 68 insertions(+), 11 deletions(-) create mode 100644 tests/ui/pattern/deref-patterns/recursion-limit.rs create mode 100644 tests/ui/pattern/deref-patterns/recursion-limit.stderr diff --git a/compiler/rustc_hir_analysis/src/autoderef.rs b/compiler/rustc_hir_analysis/src/autoderef.rs index b3eade8c8ae47..99e495d926690 100644 --- a/compiler/rustc_hir_analysis/src/autoderef.rs +++ b/compiler/rustc_hir_analysis/src/autoderef.rs @@ -2,8 +2,8 @@ use rustc_infer::infer::InferCtxt; use rustc_infer::traits::PredicateObligations; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; use rustc_session::Limit; -use rustc_span::Span; use rustc_span::def_id::{LOCAL_CRATE, LocalDefId}; +use rustc_span::{ErrorGuaranteed, Span}; use rustc_trait_selection::traits::ObligationCtxt; use tracing::{debug, instrument}; @@ -259,7 +259,11 @@ impl<'a, 'tcx> Autoderef<'a, 'tcx> { } } -pub fn report_autoderef_recursion_limit_error<'tcx>(tcx: TyCtxt<'tcx>, span: Span, ty: Ty<'tcx>) { +pub fn report_autoderef_recursion_limit_error<'tcx>( + tcx: TyCtxt<'tcx>, + span: Span, + ty: Ty<'tcx>, +) -> ErrorGuaranteed { // We've reached the recursion limit, error gracefully. let suggested_limit = match tcx.recursion_limit() { Limit(0) => Limit(2), @@ -270,5 +274,5 @@ pub fn report_autoderef_recursion_limit_error<'tcx>(tcx: TyCtxt<'tcx>, span: Spa ty, suggested_limit, crate_name: tcx.crate_name(LOCAL_CRATE), - }); + }) } diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 46916f22d0e29..e5e4fc7f8b77f 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -15,6 +15,7 @@ use rustc_hir::{ self as hir, BindingMode, ByRef, ExprKind, HirId, LangItem, Mutability, Pat, PatExpr, PatExprKind, PatKind, expr_needs_parens, }; +use rustc_hir_analysis::autoderef::report_autoderef_recursion_limit_error; use rustc_infer::infer; use rustc_middle::traits::PatternOriginExpr; use rustc_middle::ty::{self, Ty, TypeVisitableExt}; @@ -552,17 +553,28 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!("scrutinee ty {expected:?} is a smart pointer, inserting overloaded deref"); // The scrutinee is a smart pointer; implicitly dereference it. This adds a // requirement that `expected: DerefPure`. - let inner_ty = self.deref_pat_target(pat.span, expected); + let mut inner_ty = self.deref_pat_target(pat.span, expected); // Once we've checked `pat`, we'll add a `DerefMut` bound if it contains any // `ref mut` bindings. See `Self::register_deref_mut_bounds_if_needed`. - // Preserve the smart pointer type for THIR lowering and upvar analysis. - self.typeck_results - .borrow_mut() - .pat_adjustments_mut() - .entry(pat.hir_id) - .or_default() - .push(PatAdjustment { kind: PatAdjust::OverloadedDeref, source: expected }); + let mut typeck_results = self.typeck_results.borrow_mut(); + let mut pat_adjustments_table = typeck_results.pat_adjustments_mut(); + let pat_adjustments = pat_adjustments_table.entry(pat.hir_id).or_default(); + // We may reach the recursion limit if a user matches on a type `T` satisfying + // `T: Deref`; error gracefully in this case. + // FIXME(deref_patterns): If `deref_patterns` stabilizes, it may make sense to move + // this check out of this branch. Alternatively, this loop could be implemented with + // autoderef and this check removed. For now though, don't break code compiling on + // stable with lots of `&`s and a low recursion limit, if anyone's done that. + if self.tcx.recursion_limit().value_within_limit(pat_adjustments.len()) { + // Preserve the smart pointer type for THIR lowering and closure upvar analysis. + pat_adjustments + .push(PatAdjustment { kind: PatAdjust::OverloadedDeref, source: expected }); + } else { + let guar = report_autoderef_recursion_limit_error(self.tcx, pat.span, expected); + inner_ty = Ty::new_error(self.tcx, guar); + } + drop(typeck_results); // Recurse, using the old pat info to keep `current_depth` to its old value. // Peeling smart pointers does not update the default binding mode. diff --git a/tests/ui/pattern/deref-patterns/recursion-limit.rs b/tests/ui/pattern/deref-patterns/recursion-limit.rs new file mode 100644 index 0000000000000..c5fe520f6f1ab --- /dev/null +++ b/tests/ui/pattern/deref-patterns/recursion-limit.rs @@ -0,0 +1,23 @@ +//! Test that implicit deref patterns respect the recursion limit +#![feature(deref_patterns)] +#![allow(incomplete_features)] +#![recursion_limit = "8"] + +use std::ops::Deref; + +struct Cyclic; +impl Deref for Cyclic { + type Target = Cyclic; + fn deref(&self) -> &Cyclic { + &Cyclic + } +} + +fn main() { + match &Box::new(Cyclic) { + () => {} + //~^ ERROR: reached the recursion limit while auto-dereferencing `Cyclic` + //~| ERROR: the trait bound `Cyclic: DerefPure` is not satisfied + _ => {} + } +} diff --git a/tests/ui/pattern/deref-patterns/recursion-limit.stderr b/tests/ui/pattern/deref-patterns/recursion-limit.stderr new file mode 100644 index 0000000000000..9a83d1eb5a4a4 --- /dev/null +++ b/tests/ui/pattern/deref-patterns/recursion-limit.stderr @@ -0,0 +1,18 @@ +error[E0055]: reached the recursion limit while auto-dereferencing `Cyclic` + --> $DIR/recursion-limit.rs:18:9 + | +LL | () => {} + | ^^ deref recursion limit reached + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "16"]` attribute to your crate (`recursion_limit`) + +error[E0277]: the trait bound `Cyclic: DerefPure` is not satisfied + --> $DIR/recursion-limit.rs:18:9 + | +LL | () => {} + | ^^ the trait `DerefPure` is not implemented for `Cyclic` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0055, E0277. +For more information about an error, try `rustc --explain E0055`. From ff0d4bc743086111c841812ec9925efb075d1243 Mon Sep 17 00:00:00 2001 From: dianne Date: Thu, 13 Mar 2025 22:34:26 -0700 Subject: [PATCH 172/266] upvar inference for implicit deref patterns --- .../rustc_hir_typeck/src/expr_use_visitor.rs | 54 +++++++++++++++---- .../pattern/deref-patterns/closure_capture.rs | 27 ++++++++++ 2 files changed, 70 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index f43f9b5187b63..c92aa228cc2c5 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -1000,6 +1000,8 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx // determines whether to borrow *at the level of the deref pattern* rather than // borrowing the bound place (since that inner place is inside the temporary that // stores the result of calling `deref()`/`deref_mut()` so can't be captured). + // HACK: this could be a fake pattern corresponding to a deref inserted by match + // ergonomics, in which case `pat.hir_id` will be the id of the subpattern. let mutable = self.cx.typeck_results().pat_has_ref_mut_binding(subpattern); let mutability = if mutable { hir::Mutability::Mut } else { hir::Mutability::Not }; @@ -1675,12 +1677,31 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx // Then we see that to get the same result, we must start with // `deref { deref { place_foo }}` instead of `place_foo` since the pattern is now `Some(x,)` // and not `&&Some(x,)`, even though its assigned type is that of `&&Some(x,)`. - for _ in - 0..self.cx.typeck_results().pat_adjustments().get(pat.hir_id).map_or(0, |v| v.len()) - { + let typeck_results = self.cx.typeck_results(); + let adjustments: &[adjustment::PatAdjustment<'tcx>] = + typeck_results.pat_adjustments().get(pat.hir_id).map_or(&[], |v| &**v); + let mut adjusts = adjustments.iter().peekable(); + while let Some(adjust) = adjusts.next() { debug!("applying adjustment to place_with_id={:?}", place_with_id); - place_with_id = self.cat_deref(pat.hir_id, place_with_id)?; + place_with_id = match adjust.kind { + adjustment::PatAdjust::BuiltinDeref => self.cat_deref(pat.hir_id, place_with_id)?, + adjustment::PatAdjust::OverloadedDeref => { + // This adjustment corresponds to an overloaded deref; it borrows the scrutinee to + // call `Deref::deref` or `DerefMut::deref_mut`. Invoke the callback before setting + // `place_with_id` to the temporary storing the result of the deref. + // HACK(dianne): giving the callback a fake deref pattern makes sure it behaves the + // same as it would if this were an explicit deref pattern. + op(&place_with_id, &hir::Pat { kind: PatKind::Deref(pat), ..*pat })?; + let target_ty = match adjusts.peek() { + Some(&&next_adjust) => next_adjust.source, + // At the end of the deref chain, we get `pat`'s scrutinee. + None => self.pat_ty_unadjusted(pat)?, + }; + self.pat_deref_temp(pat.hir_id, pat, target_ty)? + } + }; } + drop(typeck_results); // explicitly release borrow of typeck results, just in case. let place_with_id = place_with_id; // lose mutability debug!("applied adjustment derefs to get place_with_id={:?}", place_with_id); @@ -1783,14 +1804,8 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx self.cat_pattern(subplace, subpat, op)?; } PatKind::Deref(subpat) => { - let mutable = self.cx.typeck_results().pat_has_ref_mut_binding(subpat); - let mutability = if mutable { hir::Mutability::Mut } else { hir::Mutability::Not }; - let re_erased = self.cx.tcx().lifetimes.re_erased; let ty = self.pat_ty_adjusted(subpat)?; - let ty = Ty::new_ref(self.cx.tcx(), re_erased, ty, mutability); - // A deref pattern generates a temporary. - let base = self.cat_rvalue(pat.hir_id, ty); - let place = self.cat_deref(pat.hir_id, base)?; + let place = self.pat_deref_temp(pat.hir_id, subpat, ty)?; self.cat_pattern(place, subpat, op)?; } @@ -1843,6 +1858,23 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx Ok(()) } + /// Represents the place of the temp that stores the scrutinee of a deref pattern's interior. + fn pat_deref_temp( + &self, + hir_id: HirId, + inner: &hir::Pat<'_>, + target_ty: Ty<'tcx>, + ) -> Result, Cx::Error> { + let mutable = self.cx.typeck_results().pat_has_ref_mut_binding(inner); + let mutability = if mutable { hir::Mutability::Mut } else { hir::Mutability::Not }; + let re_erased = self.cx.tcx().lifetimes.re_erased; + let ty = Ty::new_ref(self.cx.tcx(), re_erased, target_ty, mutability); + // A deref pattern stores the result of `Deref::deref` or `DerefMut::deref_mut` ... + let base = self.cat_rvalue(hir_id, ty); + // ... and the inner pattern matches on the place behind that reference. + self.cat_deref(hir_id, base) + } + fn is_multivariant_adt(&self, ty: Ty<'tcx>, span: Span) -> bool { if let ty::Adt(def, _) = self.cx.try_structurally_resolve_type(span, ty).kind() { // Note that if a non-exhaustive SingleVariant is defined in another crate, we need diff --git a/tests/ui/pattern/deref-patterns/closure_capture.rs b/tests/ui/pattern/deref-patterns/closure_capture.rs index fc0ddedac2b78..08586b6c7abdf 100644 --- a/tests/ui/pattern/deref-patterns/closure_capture.rs +++ b/tests/ui/pattern/deref-patterns/closure_capture.rs @@ -11,6 +11,15 @@ fn main() { assert_eq!(b.len(), 3); f(); + let v = vec![1, 2, 3]; + let f = || { + // this should count as a borrow of `v` as a whole + let [.., x] = v else { unreachable!() }; + assert_eq!(x, 3); + }; + assert_eq!(v, [1, 2, 3]); + f(); + let mut b = Box::new("aaa".to_string()); let mut f = || { let deref!(ref mut s) = b else { unreachable!() }; @@ -18,4 +27,22 @@ fn main() { }; f(); assert_eq!(b.len(), 5); + + let mut v = vec![1, 2, 3]; + let mut f = || { + // this should count as a mutable borrow of `v` as a whole + let [.., ref mut x] = v else { unreachable!() }; + *x = 4; + }; + f(); + assert_eq!(v, [1, 2, 4]); + + let mut v = vec![1, 2, 3]; + let mut f = || { + // here, `[.., x]` is adjusted by both an overloaded deref and a builtin deref + let [.., x] = &mut v else { unreachable!() }; + *x = 4; + }; + f(); + assert_eq!(v, [1, 2, 4]); } From 4c4b61b730ee7b53918043ff403bbc8e2d6d0eb0 Mon Sep 17 00:00:00 2001 From: dianne Date: Fri, 14 Mar 2025 02:51:20 -0700 Subject: [PATCH 173/266] add a feature gate test Implicit deref patterns allow previously ill-typed programs. Make sure they're still ill-typed without the feature gate. I've thrown in a test for `deref!(_)` too, though it seems it refers to `deref_patterns` as a library feature. --- tests/ui/pattern/deref-patterns/needs-gate.rs | 15 ++++++++++ .../pattern/deref-patterns/needs-gate.stderr | 29 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 tests/ui/pattern/deref-patterns/needs-gate.rs create mode 100644 tests/ui/pattern/deref-patterns/needs-gate.stderr diff --git a/tests/ui/pattern/deref-patterns/needs-gate.rs b/tests/ui/pattern/deref-patterns/needs-gate.rs new file mode 100644 index 0000000000000..2d5ec45217fbb --- /dev/null +++ b/tests/ui/pattern/deref-patterns/needs-gate.rs @@ -0,0 +1,15 @@ +// gate-test-deref_patterns + +fn main() { + match Box::new(0) { + deref!(0) => {} + //~^ ERROR: use of unstable library feature `deref_patterns`: placeholder syntax for deref patterns + _ => {} + } + + match Box::new(0) { + 0 => {} + //~^ ERROR: mismatched types + _ => {} + } +} diff --git a/tests/ui/pattern/deref-patterns/needs-gate.stderr b/tests/ui/pattern/deref-patterns/needs-gate.stderr new file mode 100644 index 0000000000000..8687b5dc977db --- /dev/null +++ b/tests/ui/pattern/deref-patterns/needs-gate.stderr @@ -0,0 +1,29 @@ +error[E0658]: use of unstable library feature `deref_patterns`: placeholder syntax for deref patterns + --> $DIR/needs-gate.rs:5:9 + | +LL | deref!(0) => {} + | ^^^^^ + | + = note: see issue #87121 for more information + = help: add `#![feature(deref_patterns)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0308]: mismatched types + --> $DIR/needs-gate.rs:11:9 + | +LL | match Box::new(0) { + | ----------- this expression has type `Box<{integer}>` +LL | 0 => {} + | ^ expected `Box<{integer}>`, found integer + | + = note: expected struct `Box<{integer}>` + found type `{integer}` +help: consider dereferencing to access the inner value using the Deref trait + | +LL | match *Box::new(0) { + | + + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0308, E0658. +For more information about an error, try `rustc --explain E0308`. From 93d13e98069478ab286d28b42333f74b88308a99 Mon Sep 17 00:00:00 2001 From: dianne Date: Fri, 14 Mar 2025 03:51:54 -0700 Subject: [PATCH 174/266] add an unstable book chapter - Clarifies the uses of implicit and explicit deref patterns - Includes motivating examples for both syntaxes - Shows the interaction with match ergonomics for reference types - Cross-links with `string_deref_patterns` and `box_patterns` The examples are contrived, but hopefully the intent comes across. --- .../src/language-features/box-patterns.md | 4 ++ .../src/language-features/deref-patterns.md | 57 +++++++++++++++++++ .../string-deref-patterns.md | 3 + 3 files changed, 64 insertions(+) create mode 100644 src/doc/unstable-book/src/language-features/deref-patterns.md diff --git a/src/doc/unstable-book/src/language-features/box-patterns.md b/src/doc/unstable-book/src/language-features/box-patterns.md index a1ac09633b759..c8a15b8477eee 100644 --- a/src/doc/unstable-book/src/language-features/box-patterns.md +++ b/src/doc/unstable-book/src/language-features/box-patterns.md @@ -6,6 +6,8 @@ The tracking issue for this feature is: [#29641] ------------------------ +> **Note**: This feature will be superseded by [`deref_patterns`] in the future. + Box patterns let you match on `Box`s: @@ -28,3 +30,5 @@ fn main() { } } ``` + +[`deref_patterns`]: ./deref-patterns.md diff --git a/src/doc/unstable-book/src/language-features/deref-patterns.md b/src/doc/unstable-book/src/language-features/deref-patterns.md new file mode 100644 index 0000000000000..d0102a665b0b0 --- /dev/null +++ b/src/doc/unstable-book/src/language-features/deref-patterns.md @@ -0,0 +1,57 @@ +# `deref_patterns` + +The tracking issue for this feature is: [#87121] + +[#87121]: https://github.com/rust-lang/rust/issues/87121 + +------------------------ + +> **Note**: This feature is incomplete. In the future, it is meant to supersede +> [`box_patterns`](./box-patterns.md) and [`string_deref_patterns`](./string-deref-patterns.md). + +This feature permits pattern matching on [smart pointers in the standard library] through their +`Deref` target types, either implicitly or with explicit `deref!(_)` patterns (the syntax of which +is currently a placeholder). + +```rust +#![feature(deref_patterns)] +#![allow(incomplete_features)] + +let mut v = vec![Box::new(Some(0))]; + +// Implicit dereferences are inserted when a pattern can match against the +// result of repeatedly dereferencing but can't match against a smart +// pointer itself. This works alongside match ergonomics for references. +if let [Some(x)] = &mut v { + *x += 1; +} + +// Explicit `deref!(_)` patterns may instead be used when finer control is +// needed, e.g. to dereference only a single smart pointer, or to bind the +// the result of dereferencing to a variable. +if let deref!([deref!(opt_x @ Some(1))]) = &mut v { + opt_x.as_mut().map(|x| *x += 1); +} + +assert_eq!(v, [Box::new(Some(2))]); +``` + +Without this feature, it may be necessary to introduce temporaries to represent dereferenced places +when matching on nested structures: + +```rust +let mut v = vec![Box::new(Some(0))]; +if let [b] = &mut *v { + if let Some(x) = &mut **b { + *x += 1; + } +} +if let [b] = &mut *v { + if let opt_x @ Some(1) = &mut **b { + opt_x.as_mut().map(|x| *x += 1); + } +} +assert_eq!(v, [Box::new(Some(2))]); +``` + +[smart pointers in the standard library]: https://doc.rust-lang.org/std/ops/trait.DerefPure.html#implementors diff --git a/src/doc/unstable-book/src/language-features/string-deref-patterns.md b/src/doc/unstable-book/src/language-features/string-deref-patterns.md index 3723830751e80..366bb15d4ea86 100644 --- a/src/doc/unstable-book/src/language-features/string-deref-patterns.md +++ b/src/doc/unstable-book/src/language-features/string-deref-patterns.md @@ -6,6 +6,8 @@ The tracking issue for this feature is: [#87121] ------------------------ +> **Note**: This feature will be superseded by [`deref_patterns`] in the future. + This feature permits pattern matching `String` to `&str` through [its `Deref` implementation]. ```rust @@ -42,4 +44,5 @@ pub fn is_it_the_answer(value: Value) -> bool { } ``` +[`deref_patterns`]: ./deref-patterns.md [its `Deref` implementation]: https://doc.rust-lang.org/std/string/struct.String.html#impl-Deref-for-String From 3b91b7ac57a534bbb1d4f39f679f86040a588903 Mon Sep 17 00:00:00 2001 From: Nadrieril Date: Wed, 16 Apr 2025 20:13:42 +0200 Subject: [PATCH 175/266] Make cow_of_cow test a teeny bit more explicit --- tests/ui/pattern/deref-patterns/implicit-cow-deref.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/ui/pattern/deref-patterns/implicit-cow-deref.rs b/tests/ui/pattern/deref-patterns/implicit-cow-deref.rs index 6a363c58b633b..a9b8de8601078 100644 --- a/tests/ui/pattern/deref-patterns/implicit-cow-deref.rs +++ b/tests/ui/pattern/deref-patterns/implicit-cow-deref.rs @@ -6,7 +6,7 @@ use std::borrow::Cow; fn main() { - let cow: Cow<'static, [u8]> = Cow::from(&[1, 2, 3]); + let cow: Cow<'static, [u8]> = Cow::Borrowed(&[1, 2, 3]); match cow { [..] => {} @@ -31,6 +31,7 @@ fn main() { _ => unreachable!(), } + // This matches on the outer `Cow` (the owned one). match cow_of_cow { Cow::Borrowed(_) => unreachable!(), Cow::Owned(_) => {} From 92ce44f372d081e4c548cdabeec4f580a5eb9642 Mon Sep 17 00:00:00 2001 From: Curtis D'Alves Date: Wed, 16 Apr 2025 19:26:26 -0400 Subject: [PATCH 176/266] ignore aix for tests/ui/erros/pic-linker.rs --- tests/ui/errors/pic-linker.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/ui/errors/pic-linker.rs b/tests/ui/errors/pic-linker.rs index d90989903048e..36495ca8fe958 100644 --- a/tests/ui/errors/pic-linker.rs +++ b/tests/ui/errors/pic-linker.rs @@ -5,6 +5,7 @@ //@ ignore-windows //@ ignore-macos //@ ignore-cross-compile +//@ ignore-aix //@ compile-flags: -Clink-args=-Wl,-z,text //@ run-pass From 4be670f89b94aaeab04b0e52d0efd9c61f1bef9d Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 9 Apr 2025 21:11:12 +1000 Subject: [PATCH 177/266] Warnings-as-errors in `check-builtin-attr-ice.rs`. This adds two new warnings, both of which print the attribute incorrectly as `#[]`. The next commit will fix this. --- tests/ui/attributes/check-builtin-attr-ice.rs | 4 +++ .../attributes/check-builtin-attr-ice.stderr | 26 ++++++++++++++++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/tests/ui/attributes/check-builtin-attr-ice.rs b/tests/ui/attributes/check-builtin-attr-ice.rs index 9ef5890601f6b..e3a2ffc714d06 100644 --- a/tests/ui/attributes/check-builtin-attr-ice.rs +++ b/tests/ui/attributes/check-builtin-attr-ice.rs @@ -39,13 +39,17 @@ // Notably, `should_panic` is a `AttributeType::Normal` attribute that is checked separately. +#![deny(unused_attributes)] + struct Foo { #[should_panic::skip] //~^ ERROR failed to resolve + //~| ERROR `#[]` only has an effect on functions pub field: u8, #[should_panic::a::b::c] //~^ ERROR failed to resolve + //~| ERROR `#[]` only has an effect on functions pub field2: u8, } diff --git a/tests/ui/attributes/check-builtin-attr-ice.stderr b/tests/ui/attributes/check-builtin-attr-ice.stderr index 06a4769b2b421..487a0b6d680dc 100644 --- a/tests/ui/attributes/check-builtin-attr-ice.stderr +++ b/tests/ui/attributes/check-builtin-attr-ice.stderr @@ -1,21 +1,39 @@ error[E0433]: failed to resolve: use of unresolved module or unlinked crate `should_panic` - --> $DIR/check-builtin-attr-ice.rs:43:7 + --> $DIR/check-builtin-attr-ice.rs:45:7 | LL | #[should_panic::skip] | ^^^^^^^^^^^^ use of unresolved module or unlinked crate `should_panic` error[E0433]: failed to resolve: use of unresolved module or unlinked crate `should_panic` - --> $DIR/check-builtin-attr-ice.rs:47:7 + --> $DIR/check-builtin-attr-ice.rs:50:7 | LL | #[should_panic::a::b::c] | ^^^^^^^^^^^^ use of unresolved module or unlinked crate `should_panic` error[E0433]: failed to resolve: use of unresolved module or unlinked crate `deny` - --> $DIR/check-builtin-attr-ice.rs:55:7 + --> $DIR/check-builtin-attr-ice.rs:59:7 | LL | #[deny::skip] | ^^^^ use of unresolved module or unlinked crate `deny` -error: aborting due to 3 previous errors +error: `#[]` only has an effect on functions + --> $DIR/check-builtin-attr-ice.rs:45:5 + | +LL | #[should_panic::skip] + | ^^^^^^^^^^^^^^^^^^^^^ + | +note: the lint level is defined here + --> $DIR/check-builtin-attr-ice.rs:42:9 + | +LL | #![deny(unused_attributes)] + | ^^^^^^^^^^^^^^^^^ + +error: `#[]` only has an effect on functions + --> $DIR/check-builtin-attr-ice.rs:50:5 + | +LL | #[should_panic::a::b::c] + | ^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 5 previous errors For more information about this error, try `rustc --explain E0433`. From 400e8e5dc819b1fa7f994fb60dbe8b5112ec3fd2 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 9 Apr 2025 21:15:45 +1000 Subject: [PATCH 178/266] Fix attribute printing in an error. The current code assumes that the attribute is just an identifier, and so misprints paths. --- compiler/rustc_passes/src/check_attr.rs | 5 ++++- compiler/rustc_passes/src/errors.rs | 2 +- tests/ui/attributes/check-builtin-attr-ice.rs | 4 ++-- tests/ui/attributes/check-builtin-attr-ice.stderr | 4 ++-- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 42279258e8777..dcfecdc26ea21 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -561,12 +561,15 @@ impl<'tcx> CheckAttrVisitor<'tcx> { allowed_target: Target, ) { if target != allowed_target { + let path = attr.path(); + let path: Vec<_> = path.iter().map(|s| s.as_str()).collect(); + let attr_name = path.join("::"); self.tcx.emit_node_span_lint( UNUSED_ATTRIBUTES, hir_id, attr.span(), errors::OnlyHasEffectOn { - attr_name: attr.name_or_empty(), + attr_name, target_name: allowed_target.name().replace(' ', "_"), }, ); diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 85eddafefcd56..075927a54f805 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -1433,7 +1433,7 @@ pub(crate) struct UselessAssignment<'a> { #[derive(LintDiagnostic)] #[diag(passes_only_has_effect_on)] pub(crate) struct OnlyHasEffectOn { - pub attr_name: Symbol, + pub attr_name: String, pub target_name: String, } diff --git a/tests/ui/attributes/check-builtin-attr-ice.rs b/tests/ui/attributes/check-builtin-attr-ice.rs index e3a2ffc714d06..7745849acd0b1 100644 --- a/tests/ui/attributes/check-builtin-attr-ice.rs +++ b/tests/ui/attributes/check-builtin-attr-ice.rs @@ -44,12 +44,12 @@ struct Foo { #[should_panic::skip] //~^ ERROR failed to resolve - //~| ERROR `#[]` only has an effect on functions + //~| ERROR `#[should_panic::skip]` only has an effect on functions pub field: u8, #[should_panic::a::b::c] //~^ ERROR failed to resolve - //~| ERROR `#[]` only has an effect on functions + //~| ERROR `#[should_panic::a::b::c]` only has an effect on functions pub field2: u8, } diff --git a/tests/ui/attributes/check-builtin-attr-ice.stderr b/tests/ui/attributes/check-builtin-attr-ice.stderr index 487a0b6d680dc..4f26f71efb7e7 100644 --- a/tests/ui/attributes/check-builtin-attr-ice.stderr +++ b/tests/ui/attributes/check-builtin-attr-ice.stderr @@ -16,7 +16,7 @@ error[E0433]: failed to resolve: use of unresolved module or unlinked crate `den LL | #[deny::skip] | ^^^^ use of unresolved module or unlinked crate `deny` -error: `#[]` only has an effect on functions +error: `#[should_panic::skip]` only has an effect on functions --> $DIR/check-builtin-attr-ice.rs:45:5 | LL | #[should_panic::skip] @@ -28,7 +28,7 @@ note: the lint level is defined here LL | #![deny(unused_attributes)] | ^^^^^^^^^^^^^^^^^ -error: `#[]` only has an effect on functions +error: `#[should_panic::a::b::c]` only has an effect on functions --> $DIR/check-builtin-attr-ice.rs:50:5 | LL | #[should_panic::a::b::c] From 7e1f2f9c54338cbefddffcce725f89d271d2cbe8 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 10 Apr 2025 13:47:35 +1000 Subject: [PATCH 179/266] Augment some tests involving attributes. This shows places where the use of `name_or_empty` causes problems, i.e. we print empty identifiers in error messages: ``` error: unrecognized field name `` error: `` isn't a valid `#[macro_export]` argument `#[no_sanitize()]` should be applied to a function ``` (The last one is about an attribute `#[no_sanitize("address")]`.) The next commit will fix these. --- tests/ui/abi/debug.rs | 3 +++ tests/ui/abi/debug.stderr | 8 +++++++- .../invalid_macro_export_argument.deny.stderr | 8 +++++++- .../invalid_macro_export_argument.rs | 6 ++++++ tests/ui/attributes/no-sanitize.rs | 5 +++++ tests/ui/attributes/no-sanitize.stderr | 19 ++++++++++++++++++- 6 files changed, 46 insertions(+), 3 deletions(-) diff --git a/tests/ui/abi/debug.rs b/tests/ui/abi/debug.rs index 6dbc316146412..e3260191e5c86 100644 --- a/tests/ui/abi/debug.rs +++ b/tests/ui/abi/debug.rs @@ -52,3 +52,6 @@ type TestAbiNeSign = (fn(i32), fn(u32)); //~ ERROR: ABIs are not compatible #[rustc_abi(assert_eq)] type TestAbiEqNonsense = (fn((str, str)), fn((str, str))); //~ ERROR: cannot be known at compilation time + +#[rustc_abi("assert_eq")] //~ ERROR unrecognized field name `` +type Bad = u32; diff --git a/tests/ui/abi/debug.stderr b/tests/ui/abi/debug.stderr index 2239ba0e5880a..717a95685cbe9 100644 --- a/tests/ui/abi/debug.stderr +++ b/tests/ui/abi/debug.stderr @@ -906,6 +906,12 @@ LL | type TestAbiEqNonsense = (fn((str, str)), fn((str, str))); = help: the trait `Sized` is not implemented for `str` = note: only the last element of a tuple may have a dynamically sized type +error: unrecognized field name `` + --> $DIR/debug.rs:56:13 + | +LL | #[rustc_abi("assert_eq")] + | ^^^^^^^^^^^ + error: `#[rustc_abi]` can only be applied to function items, type aliases, and associated functions --> $DIR/debug.rs:29:5 | @@ -1004,6 +1010,6 @@ error: fn_abi_of(assoc_test) = FnAbi { LL | fn assoc_test(&self) { } | ^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 11 previous errors +error: aborting due to 12 previous errors For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/attributes/invalid_macro_export_argument.deny.stderr b/tests/ui/attributes/invalid_macro_export_argument.deny.stderr index 644acc27b58e2..897bcecc20e2a 100644 --- a/tests/ui/attributes/invalid_macro_export_argument.deny.stderr +++ b/tests/ui/attributes/invalid_macro_export_argument.deny.stderr @@ -16,5 +16,11 @@ error: `not_local_inner_macros` isn't a valid `#[macro_export]` argument LL | #[macro_export(not_local_inner_macros)] | ^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 2 previous errors +error: `` isn't a valid `#[macro_export]` argument + --> $DIR/invalid_macro_export_argument.rs:33:16 + | +LL | #[macro_export("blah")] + | ^^^^^^ + +error: aborting due to 3 previous errors diff --git a/tests/ui/attributes/invalid_macro_export_argument.rs b/tests/ui/attributes/invalid_macro_export_argument.rs index 96f66991e0414..c0aa7df2e8734 100644 --- a/tests/ui/attributes/invalid_macro_export_argument.rs +++ b/tests/ui/attributes/invalid_macro_export_argument.rs @@ -30,4 +30,10 @@ macro_rules! e { () => () } +#[macro_export("blah")] +//[deny]~^ ERROR `` isn't a valid `#[macro_export]` argument +macro_rules! f { + () => () +} + fn main() {} diff --git a/tests/ui/attributes/no-sanitize.rs b/tests/ui/attributes/no-sanitize.rs index 8c79866d5aa31..a7225efc7b800 100644 --- a/tests/ui/attributes/no-sanitize.rs +++ b/tests/ui/attributes/no-sanitize.rs @@ -38,3 +38,8 @@ fn valid() {} #[no_sanitize(address)] static VALID : i32 = 0; + +#[no_sanitize("address")] +//~^ ERROR `#[no_sanitize()]` should be applied to a function +//~| ERROR invalid argument for `no_sanitize` +static VALID2 : i32 = 0; diff --git a/tests/ui/attributes/no-sanitize.stderr b/tests/ui/attributes/no-sanitize.stderr index 9b0b76e3f4eba..1f24aa71af56d 100644 --- a/tests/ui/attributes/no-sanitize.stderr +++ b/tests/ui/attributes/no-sanitize.stderr @@ -59,5 +59,22 @@ LL | #[no_sanitize(address, memory)] LL | static INVALID : i32 = 0; | ------------------------- not a function -error: aborting due to 7 previous errors +error: `#[no_sanitize()]` should be applied to a function + --> $DIR/no-sanitize.rs:42:15 + | +LL | #[no_sanitize("address")] + | ^^^^^^^^^ +... +LL | static VALID2 : i32 = 0; + | ------------------------ not a function + +error: invalid argument for `no_sanitize` + --> $DIR/no-sanitize.rs:42:15 + | +LL | #[no_sanitize("address")] + | ^^^^^^^^^ + | + = note: expected one of: `address`, `cfi`, `hwaddress`, `kcfi`, `memory`, `memtag`, `shadow-call-stack`, or `thread` + +error: aborting due to 9 previous errors From 2fef0a30ae6b2687dfb286cb544d2a542f7e2335 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 10 Apr 2025 14:33:59 +1000 Subject: [PATCH 180/266] Replace infallible `name_or_empty` methods with fallible `name` methods. I'm removing empty identifiers everywhere, because in practice they always mean "no identifier" rather than "empty identifier". (An empty identifier is impossible.) It's better to use `Option` to mean "no identifier" because you then can't forget about the "no identifier" possibility. Some specifics: - When testing an attribute for a single name, the commit uses the `has_name` method. - When testing an attribute for multiple names, the commit uses the new `has_any_name` method. - When using `match` on an attribute, the match arms now have `Some` on them. In the tests, we now avoid printing empty identifiers by not printing the identifier in the `error:` line at all, instead letting the carets point out the problem. --- compiler/rustc_ast/src/attr/mod.rs | 33 +++-- compiler/rustc_ast_lowering/src/item.rs | 2 +- .../rustc_ast_passes/src/ast_validation.rs | 5 +- .../rustc_attr_parsing/src/attributes/cfg.rs | 12 +- compiler/rustc_attr_parsing/src/context.rs | 6 +- .../src/deriving/generic/mod.rs | 5 +- .../rustc_codegen_ssa/src/codegen_attrs.rs | 33 ++--- compiler/rustc_expand/src/base.rs | 8 +- compiler/rustc_expand/src/expand.rs | 12 +- compiler/rustc_hir/src/hir.rs | 11 +- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 2 +- compiler/rustc_hir_typeck/src/method/probe.rs | 7 +- compiler/rustc_incremental/messages.ftl | 2 +- compiler/rustc_incremental/src/errors.rs | 5 +- .../src/persist/dirty_clean.rs | 3 +- compiler/rustc_lint_defs/src/lib.rs | 2 +- compiler/rustc_metadata/src/native_libs.rs | 14 +-- compiler/rustc_metadata/src/rmeta/encoder.rs | 4 +- .../rustc_mir_build/src/builder/custom/mod.rs | 3 +- compiler/rustc_mir_build/src/builder/mod.rs | 2 +- compiler/rustc_mir_build/src/thir/cx/mod.rs | 2 +- .../src/framework/graphviz.rs | 5 +- compiler/rustc_passes/messages.ftl | 6 +- compiler/rustc_passes/src/abi_test.rs | 20 +-- compiler/rustc_passes/src/check_attr.rs | 116 +++++++++--------- .../rustc_passes/src/debugger_visualizer.rs | 22 ++-- compiler/rustc_passes/src/errors.rs | 7 +- compiler/rustc_passes/src/layout_test.rs | 18 +-- compiler/rustc_span/src/symbol.rs | 1 + src/librustdoc/clean/types.rs | 2 +- src/librustdoc/core.rs | 4 +- src/librustdoc/doctest/make.rs | 14 +-- src/librustdoc/html/render/context.rs | 12 +- src/tools/clippy/clippy_utils/src/lib.rs | 4 +- tests/ui/abi/debug.rs | 2 +- tests/ui/abi/debug.stderr | 2 +- .../invalid_macro_export_argument.deny.stderr | 4 +- .../invalid_macro_export_argument.rs | 4 +- tests/ui/attributes/no-sanitize.rs | 2 +- tests/ui/attributes/no-sanitize.stderr | 2 +- 40 files changed, 217 insertions(+), 203 deletions(-) diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index d656d9b0b8af3..f104400a572ba 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -305,8 +305,8 @@ impl MetaItem { if let [PathSegment { ident, .. }] = self.path.segments[..] { Some(ident) } else { None } } - pub fn name_or_empty(&self) -> Symbol { - self.ident().unwrap_or_else(Ident::empty).name + pub fn name(&self) -> Option { + self.ident().map(|ident| ident.name) } pub fn has_name(&self, name: Symbol) -> bool { @@ -511,13 +511,14 @@ impl MetaItemInner { } } - /// For a single-segment meta item, returns its name; otherwise, returns `None`. + /// For a single-segment meta item, returns its identifier; otherwise, returns `None`. pub fn ident(&self) -> Option { self.meta_item().and_then(|meta_item| meta_item.ident()) } - pub fn name_or_empty(&self) -> Symbol { - self.ident().unwrap_or_else(Ident::empty).name + /// For a single-segment meta item, returns its name; otherwise, returns `None`. + pub fn name(&self) -> Option { + self.ident().map(|ident| ident.name) } /// Returns `true` if this list item is a MetaItem with a name of `name`. @@ -738,9 +739,9 @@ pub trait AttributeExt: Debug { fn id(&self) -> AttrId; /// For a single-segment attribute (i.e., `#[attr]` and not `#[path::atrr]`), - /// return the name of the attribute, else return the empty identifier. - fn name_or_empty(&self) -> Symbol { - self.ident().unwrap_or_else(Ident::empty).name + /// return the name of the attribute; otherwise, returns `None`. + fn name(&self) -> Option { + self.ident().map(|ident| ident.name) } /// Get the meta item list, `#[attr(meta item list)]` @@ -752,7 +753,7 @@ pub trait AttributeExt: Debug { /// Gets the span of the value literal, as string, when using `#[attr = value]` fn value_span(&self) -> Option; - /// For a single-segment attribute, returns its name; otherwise, returns `None`. + /// For a single-segment attribute, returns its ident; otherwise, returns `None`. fn ident(&self) -> Option; /// Checks whether the path of this attribute matches the name. @@ -770,6 +771,11 @@ pub trait AttributeExt: Debug { self.ident().map(|x| x.name == name).unwrap_or(false) } + #[inline] + fn has_any_name(&self, names: &[Symbol]) -> bool { + names.iter().any(|&name| self.has_name(name)) + } + /// get the span of the entire attribute fn span(&self) -> Span; @@ -813,8 +819,8 @@ impl Attribute { AttributeExt::id(self) } - pub fn name_or_empty(&self) -> Symbol { - AttributeExt::name_or_empty(self) + pub fn name(&self) -> Option { + AttributeExt::name(self) } pub fn meta_item_list(&self) -> Option> { @@ -846,6 +852,11 @@ impl Attribute { AttributeExt::has_name(self, name) } + #[inline] + pub fn has_any_name(&self, names: &[Symbol]) -> bool { + AttributeExt::has_any_name(self, names) + } + pub fn span(&self) -> Span { AttributeExt::span(self) } diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index d8b55bea3d763..fc32c4efce56a 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1310,7 +1310,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // create a fake body so that the entire rest of the compiler doesn't have to deal with // this as a special case. return self.lower_fn_body(decl, contract, |this| { - if attrs.iter().any(|a| a.name_or_empty() == sym::rustc_intrinsic) { + if attrs.iter().any(|a| a.has_name(sym::rustc_intrinsic)) { let span = this.lower_span(span); let empty_block = hir::Block { hir_id: this.next_id(), diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index dc77e7b283442..daf8ff5dc65b1 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -347,7 +347,7 @@ impl<'a> AstValidator<'a> { sym::forbid, sym::warn, ]; - !arr.contains(&attr.name_or_empty()) && rustc_attr_parsing::is_builtin_attr(*attr) + !attr.has_any_name(&arr) && rustc_attr_parsing::is_builtin_attr(*attr) }) .for_each(|attr| { if attr.is_doc_comment() { @@ -945,8 +945,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { self.visit_attrs_vis_ident(&item.attrs, &item.vis, ident); self.check_defaultness(item.span, *defaultness); - let is_intrinsic = - item.attrs.iter().any(|a| a.name_or_empty() == sym::rustc_intrinsic); + let is_intrinsic = item.attrs.iter().any(|a| a.has_name(sym::rustc_intrinsic)); if body.is_none() && !is_intrinsic { self.dcx().emit_err(errors::FnWithoutBody { span: item.span, diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg.rs b/compiler/rustc_attr_parsing/src/attributes/cfg.rs index 0d6d521b40c61..a40112e27a237 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg.rs @@ -117,7 +117,7 @@ pub fn eval_condition( }; match &cfg.kind { - MetaItemKind::List(mis) if cfg.name_or_empty() == sym::version => { + MetaItemKind::List(mis) if cfg.has_name(sym::version) => { try_gate_cfg(sym::version, cfg.span, sess, features); let (min_version, span) = match &mis[..] { [MetaItemInner::Lit(MetaItemLit { kind: LitKind::Str(sym, ..), span, .. })] => { @@ -164,18 +164,18 @@ pub fn eval_condition( // The unwraps below may look dangerous, but we've already asserted // that they won't fail with the loop above. - match cfg.name_or_empty() { - sym::any => mis + match cfg.name() { + Some(sym::any) => mis .iter() // We don't use any() here, because we want to evaluate all cfg condition // as eval_condition can (and does) extra checks .fold(false, |res, mi| res | eval_condition(mi, sess, features, eval)), - sym::all => mis + Some(sym::all) => mis .iter() // We don't use all() here, because we want to evaluate all cfg condition // as eval_condition can (and does) extra checks .fold(true, |res, mi| res & eval_condition(mi, sess, features, eval)), - sym::not => { + Some(sym::not) => { let [mi] = mis.as_slice() else { dcx.emit_err(session_diagnostics::ExpectedOneCfgPattern { span: cfg.span }); return false; @@ -183,7 +183,7 @@ pub fn eval_condition( !eval_condition(mi, sess, features, eval) } - sym::target => { + Some(sym::target) => { if let Some(features) = features && !features.cfg_target_compact() { diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 3bf03f84ce8fd..972614a3366cd 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -222,7 +222,7 @@ impl<'sess> AttributeParser<'sess> { // if we're only looking for a single attribute, // skip all the ones we don't care about if let Some(expected) = self.parse_only { - if attr.name_or_empty() != expected { + if !attr.has_name(expected) { continue; } } @@ -232,7 +232,7 @@ impl<'sess> AttributeParser<'sess> { // that's expanded right? But no, sometimes, when parsing attributes on macros, // we already use the lowering logic and these are still there. So, when `omit_doc` // is set we *also* want to ignore these - if omit_doc == OmitDoc::Skip && attr.name_or_empty() == sym::doc { + if omit_doc == OmitDoc::Skip && attr.has_name(sym::doc) { continue; } @@ -250,7 +250,7 @@ impl<'sess> AttributeParser<'sess> { })) } // // FIXME: make doc attributes go through a proper attribute parser - // ast::AttrKind::Normal(n) if n.name_or_empty() == sym::doc => { + // ast::AttrKind::Normal(n) if n.has_name(sym::doc) => { // let p = GenericMetaItemParser::from_attr(&n, self.dcx()); // // attributes.push(Attribute::Parsed(AttributeKind::DocComment { diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index b9197be444266..d9aac54ee73c7 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -527,15 +527,14 @@ impl<'a> TraitDef<'a> { item.attrs .iter() .filter(|a| { - [ + a.has_any_name(&[ sym::allow, sym::warn, sym::deny, sym::forbid, sym::stable, sym::unstable, - ] - .contains(&a.name_or_empty()) + ]) }) .cloned(), ); diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index ddb6118898334..449336424dc52 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -345,20 +345,26 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { no_sanitize_span = Some(attr.span()); if let Some(list) = attr.meta_item_list() { for item in list.iter() { - match item.name_or_empty() { - sym::address => { + match item.name() { + Some(sym::address) => { codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS } - sym::cfi => codegen_fn_attrs.no_sanitize |= SanitizerSet::CFI, - sym::kcfi => codegen_fn_attrs.no_sanitize |= SanitizerSet::KCFI, - sym::memory => codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY, - sym::memtag => codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMTAG, - sym::shadow_call_stack => { + Some(sym::cfi) => codegen_fn_attrs.no_sanitize |= SanitizerSet::CFI, + Some(sym::kcfi) => codegen_fn_attrs.no_sanitize |= SanitizerSet::KCFI, + Some(sym::memory) => { + codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY + } + Some(sym::memtag) => { + codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMTAG + } + Some(sym::shadow_call_stack) => { codegen_fn_attrs.no_sanitize |= SanitizerSet::SHADOWCALLSTACK } - sym::thread => codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD, - sym::hwaddress => { + Some(sym::thread) => { + codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD + } + Some(sym::hwaddress) => { codegen_fn_attrs.no_sanitize |= SanitizerSet::HWADDRESS } _ => { @@ -419,9 +425,9 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { continue; }; - let attrib_to_write = match meta_item.name_or_empty() { - sym::prefix_nops => &mut prefix, - sym::entry_nops => &mut entry, + let attrib_to_write = match meta_item.name() { + Some(sym::prefix_nops) => &mut prefix, + Some(sym::entry_nops) => &mut entry, _ => { tcx.dcx().emit_err(errors::UnexpectedParameterName { span: item.span(), @@ -785,8 +791,7 @@ impl<'a> MixedExportNameAndNoMangleState<'a> { fn autodiff_attrs(tcx: TyCtxt<'_>, id: DefId) -> Option { let attrs = tcx.get_attrs(id, sym::rustc_autodiff); - let attrs = - attrs.filter(|attr| attr.name_or_empty() == sym::rustc_autodiff).collect::>(); + let attrs = attrs.filter(|attr| attr.has_name(sym::rustc_autodiff)).collect::>(); // check for exactly one autodiff attribute on placeholder functions. // There should only be one, since we generate a new placeholder per ad macro. diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 49f6d58172ff6..f5eaf7d616b22 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -824,10 +824,10 @@ impl SyntaxExtension { return Err(item.span); } - match item.name_or_empty() { - sym::no => Ok(CollapseMacroDebuginfo::No), - sym::external => Ok(CollapseMacroDebuginfo::External), - sym::yes => Ok(CollapseMacroDebuginfo::Yes), + match item.name() { + Some(sym::no) => Ok(CollapseMacroDebuginfo::No), + Some(sym::external) => Ok(CollapseMacroDebuginfo::External), + Some(sym::yes) => Ok(CollapseMacroDebuginfo::Yes), _ => Err(item.path.span), } } diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 1b539477d51ec..1e26d66819430 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -2053,8 +2053,8 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { ) -> Node::OutputTy { loop { return match self.take_first_attr(&mut node) { - Some((attr, pos, derives)) => match attr.name_or_empty() { - sym::cfg => { + Some((attr, pos, derives)) => match attr.name() { + Some(sym::cfg) => { let (res, meta_item) = self.expand_cfg_true(&mut node, attr, pos); if res { continue; @@ -2071,7 +2071,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { } Default::default() } - sym::cfg_attr => { + Some(sym::cfg_attr) => { self.expand_cfg_attr(&mut node, &attr, pos); continue; } @@ -2144,8 +2144,8 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { ) { loop { return match self.take_first_attr(node) { - Some((attr, pos, derives)) => match attr.name_or_empty() { - sym::cfg => { + Some((attr, pos, derives)) => match attr.name() { + Some(sym::cfg) => { let span = attr.span; if self.expand_cfg_true(node, attr, pos).0 { continue; @@ -2154,7 +2154,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { node.expand_cfg_false(self, pos, span); continue; } - sym::cfg_attr => { + Some(sym::cfg_attr) => { self.expand_cfg_attr(node, &attr, pos); continue; } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 6455f33b9d153..897831f627660 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1237,7 +1237,7 @@ impl AttributeExt for Attribute { Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => { Some((*comment, *kind)) } - Attribute::Unparsed(_) if self.name_or_empty() == sym::doc => { + Attribute::Unparsed(_) if self.has_name(sym::doc) => { self.value_str().map(|s| (s, CommentKind::Line)) } _ => None, @@ -1262,8 +1262,8 @@ impl Attribute { } #[inline] - pub fn name_or_empty(&self) -> Symbol { - AttributeExt::name_or_empty(self) + pub fn name(&self) -> Option { + AttributeExt::name(self) } #[inline] @@ -1301,6 +1301,11 @@ impl Attribute { AttributeExt::has_name(self, name) } + #[inline] + pub fn has_any_name(&self, names: &[Symbol]) -> bool { + AttributeExt::has_any_name(self, names) + } + #[inline] pub fn span(&self) -> Span { AttributeExt::span(self) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index 74cc8181418c5..934820eb4dafb 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -488,7 +488,7 @@ fn parse_never_type_options_attr( item.span(), format!( "unknown or duplicate never type option: `{}` (supported: `fallback`, `diverging_block_default`)", - item.name_or_empty() + item.name().unwrap() ), ); } diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index ba4396a5ab35b..1d3a081cbb884 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -2334,8 +2334,9 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { let hir_id = self.fcx.tcx.local_def_id_to_hir_id(local_def_id); let attrs = self.fcx.tcx.hir_attrs(hir_id); for attr in attrs { - if sym::doc == attr.name_or_empty() { - } else if sym::rustc_confusables == attr.name_or_empty() { + if attr.has_name(sym::doc) { + // do nothing + } else if attr.has_name(sym::rustc_confusables) { let Some(confusables) = attr.meta_item_list() else { continue; }; @@ -2355,7 +2356,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { continue; }; for v in values { - if v.name_or_empty() != sym::alias { + if !v.has_name(sym::alias) { continue; } if let Some(nested) = v.meta_item_list() { diff --git a/compiler/rustc_incremental/messages.ftl b/compiler/rustc_incremental/messages.ftl index 2a65101d360d3..bbc1fab05dfeb 100644 --- a/compiler/rustc_incremental/messages.ftl +++ b/compiler/rustc_incremental/messages.ftl @@ -93,7 +93,7 @@ incremental_undefined_clean_dirty_assertions = incremental_undefined_clean_dirty_assertions_item = clean/dirty auto-assertions not yet defined for Node::Item.node={$kind} -incremental_unknown_item = unknown item `{$name}` +incremental_unknown_rustc_clean_argument = unknown `rustc_clean` argument incremental_unrecognized_depnode = unrecognized `DepNode` variant: {$name} diff --git a/compiler/rustc_incremental/src/errors.rs b/compiler/rustc_incremental/src/errors.rs index b4a207386dc44..dbc72d085be99 100644 --- a/compiler/rustc_incremental/src/errors.rs +++ b/compiler/rustc_incremental/src/errors.rs @@ -107,11 +107,10 @@ pub(crate) struct NotLoaded<'a> { } #[derive(Diagnostic)] -#[diag(incremental_unknown_item)] -pub(crate) struct UnknownItem { +#[diag(incremental_unknown_rustc_clean_argument)] +pub(crate) struct UnknownRustcCleanArgument { #[primary_span] pub span: Span, - pub name: Symbol, } #[derive(Diagnostic)] diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index d40a0d514f6f9..64166255fa485 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -405,8 +405,7 @@ fn check_config(tcx: TyCtxt<'_>, attr: &Attribute) -> bool { debug!("check_config: searching for cfg {:?}", value); cfg = Some(config.contains(&(value, None))); } else if !(item.has_name(EXCEPT) || item.has_name(LOADED_FROM_DISK)) { - tcx.dcx() - .emit_err(errors::UnknownItem { span: attr.span(), name: item.name_or_empty() }); + tcx.dcx().emit_err(errors::UnknownRustcCleanArgument { span: item.span() }); } } diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 7fdbae3a59d7e..b4069b317bfa1 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -249,7 +249,7 @@ impl Level { /// Converts an `Attribute` to a level. pub fn from_attr(attr: &impl AttributeExt) -> Option<(Self, Option)> { - Self::from_symbol(attr.name_or_empty(), || Some(attr.id())) + attr.name().and_then(|name| Self::from_symbol(name, || Some(attr.id()))) } /// Converts a `Symbol` to a level. diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs index cfb0de8475c8f..cee9cff077503 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -226,8 +226,8 @@ impl<'tcx> Collector<'tcx> { let mut wasm_import_module = None; let mut import_name_type = None; for item in items.iter() { - match item.name_or_empty() { - sym::name => { + match item.name() { + Some(sym::name) => { if name.is_some() { sess.dcx().emit_err(errors::MultipleNamesInLink { span: item.span() }); continue; @@ -242,7 +242,7 @@ impl<'tcx> Collector<'tcx> { } name = Some((link_name, span)); } - sym::kind => { + Some(sym::kind) => { if kind.is_some() { sess.dcx().emit_err(errors::MultipleKindsInLink { span: item.span() }); continue; @@ -304,7 +304,7 @@ impl<'tcx> Collector<'tcx> { }; kind = Some(link_kind); } - sym::modifiers => { + Some(sym::modifiers) => { if modifiers.is_some() { sess.dcx() .emit_err(errors::MultipleLinkModifiers { span: item.span() }); @@ -316,7 +316,7 @@ impl<'tcx> Collector<'tcx> { }; modifiers = Some((link_modifiers, item.name_value_literal_span().unwrap())); } - sym::cfg => { + Some(sym::cfg) => { if cfg.is_some() { sess.dcx().emit_err(errors::MultipleCfgs { span: item.span() }); continue; @@ -346,7 +346,7 @@ impl<'tcx> Collector<'tcx> { } cfg = Some(link_cfg.clone()); } - sym::wasm_import_module => { + Some(sym::wasm_import_module) => { if wasm_import_module.is_some() { sess.dcx().emit_err(errors::MultipleWasmImport { span: item.span() }); continue; @@ -357,7 +357,7 @@ impl<'tcx> Collector<'tcx> { }; wasm_import_module = Some((link_wasm_import_module, item.span())); } - sym::import_name_type => { + Some(sym::import_name_type) => { if import_name_type.is_some() { sess.dcx() .emit_err(errors::MultipleImportNameType { span: item.span() }); diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 177318bfe15e9..3ea61d1b40a60 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -821,7 +821,9 @@ struct AnalyzeAttrState<'a> { #[inline] fn analyze_attr(attr: &impl AttributeExt, state: &mut AnalyzeAttrState<'_>) -> bool { let mut should_encode = false; - if !rustc_feature::encode_cross_crate(attr.name_or_empty()) { + if let Some(name) = attr.name() + && !rustc_feature::encode_cross_crate(name) + { // Attributes not marked encode-cross-crate don't need to be encoded for downstream crates. } else if attr.doc_str().is_some() { // We keep all doc comments reachable to rustdoc because they might be "imported" into diff --git a/compiler/rustc_mir_build/src/builder/custom/mod.rs b/compiler/rustc_mir_build/src/builder/custom/mod.rs index bfc16816e2e5e..902a6e7f115be 100644 --- a/compiler/rustc_mir_build/src/builder/custom/mod.rs +++ b/compiler/rustc_mir_build/src/builder/custom/mod.rs @@ -103,8 +103,9 @@ fn parse_attribute(attr: &Attribute) -> MirPhase { let mut dialect: Option = None; let mut phase: Option = None; + // Not handling errors properly for this internal attribute; will just abort on errors. for nested in meta_items { - let name = nested.name_or_empty(); + let name = nested.name().unwrap(); let value = nested.value_str().unwrap().as_str().to_string(); match name.as_str() { "dialect" => { diff --git a/compiler/rustc_mir_build/src/builder/mod.rs b/compiler/rustc_mir_build/src/builder/mod.rs index 8ca9ab58e4571..59a52ae67cb1f 100644 --- a/compiler/rustc_mir_build/src/builder/mod.rs +++ b/compiler/rustc_mir_build/src/builder/mod.rs @@ -485,7 +485,7 @@ fn construct_fn<'tcx>( }; if let Some(custom_mir_attr) = - tcx.hir_attrs(fn_id).iter().find(|attr| attr.name_or_empty() == sym::custom_mir) + tcx.hir_attrs(fn_id).iter().find(|attr| attr.has_name(sym::custom_mir)) { return custom::build_custom_mir( tcx, diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index b3daed8a7e017..2f593b9a0a741 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -113,7 +113,7 @@ impl<'tcx> ThirBuildCx<'tcx> { apply_adjustments: tcx .hir_attrs(hir_id) .iter() - .all(|attr| attr.name_or_empty() != rustc_span::sym::custom_mir), + .all(|attr| !attr.has_name(rustc_span::sym::custom_mir)), } } diff --git a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs index c436b8c0fb019..144fa8c6fddda 100644 --- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs +++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs @@ -144,9 +144,10 @@ impl RustcMirAttrs { attr: &ast::MetaItemInner, mapper: impl FnOnce(Symbol) -> Result, ) -> Result<(), ()> { + // Unwrapping the name is safe because this is only called when `has_name` has succeeded. if field.is_some() { tcx.dcx() - .emit_err(DuplicateValuesFor { span: attr.span(), name: attr.name_or_empty() }); + .emit_err(DuplicateValuesFor { span: attr.span(), name: attr.name().unwrap() }); return Err(()); } @@ -156,7 +157,7 @@ impl RustcMirAttrs { Ok(()) } else { tcx.dcx() - .emit_err(RequiresAnArgument { span: attr.span(), name: attr.name_or_empty() }); + .emit_err(RequiresAnArgument { span: attr.span(), name: attr.name().unwrap() }); Err(()) } } diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index 6ee5e356435c8..99789b74488c9 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -404,7 +404,7 @@ 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 = `{$name}` isn't a valid `#[macro_export]` argument +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 @@ -771,8 +771,8 @@ passes_unreachable_due_to_uninhabited = unreachable {$descr} .label_orig = any code following this expression is unreachable .note = this expression has type `{$ty}`, which is uninhabited -passes_unrecognized_field = - unrecognized field name `{$name}` +passes_unrecognized_argument = + unrecognized argument passes_unstable_attr_for_already_stable_feature = can't mark as unstable using an already stable feature diff --git a/compiler/rustc_passes/src/abi_test.rs b/compiler/rustc_passes/src/abi_test.rs index 671b7d7ad76cf..b139ed6a66c38 100644 --- a/compiler/rustc_passes/src/abi_test.rs +++ b/compiler/rustc_passes/src/abi_test.rs @@ -9,7 +9,7 @@ use rustc_span::sym; use rustc_target::callconv::FnAbi; use super::layout_test::ensure_wf; -use crate::errors::{AbiInvalidAttribute, AbiNe, AbiOf, UnrecognizedField}; +use crate::errors::{AbiInvalidAttribute, AbiNe, AbiOf, UnrecognizedArgument}; pub fn test_abi(tcx: TyCtxt<'_>) { if !tcx.features().rustc_attrs() { @@ -77,8 +77,8 @@ fn dump_abi_of_fn_item(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribut // The `..` are the names of fields to dump. let meta_items = attr.meta_item_list().unwrap_or_default(); for meta_item in meta_items { - match meta_item.name_or_empty() { - sym::debug => { + match meta_item.name() { + Some(sym::debug) => { let fn_name = tcx.item_name(item_def_id.into()); tcx.dcx().emit_err(AbiOf { span: tcx.def_span(item_def_id), @@ -88,8 +88,8 @@ fn dump_abi_of_fn_item(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribut }); } - name => { - tcx.dcx().emit_err(UnrecognizedField { span: meta_item.span(), name }); + _ => { + tcx.dcx().emit_err(UnrecognizedArgument { span: meta_item.span() }); } } } @@ -118,8 +118,8 @@ fn dump_abi_of_fn_type(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribut } let meta_items = attr.meta_item_list().unwrap_or_default(); for meta_item in meta_items { - match meta_item.name_or_empty() { - sym::debug => { + match meta_item.name() { + Some(sym::debug) => { let ty::FnPtr(sig_tys, hdr) = ty.kind() else { span_bug!( meta_item.span(), @@ -138,7 +138,7 @@ fn dump_abi_of_fn_type(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribut let fn_name = tcx.item_name(item_def_id.into()); tcx.dcx().emit_err(AbiOf { span, fn_name, fn_abi: format!("{:#?}", abi) }); } - sym::assert_eq => { + Some(sym::assert_eq) => { let ty::Tuple(fields) = ty.kind() else { span_bug!( meta_item.span(), @@ -188,8 +188,8 @@ fn dump_abi_of_fn_type(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribut }); } } - name => { - tcx.dcx().emit_err(UnrecognizedField { span: meta_item.span(), name }); + _ => { + tcx.dcx().emit_err(UnrecognizedArgument { span: meta_item.span() }); } } } diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index dcfecdc26ea21..cbe5058b55191 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -523,9 +523,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { fn check_no_sanitize(&self, attr: &Attribute, span: Span, target: Target) { if let Some(list) = attr.meta_item_list() { for item in list.iter() { - let sym = item.name_or_empty(); + let sym = item.name(); match sym { - sym::address | sym::hwaddress => { + Some(s @ sym::address | s @ sym::hwaddress) => { let is_valid = matches!(target, Target::Fn | Target::Method(..) | Target::Static); if !is_valid { @@ -533,7 +533,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr_span: item.span(), defn_span: span, accepted_kind: "a function or static", - attr_str: sym.as_str(), + attr_str: s.as_str(), }); } } @@ -544,7 +544,10 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr_span: item.span(), defn_span: span, accepted_kind: "a function", - attr_str: sym.as_str(), + attr_str: &match sym { + Some(name) => name.to_string(), + None => "...".to_string(), + }, }); } } @@ -592,7 +595,8 @@ impl<'tcx> CheckAttrVisitor<'tcx> { // * `#[track_caller]` // * `#[test]`, `#[ignore]`, `#[should_panic]` // - // NOTE: when making changes to this list, check that `error_codes/E0736.md` remains accurate + // NOTE: when making changes to this list, check that `error_codes/E0736.md` remains + // accurate. const ALLOW_LIST: &[rustc_span::Symbol] = &[ // conditional compilation sym::cfg_trace, @@ -675,11 +679,11 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - if !ALLOW_LIST.iter().any(|name| other_attr.has_name(*name)) { + if !other_attr.has_any_name(ALLOW_LIST) { self.dcx().emit_err(errors::NakedFunctionIncompatibleAttribute { span: other_attr.span(), naked_span: attr.span(), - attr: other_attr.name_or_empty(), + attr: other_attr.name().unwrap(), }); return; @@ -1153,7 +1157,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { ) { match target { Target::Use | Target::ExternCrate => { - let do_inline = meta.name_or_empty() == sym::inline; + let do_inline = meta.has_name(sym::inline); if let Some((prev_inline, prev_span)) = *specified_inline { if do_inline != prev_inline { let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]); @@ -1263,8 +1267,8 @@ impl<'tcx> CheckAttrVisitor<'tcx> { fn check_test_attr(&self, meta: &MetaItemInner, hir_id: HirId) { if let Some(metas) = meta.meta_item_list() { for i_meta in metas { - match (i_meta.name_or_empty(), i_meta.meta_item()) { - (sym::attr | sym::no_crate_inject, _) => {} + match (i_meta.name(), i_meta.meta_item()) { + (Some(sym::attr | sym::no_crate_inject), _) => {} (_, Some(m)) => { self.tcx.emit_node_span_lint( INVALID_DOC_ATTRIBUTES, @@ -1325,61 +1329,63 @@ impl<'tcx> CheckAttrVisitor<'tcx> { if let Some(list) = attr.meta_item_list() { for meta in &list { if let Some(i_meta) = meta.meta_item() { - match i_meta.name_or_empty() { - sym::alias => { + match i_meta.name() { + Some(sym::alias) => { if self.check_attr_not_crate_level(meta, hir_id, "alias") { self.check_doc_alias(meta, hir_id, target, aliases); } } - sym::keyword => { + Some(sym::keyword) => { if self.check_attr_not_crate_level(meta, hir_id, "keyword") { self.check_doc_keyword(meta, hir_id); } } - sym::fake_variadic => { + Some(sym::fake_variadic) => { if self.check_attr_not_crate_level(meta, hir_id, "fake_variadic") { self.check_doc_fake_variadic(meta, hir_id); } } - sym::search_unbox => { + Some(sym::search_unbox) => { if self.check_attr_not_crate_level(meta, hir_id, "fake_variadic") { self.check_doc_search_unbox(meta, hir_id); } } - sym::test => { + Some(sym::test) => { if self.check_attr_crate_level(attr, meta, hir_id) { self.check_test_attr(meta, hir_id); } } - sym::html_favicon_url - | sym::html_logo_url - | sym::html_playground_url - | sym::issue_tracker_base_url - | sym::html_root_url - | sym::html_no_source => { + Some( + sym::html_favicon_url + | sym::html_logo_url + | sym::html_playground_url + | sym::issue_tracker_base_url + | sym::html_root_url + | sym::html_no_source, + ) => { self.check_attr_crate_level(attr, meta, hir_id); } - sym::cfg_hide => { + Some(sym::cfg_hide) => { if self.check_attr_crate_level(attr, meta, hir_id) { self.check_doc_cfg_hide(meta, hir_id); } } - sym::inline | sym::no_inline => { + Some(sym::inline | sym::no_inline) => { self.check_doc_inline(attr, meta, hir_id, target, specified_inline) } - sym::masked => self.check_doc_masked(attr, meta, hir_id, target), + Some(sym::masked) => self.check_doc_masked(attr, meta, hir_id, target), - sym::cfg | sym::hidden | sym::notable_trait => {} + Some(sym::cfg | sym::hidden | sym::notable_trait) => {} - sym::rust_logo => { + Some(sym::rust_logo) => { if self.check_attr_crate_level(attr, meta, hir_id) && !self.tcx.features().rustdoc_internals() { @@ -2302,7 +2308,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } fn check_macro_use(&self, hir_id: HirId, attr: &Attribute, target: Target) { - let name = attr.name_or_empty(); + let name = attr.name().unwrap(); match target { Target::ExternCrate | Target::Mod => {} _ => { @@ -2334,12 +2340,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr.span(), errors::MacroExport::TooManyItems, ); - } else if meta_item_list[0].name_or_empty() != sym::local_inner_macros { + } 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::UnknownItem { name: meta_item_list[0].name_or_empty() }, + errors::MacroExport::InvalidArgument, ); } } else { @@ -2384,33 +2390,28 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } // Warn on useless empty attributes. - let note = if (matches!( - attr.name_or_empty(), - sym::macro_use - | sym::allow - | sym::expect - | sym::warn - | sym::deny - | sym::forbid - | sym::feature - | sym::target_feature - ) && attr.meta_item_list().is_some_and(|list| list.is_empty())) + let note = if attr.has_any_name(&[ + sym::macro_use, + sym::allow, + sym::expect, + sym::warn, + sym::deny, + sym::forbid, + sym::feature, + sym::target_feature, + ]) && attr.meta_item_list().is_some_and(|list| list.is_empty()) { - errors::UnusedNote::EmptyList { name: attr.name_or_empty() } - } else if matches!( - attr.name_or_empty(), - sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect - ) && let Some(meta) = attr.meta_item_list() + errors::UnusedNote::EmptyList { name: attr.name().unwrap() } + } else if attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect]) + && let Some(meta) = attr.meta_item_list() && let [meta] = meta.as_slice() && let Some(item) = meta.meta_item() && let MetaItemKind::NameValue(_) = &item.kind && item.path == sym::reason { - errors::UnusedNote::NoLints { name: attr.name_or_empty() } - } else if matches!( - attr.name_or_empty(), - sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect - ) && let Some(meta) = attr.meta_item_list() + errors::UnusedNote::NoLints { name: attr.name().unwrap() } + } else if attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect]) + && let Some(meta) = attr.meta_item_list() && meta.iter().any(|meta| { meta.meta_item().map_or(false, |item| item.path == sym::linker_messages) }) @@ -2443,7 +2444,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { return; } } - } else if attr.name_or_empty() == sym::default_method_body_is_const { + } else if attr.has_name(sym::default_method_body_is_const) { errors::UnusedNote::DefaultMethodBodyConst } else { return; @@ -2900,10 +2901,11 @@ fn check_duplicates( if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() { return; } + let attr_name = attr.name().unwrap(); match duplicates { DuplicatesOk => {} WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => { - match seen.entry(attr.name_or_empty()) { + match seen.entry(attr_name) { Entry::Occupied(mut entry) => { let (this, other) = if matches!(duplicates, FutureWarnPreceding) { let to_remove = entry.insert(attr.span()); @@ -2930,7 +2932,7 @@ fn check_duplicates( } } } - ErrorFollowing | ErrorPreceding => match seen.entry(attr.name_or_empty()) { + ErrorFollowing | ErrorPreceding => match seen.entry(attr_name) { Entry::Occupied(mut entry) => { let (this, other) = if matches!(duplicates, ErrorPreceding) { let to_remove = entry.insert(attr.span()); @@ -2938,11 +2940,7 @@ fn check_duplicates( } else { (attr.span(), *entry.get()) }; - tcx.dcx().emit_err(errors::UnusedMultiple { - this, - other, - name: attr.name_or_empty(), - }); + tcx.dcx().emit_err(errors::UnusedMultiple { this, other, name: attr_name }); } Entry::Vacant(entry) => { entry.insert(attr.span()); diff --git a/compiler/rustc_passes/src/debugger_visualizer.rs b/compiler/rustc_passes/src/debugger_visualizer.rs index 062d56a79a0b4..7a7a8175e5569 100644 --- a/compiler/rustc_passes/src/debugger_visualizer.rs +++ b/compiler/rustc_passes/src/debugger_visualizer.rs @@ -28,17 +28,17 @@ impl DebuggerVisualizerCollector<'_> { return; }; - let (visualizer_type, visualizer_path) = - match (meta_item.name_or_empty(), meta_item.value_str()) { - (sym::natvis_file, Some(value)) => (DebuggerVisualizerType::Natvis, value), - (sym::gdb_script_file, Some(value)) => { - (DebuggerVisualizerType::GdbPrettyPrinter, value) - } - (_, _) => { - self.sess.dcx().emit_err(DebugVisualizerInvalid { span: meta_item.span }); - return; - } - }; + let (visualizer_type, visualizer_path) = match (meta_item.name(), meta_item.value_str()) + { + (Some(sym::natvis_file), Some(value)) => (DebuggerVisualizerType::Natvis, value), + (Some(sym::gdb_script_file), Some(value)) => { + (DebuggerVisualizerType::GdbPrettyPrinter, value) + } + (_, _) => { + self.sess.dcx().emit_err(DebugVisualizerInvalid { span: meta_item.span }); + return; + } + }; let file = match resolve_path(&self.sess, visualizer_path.as_str(), attr.span) { Ok(file) => file, diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 075927a54f805..26ee89a71640c 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -756,7 +756,7 @@ pub(crate) enum MacroExport { OnDeclMacro, #[diag(passes_invalid_macro_export_arguments)] - UnknownItem { name: Symbol }, + InvalidArgument, #[diag(passes_invalid_macro_export_arguments_too_many_items)] TooManyItems, @@ -1045,11 +1045,10 @@ pub(crate) struct AbiInvalidAttribute { } #[derive(Diagnostic)] -#[diag(passes_unrecognized_field)] -pub(crate) struct UnrecognizedField { +#[diag(passes_unrecognized_argument)] +pub(crate) struct UnrecognizedArgument { #[primary_span] pub span: Span, - pub name: Symbol, } #[derive(Diagnostic)] diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index d4512c9417eb4..a19faf0fa8367 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -13,7 +13,7 @@ use rustc_trait_selection::traits; use crate::errors::{ LayoutAbi, LayoutAlign, LayoutHomogeneousAggregate, LayoutInvalidAttribute, LayoutOf, - LayoutSize, UnrecognizedField, + LayoutSize, UnrecognizedArgument, }; pub fn test_layout(tcx: TyCtxt<'_>) { @@ -79,28 +79,28 @@ fn dump_layout_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribute) { // The `..` are the names of fields to dump. let meta_items = attr.meta_item_list().unwrap_or_default(); for meta_item in meta_items { - match meta_item.name_or_empty() { + match meta_item.name() { // FIXME: this never was about ABI and now this dump arg is confusing - sym::abi => { + Some(sym::abi) => { tcx.dcx().emit_err(LayoutAbi { span, abi: format!("{:?}", ty_layout.backend_repr), }); } - sym::align => { + Some(sym::align) => { tcx.dcx().emit_err(LayoutAlign { span, align: format!("{:?}", ty_layout.align), }); } - sym::size => { + Some(sym::size) => { tcx.dcx() .emit_err(LayoutSize { span, size: format!("{:?}", ty_layout.size) }); } - sym::homogeneous_aggregate => { + Some(sym::homogeneous_aggregate) => { tcx.dcx().emit_err(LayoutHomogeneousAggregate { span, homogeneous_aggregate: format!( @@ -111,15 +111,15 @@ fn dump_layout_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribute) { }); } - sym::debug => { + Some(sym::debug) => { let normalized_ty = tcx.normalize_erasing_regions(typing_env, ty); // FIXME: using the `Debug` impl here isn't ideal. let ty_layout = format!("{:#?}", *ty_layout); tcx.dcx().emit_err(LayoutOf { span, normalized_ty, ty_layout }); } - name => { - tcx.dcx().emit_err(UnrecognizedField { span: meta_item.span(), name }); + _ => { + tcx.dcx().emit_err(UnrecognizedArgument { span: meta_item.span() }); } } } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 2af567f2ec502..6b9ce92b183d2 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1185,6 +1185,7 @@ symbols! { instruction_set, integer_: "integer", // underscore to avoid clashing with the function `sym::integer` below integral, + internal_features, into_async_iter_into_iter, into_future, into_iter, diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 31aa84535cc4e..b084eded40352 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -788,7 +788,7 @@ impl Item { } _ => Some(rustc_hir_pretty::attribute_to_string(&tcx, attr)), } - } else if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) { + } else if attr.has_any_name(ALLOWED_ATTRIBUTES) { Some( rustc_hir_pretty::attribute_to_string(&tcx, attr) .replace("\\\n", "") diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index c4dea79370d1f..f7695ac8635bb 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -412,9 +412,7 @@ pub(crate) fn run_global_ctxt( // Process all of the crate attributes, extracting plugin metadata along // with the passes which we are supposed to run. for attr in krate.module.attrs.lists(sym::doc) { - let name = attr.name_or_empty(); - - if attr.is_word() && name == sym::document_private_items { + if attr.is_word() && attr.has_name(sym::document_private_items) { ctxt.render_options.document_private = true; } } diff --git a/src/librustdoc/doctest/make.rs b/src/librustdoc/doctest/make.rs index 4edd5433de6cd..d5c965f7053e0 100644 --- a/src/librustdoc/doctest/make.rs +++ b/src/librustdoc/doctest/make.rs @@ -345,7 +345,7 @@ fn parse_source(source: &str, crate_name: &Option<&str>) -> Result) -> bool { let mut is_extern_crate = false; if !info.has_global_allocator - && item.attrs.iter().any(|attr| attr.name_or_empty() == sym::global_allocator) + && item.attrs.iter().any(|attr| attr.has_name(sym::global_allocator)) { info.has_global_allocator = true; } @@ -377,7 +377,7 @@ fn parse_source(source: &str, crate_name: &Option<&str>) -> Result) -> Result { for attr in &item.attrs { - let attr_name = attr.name_or_empty(); - - if attr.style == AttrStyle::Outer || not_crate_attrs.contains(&attr_name) { + if attr.style == AttrStyle::Outer || attr.has_any_name(not_crate_attrs) { // There is one exception to these attributes: // `#![allow(internal_features)]`. If this attribute is used, we need to // consider it only as a crate-level attribute. - if attr_name == sym::allow + if attr.has_name(sym::allow) && let Some(list) = attr.meta_item_list() - && list.iter().any(|sub_attr| { - sub_attr.name_or_empty().as_str() == "internal_features" - }) + && list.iter().any(|sub_attr| sub_attr.has_name(sym::internal_features)) { push_to_s(&mut info.crate_attrs, source, attr.span, &mut prev_span_hi); } else { diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index 596ac665fc313..f22935df96c87 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -521,23 +521,23 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { // Crawl the crate attributes looking for attributes which control how we're // going to emit HTML for attr in krate.module.attrs.lists(sym::doc) { - match (attr.name_or_empty(), attr.value_str()) { - (sym::html_favicon_url, Some(s)) => { + match (attr.name(), attr.value_str()) { + (Some(sym::html_favicon_url), Some(s)) => { layout.favicon = s.to_string(); } - (sym::html_logo_url, Some(s)) => { + (Some(sym::html_logo_url), Some(s)) => { layout.logo = s.to_string(); } - (sym::html_playground_url, Some(s)) => { + (Some(sym::html_playground_url), Some(s)) => { playground = Some(markdown::Playground { crate_name: Some(krate.name(tcx)), url: s.to_string(), }); } - (sym::issue_tracker_base_url, Some(s)) => { + (Some(sym::issue_tracker_base_url), Some(s)) => { issue_tracker_base_url = Some(s.to_string()); } - (sym::html_no_source, None) if attr.is_word() => { + (Some(sym::html_no_source), None) if attr.is_word() => { include_sources = false; } _ => {} diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index 9f450d654d52d..f715fc86e4e5d 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -2363,14 +2363,14 @@ pub fn is_no_std_crate(cx: &LateContext<'_>) -> bool { cx.tcx .hir_attrs(hir::CRATE_HIR_ID) .iter() - .any(|attr| attr.name_or_empty() == sym::no_std) + .any(|attr| attr.has_name(sym::no_std)) } pub fn is_no_core_crate(cx: &LateContext<'_>) -> bool { cx.tcx .hir_attrs(hir::CRATE_HIR_ID) .iter() - .any(|attr| attr.name_or_empty() == sym::no_core) + .any(|attr| attr.has_name(sym::no_core)) } /// Check if parent of a hir node is a trait implementation block. diff --git a/tests/ui/abi/debug.rs b/tests/ui/abi/debug.rs index e3260191e5c86..c0d8de05fda5e 100644 --- a/tests/ui/abi/debug.rs +++ b/tests/ui/abi/debug.rs @@ -53,5 +53,5 @@ type TestAbiNeSign = (fn(i32), fn(u32)); //~ ERROR: ABIs are not compatible #[rustc_abi(assert_eq)] type TestAbiEqNonsense = (fn((str, str)), fn((str, str))); //~ ERROR: cannot be known at compilation time -#[rustc_abi("assert_eq")] //~ ERROR unrecognized field name `` +#[rustc_abi("assert_eq")] //~ ERROR unrecognized argument type Bad = u32; diff --git a/tests/ui/abi/debug.stderr b/tests/ui/abi/debug.stderr index 717a95685cbe9..480f3f04215e7 100644 --- a/tests/ui/abi/debug.stderr +++ b/tests/ui/abi/debug.stderr @@ -906,7 +906,7 @@ LL | type TestAbiEqNonsense = (fn((str, str)), fn((str, str))); = help: the trait `Sized` is not implemented for `str` = note: only the last element of a tuple may have a dynamically sized type -error: unrecognized field name `` +error: unrecognized argument --> $DIR/debug.rs:56:13 | LL | #[rustc_abi("assert_eq")] diff --git a/tests/ui/attributes/invalid_macro_export_argument.deny.stderr b/tests/ui/attributes/invalid_macro_export_argument.deny.stderr index 897bcecc20e2a..9d44bd162c7b7 100644 --- a/tests/ui/attributes/invalid_macro_export_argument.deny.stderr +++ b/tests/ui/attributes/invalid_macro_export_argument.deny.stderr @@ -10,13 +10,13 @@ note: the lint level is defined here LL | #![cfg_attr(deny, deny(invalid_macro_export_arguments))] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: `not_local_inner_macros` isn't a valid `#[macro_export]` argument +error: invalid `#[macro_export]` argument --> $DIR/invalid_macro_export_argument.rs:13:16 | LL | #[macro_export(not_local_inner_macros)] | ^^^^^^^^^^^^^^^^^^^^^^ -error: `` isn't a valid `#[macro_export]` argument +error: invalid `#[macro_export]` argument --> $DIR/invalid_macro_export_argument.rs:33:16 | LL | #[macro_export("blah")] diff --git a/tests/ui/attributes/invalid_macro_export_argument.rs b/tests/ui/attributes/invalid_macro_export_argument.rs index c0aa7df2e8734..c5fe39d062a4e 100644 --- a/tests/ui/attributes/invalid_macro_export_argument.rs +++ b/tests/ui/attributes/invalid_macro_export_argument.rs @@ -11,7 +11,7 @@ macro_rules! a { } #[macro_export(not_local_inner_macros)] -//[deny]~^ ERROR `not_local_inner_macros` isn't a valid `#[macro_export]` argument +//[deny]~^ ERROR invalid `#[macro_export]` argument macro_rules! b { () => () } @@ -31,7 +31,7 @@ macro_rules! e { } #[macro_export("blah")] -//[deny]~^ ERROR `` isn't a valid `#[macro_export]` argument +//[deny]~^ ERROR invalid `#[macro_export]` argument macro_rules! f { () => () } diff --git a/tests/ui/attributes/no-sanitize.rs b/tests/ui/attributes/no-sanitize.rs index a7225efc7b800..ddf909be63a8a 100644 --- a/tests/ui/attributes/no-sanitize.rs +++ b/tests/ui/attributes/no-sanitize.rs @@ -40,6 +40,6 @@ fn valid() {} static VALID : i32 = 0; #[no_sanitize("address")] -//~^ ERROR `#[no_sanitize()]` should be applied to a function +//~^ ERROR `#[no_sanitize(...)]` should be applied to a function //~| ERROR invalid argument for `no_sanitize` static VALID2 : i32 = 0; diff --git a/tests/ui/attributes/no-sanitize.stderr b/tests/ui/attributes/no-sanitize.stderr index 1f24aa71af56d..8d5fbb109eadb 100644 --- a/tests/ui/attributes/no-sanitize.stderr +++ b/tests/ui/attributes/no-sanitize.stderr @@ -59,7 +59,7 @@ LL | #[no_sanitize(address, memory)] LL | static INVALID : i32 = 0; | ------------------------- not a function -error: `#[no_sanitize()]` should be applied to a function +error: `#[no_sanitize(...)]` should be applied to a function --> $DIR/no-sanitize.rs:42:15 | LL | #[no_sanitize("address")] From 846c10fecfdbda6e43073af226486ff7ec3f873d Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 16 Apr 2025 09:19:52 +1000 Subject: [PATCH 181/266] Avoid an `unwrap` in `RustcMirAttrs::set_field`. --- .../src/framework/graphviz.rs | 45 ++++++++++--------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs index 144fa8c6fddda..95f488a925b2c 100644 --- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs +++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs @@ -109,27 +109,29 @@ impl RustcMirAttrs { .flat_map(|attr| attr.meta_item_list().into_iter().flat_map(|v| v.into_iter())); for attr in rustc_mir_attrs { - let attr_result = if attr.has_name(sym::borrowck_graphviz_postflow) { - Self::set_field(&mut ret.basename_and_suffix, tcx, &attr, |s| { - let path = PathBuf::from(s.to_string()); - match path.file_name() { - Some(_) => Ok(path), - None => { - tcx.dcx().emit_err(PathMustEndInFilename { span: attr.span() }); + let attr_result = match attr.name() { + Some(name @ sym::borrowck_graphviz_postflow) => { + Self::set_field(&mut ret.basename_and_suffix, tcx, name, &attr, |s| { + let path = PathBuf::from(s.to_string()); + match path.file_name() { + Some(_) => Ok(path), + None => { + tcx.dcx().emit_err(PathMustEndInFilename { span: attr.span() }); + Err(()) + } + } + }) + } + Some(name @ sym::borrowck_graphviz_format) => { + Self::set_field(&mut ret.formatter, tcx, name, &attr, |s| match s { + sym::two_phase => Ok(s), + _ => { + tcx.dcx().emit_err(UnknownFormatter { span: attr.span() }); Err(()) } - } - }) - } else if attr.has_name(sym::borrowck_graphviz_format) { - Self::set_field(&mut ret.formatter, tcx, &attr, |s| match s { - sym::two_phase => Ok(s), - _ => { - tcx.dcx().emit_err(UnknownFormatter { span: attr.span() }); - Err(()) - } - }) - } else { - Ok(()) + }) + } + _ => Ok(()), }; result = result.and(attr_result); @@ -141,13 +143,12 @@ impl RustcMirAttrs { fn set_field( field: &mut Option, tcx: TyCtxt<'_>, + name: Symbol, attr: &ast::MetaItemInner, mapper: impl FnOnce(Symbol) -> Result, ) -> Result<(), ()> { - // Unwrapping the name is safe because this is only called when `has_name` has succeeded. if field.is_some() { - tcx.dcx() - .emit_err(DuplicateValuesFor { span: attr.span(), name: attr.name().unwrap() }); + tcx.dcx().emit_err(DuplicateValuesFor { span: attr.span(), name }); return Err(()); } From a114bcffe7c6cd4c7cf6dccac0a47ed49894ed2f Mon Sep 17 00:00:00 2001 From: jyn Date: Tue, 15 Apr 2025 17:01:58 -0400 Subject: [PATCH 182/266] document RUSTC_BOOTSTRAP, RUSTC_OVERRIDE_VERSION_STRING, and -Z allow-features in the unstable book --- .../src/compiler-flags/allow-features.md | 14 +++++ .../src/compiler-flags/rustc-bootstrap.md | 56 +++++++++++++++++++ .../rustc-override-version-string.md | 39 +++++++++++++ 3 files changed, 109 insertions(+) create mode 100644 src/doc/unstable-book/src/compiler-flags/allow-features.md create mode 100644 src/doc/unstable-book/src/compiler-flags/rustc-bootstrap.md create mode 100644 src/doc/unstable-book/src/compiler-flags/rustc-override-version-string.md diff --git a/src/doc/unstable-book/src/compiler-flags/allow-features.md b/src/doc/unstable-book/src/compiler-flags/allow-features.md new file mode 100644 index 0000000000000..84fa465c89b4b --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/allow-features.md @@ -0,0 +1,14 @@ +# `allow-features` + +This feature is perma-unstable and has no tracking issue. + +---- + +This flag allows limiting the features which can be enabled with `#![feature(...)]` attributes. +By default, all features are allowed on nightly and no features are allowed on stable or beta (but see [`RUSTC_BOOTSTRAP`]). + +Features are comma-separated, for example `-Z allow-features=ffi_pure,f16`. +If the flag is present, any feature listed will be allowed and any feature not listed will be disallowed. +Any unrecognized feature is ignored. + +[`RUSTC_BOOTSTRAP`]: ./rustc-bootstrap.html diff --git a/src/doc/unstable-book/src/compiler-flags/rustc-bootstrap.md b/src/doc/unstable-book/src/compiler-flags/rustc-bootstrap.md new file mode 100644 index 0000000000000..6895f23223867 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/rustc-bootstrap.md @@ -0,0 +1,56 @@ +# `RUSTC_BOOTSTRAP` + +This feature is perma-unstable and has no tracking issue. + +---- + +The `RUSTC_BOOTSTRAP` environment variable tells rustc to act as if it is a nightly compiler; +in particular, it allows `#![feature(...)]` attributes and `-Z` flags even on the stable release channel. + +Setting `RUSTC_BOOTSTRAP=1` instructs rustc to enable this for all crates. +Setting `RUSTC_BOOTSTRAP=crate_name` instructs rustc to only apply this to crates named `crate_name`. +Setting `RUSTC_BOOTSTRAP=-1` instructs rustc to act as if it is a stable compiler, even on the nightly release channel. +Cargo disallows setting `cargo::rustc-env=RUSTC_BOOTSTRAP` in build scripts. +Build systems can limit the features they enable with [`-Z allow-features=feature1,feature2`][Z-allow-features]. +Crates can fully opt out of unstable features by using [`#![forbid(unstable_features)]`][unstable-features] at the crate root (or any other way of enabling lints, such as `-F unstable-features`). + +[Z-allow-features]: ./allow-features.html +[unstable-features]: ../../rustc/lints/listing/allowed-by-default.html#unstable-features + +## Why does this environment variable exist? + +`RUSTC_BOOTSTRAP`, as the name suggests, is used for bootstrapping the compiler from an earlier version. +In particular, nightly is built with beta, and beta is built with stable. +Since the standard library and compiler both use unstable features, `RUSTC_BOOTSTRAP` is required so that we can use the previous version to build them. + +## Why is this environment variable so easy to use for people not in the rust project? + +Originally, `RUSTC_BOOTSTRAP` required passing in a hash of the previous compiler version, to discourage using it for any purpose other than bootstrapping. +That constraint was later relaxed; see for the discussion that happened at that time. + +People have at various times proposed re-adding the technical constraints. +However, doing so is extremely disruptive for several major projects that we very much want to keep using the latest stable toolchain version, such as Firefox, Rust for Linux, and Chromium. +We continue to allow `RUSTC_BOOTSTRAP` until we can come up with an alternative that does not disrupt our largest constituents. + +## Stability policy + +Despite being usable on stable, this is an unstable feature. +Like any other unstable feature, we reserve the right to change or remove this feature in the future, as well as any other unstable feature that it enables. +Using this feature opts you out of the normal stability/backwards compatibility guarantee of stable. + +Although we do not take technical measures to prevent it from being used, we strongly discourage using this feature. +If at all possible, please contribute to stabilizing the features you care about instead of bypassing the Rust project's stability policy. + +For library crates, we especially discourage the use of this feature. +The crates depending on you do not know that you use this feature, have little recourse if it breaks, and can be used in contexts that are hard to predict. + +For libraries that do use this feature, please document the versions you support (including a *maximum* as well as minimum version), and a mechanism to disable it. +If you do not have a mechanism to disable the use of `RUSTC_BOOTSTRAP`, consider removing its use altogether, such that people can only use your library if they are already using a nightly toolchain. +This leaves the choice of whether to opt-out of Rust's stability guarantees up to the end user building their code. + +## History + +- [Allowed without a hash](https://github.com/rust-lang/rust/pull/37265) ([discussion](https://github.com/rust-lang/rust/issues/36548)) +- [Extended to crate names](https://github.com/rust-lang/rust/pull/77802) ([discussion](https://github.com/rust-lang/cargo/issues/7088)) +- [Disallowed for build scripts](https://github.com/rust-lang/cargo/pull/9181) ([discussion](https://github.com/rust-lang/compiler-team/issues/350)) +- [Extended to emulate stable](https://github.com/rust-lang/rust/pull/132993) ([discussion](https://github.com/rust-lang/rust/issues/123404)) diff --git a/src/doc/unstable-book/src/compiler-flags/rustc-override-version-string.md b/src/doc/unstable-book/src/compiler-flags/rustc-override-version-string.md new file mode 100644 index 0000000000000..3d867b5f7146b --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/rustc-override-version-string.md @@ -0,0 +1,39 @@ +# `RUSTC_OVERRIDE_VERSION_STRING` + +This feature is perma-unstable and has no tracking issue. + +---- + +The `RUSTC_OVERRIDE_VERSION_STRING` environment variable overrides the version reported by `rustc --version`. For example: + +```console +$ rustc --version +rustc 1.87.0-nightly (43f0014ef 2025-03-25) +$ env RUSTC_OVERRIDE_VERSION_STRING=1.81.0-nightly rustc --version +rustc 1.81.0-nightly +``` + +Note that the version string is completely overwritten; i.e. rustc discards commit hash and commit date information unless it is explicitly included in the environment variable. The string only applies to the "release" part of the version; for example: +```console +$ RUSTC_OVERRIDE_VERSION_STRING="1.81.0-nightly (aaaaaaaaa 2025-03-22)" rustc -vV +rustc 1.81.0-nightly (aaaaaaaaa 2025-03-22) +binary: rustc +commit-hash: 43f0014ef0f242418674f49052ed39b70f73bc1c +commit-date: 2025-03-25 +host: x86_64-unknown-linux-gnu +release: 1.81.0-nightly (aaaaaaaaa 2025-03-22) +LLVM version: 20.1.1 +``` + +Note here that `commit-hash` and `commit-date` do not match the values in the string, and `release` includes the fake hash and date. + +This variable has no effect on whether or not unstable features are allowed to be used. It only affects the output of `--version`. + +## Why does this environment variable exist? + +Various library crates have incomplete or incorrect feature detection. +This environment variable allows bisecting crates that do incorrect detection with `version_check::supports_feature`. + +This is not intended to be used for any other case (and, except for bisection, is not particularly useful). + +See for further discussion. From 9f548e298ddb0eaa546b68c976199a93635d6855 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Thu, 17 Apr 2025 02:24:28 +0200 Subject: [PATCH 183/266] Support inlined cross-crate re-exported trait aliases --- src/librustdoc/clean/inline.rs | 43 +++++----- src/librustdoc/core.rs | 4 +- src/librustdoc/html/render/print_item.rs | 5 +- tests/rustdoc/auxiliary/ext-trait-aliases.rs | 13 +++ .../rustdoc/auxiliary/trait-alias-mention.rs | 3 - tests/rustdoc/trait-alias-mention.rs | 10 --- tests/rustdoc/trait-aliases.rs | 82 +++++++++++++++++++ tests/rustdoc/trait_alias.rs | 26 ------ 8 files changed, 122 insertions(+), 64 deletions(-) create mode 100644 tests/rustdoc/auxiliary/ext-trait-aliases.rs delete mode 100644 tests/rustdoc/auxiliary/trait-alias-mention.rs delete mode 100644 tests/rustdoc/trait-alias-mention.rs create mode 100644 tests/rustdoc/trait-aliases.rs delete mode 100644 tests/rustdoc/trait_alias.rs diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 3a2b6974681bc..2ea0fd8ad6c1b 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -67,9 +67,13 @@ pub(crate) fn try_inline( record_extern_fqn(cx, did, ItemType::Trait); cx.with_param_env(did, |cx| { build_impls(cx, did, attrs_without_docs, &mut ret); - clean::TraitItem(Box::new(build_external_trait(cx, did))) + clean::TraitItem(Box::new(build_trait(cx, did))) }) } + Res::Def(DefKind::TraitAlias, did) => { + record_extern_fqn(cx, did, ItemType::TraitAlias); + cx.with_param_env(did, |cx| clean::TraitAliasItem(build_trait_alias(cx, did))) + } Res::Def(DefKind::Fn, did) => { record_extern_fqn(cx, did, ItemType::Function); cx.with_param_env(did, |cx| { @@ -251,7 +255,7 @@ pub(crate) fn record_extern_fqn(cx: &mut DocContext<'_>, did: DefId, kind: ItemT } } -pub(crate) fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait { +pub(crate) fn build_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait { let trait_items = cx .tcx .associated_items(did) @@ -263,11 +267,18 @@ pub(crate) fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean let predicates = cx.tcx.predicates_of(did); let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates); let generics = filter_non_trait_generics(did, generics); - let (generics, supertrait_bounds) = separate_supertrait_bounds(generics); + let (generics, supertrait_bounds) = separate_self_bounds(generics); clean::Trait { def_id: did, generics, items: trait_items, bounds: supertrait_bounds } } -pub(crate) fn build_function(cx: &mut DocContext<'_>, def_id: DefId) -> Box { +fn build_trait_alias(cx: &mut DocContext<'_>, did: DefId) -> clean::TraitAlias { + let predicates = cx.tcx.predicates_of(did); + let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates); + let (generics, bounds) = separate_self_bounds(generics); + clean::TraitAlias { generics, bounds } +} + +pub(super) fn build_function(cx: &mut DocContext<'_>, def_id: DefId) -> Box { let sig = cx.tcx.fn_sig(def_id).instantiate_identity(); // The generics need to be cleaned before the signature. let mut generics = @@ -788,12 +799,7 @@ fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean: g } -/// Supertrait bounds for a trait are also listed in the generics coming from -/// the metadata for a crate, so we want to separate those out and create a new -/// list of explicit supertrait bounds to render nicely. -fn separate_supertrait_bounds( - mut g: clean::Generics, -) -> (clean::Generics, Vec) { +fn separate_self_bounds(mut g: clean::Generics) -> (clean::Generics, Vec) { let mut ty_bounds = Vec::new(); g.where_predicates.retain(|pred| match *pred { clean::WherePredicate::BoundPredicate { ty: clean::SelfTy, ref bounds, .. } => { @@ -806,22 +812,17 @@ fn separate_supertrait_bounds( } pub(crate) fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) { - if did.is_local() { - return; - } - + if did.is_local() + || cx.external_traits.contains_key(&did) + || cx.active_extern_traits.contains(&did) { - if cx.external_traits.contains_key(&did) || cx.active_extern_traits.contains(&did) { - return; - } + return; } - { - cx.active_extern_traits.insert(did); - } + cx.active_extern_traits.insert(did); debug!("record_extern_trait: {did:?}"); - let trait_ = build_external_trait(cx, did); + let trait_ = build_trait(cx, did); cx.external_traits.insert(did, trait_); cx.active_extern_traits.remove(&did); diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index c4dea79370d1f..41688b41c6e7f 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -27,7 +27,7 @@ use rustc_span::source_map; use rustc_span::symbol::sym; use tracing::{debug, info}; -use crate::clean::inline::build_external_trait; +use crate::clean::inline::build_trait; use crate::clean::{self, ItemId}; use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions}; use crate::formats::cache::Cache; @@ -385,7 +385,7 @@ pub(crate) fn run_global_ctxt( // // Note that in case of `#![no_core]`, the trait is not available. if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() { - let sized_trait = build_external_trait(&mut ctxt, sized_trait_did); + let sized_trait = build_trait(&mut ctxt, sized_trait_did); ctxt.external_traits.insert(sized_trait_did, sized_trait); } diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index 96847f13f655c..da33fedaa319f 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -1229,12 +1229,13 @@ fn item_trait_alias( wrap_item(w, |w| { write!( w, - "{attrs}trait {name}{generics}{where_b} = {bounds};", + "{attrs}trait {name}{generics} = {bounds}{where_clause};", attrs = render_attributes_in_pre(it, "", cx), name = it.name.unwrap(), generics = t.generics.print(cx), - where_b = print_where_clause(&t.generics, cx, 0, Ending::Newline).maybe_display(), bounds = bounds(&t.bounds, true, cx), + where_clause = + print_where_clause(&t.generics, cx, 0, Ending::NoNewline).maybe_display(), ) })?; diff --git a/tests/rustdoc/auxiliary/ext-trait-aliases.rs b/tests/rustdoc/auxiliary/ext-trait-aliases.rs new file mode 100644 index 0000000000000..8454c04063c12 --- /dev/null +++ b/tests/rustdoc/auxiliary/ext-trait-aliases.rs @@ -0,0 +1,13 @@ +#![feature(trait_alias)] + +pub trait ExtAlias0 = Copy + Iterator; + +pub trait ExtAlias1<'a, T: 'a + Clone, const N: usize> = From<[&'a T; N]>; + +pub trait ExtAlias2 = where T: From, String: Into; + +pub trait ExtAlias3 = Sized; + +pub trait ExtAlias4 = where Self: Sized; + +pub trait ExtAlias5 = ; diff --git a/tests/rustdoc/auxiliary/trait-alias-mention.rs b/tests/rustdoc/auxiliary/trait-alias-mention.rs deleted file mode 100644 index 6df06c87a09d5..0000000000000 --- a/tests/rustdoc/auxiliary/trait-alias-mention.rs +++ /dev/null @@ -1,3 +0,0 @@ -#![feature(trait_alias)] - -pub trait SomeAlias = std::fmt::Debug + std::marker::Copy; diff --git a/tests/rustdoc/trait-alias-mention.rs b/tests/rustdoc/trait-alias-mention.rs deleted file mode 100644 index b6ef926e644e5..0000000000000 --- a/tests/rustdoc/trait-alias-mention.rs +++ /dev/null @@ -1,10 +0,0 @@ -//@ aux-build:trait-alias-mention.rs -//@ build-aux-docs - -#![crate_name = "foo"] - -extern crate trait_alias_mention; - -//@ has foo/fn.mention_alias_in_bounds.html '//a[@href="../trait_alias_mention/traitalias.SomeAlias.html"]' 'SomeAlias' -pub fn mention_alias_in_bounds() { -} diff --git a/tests/rustdoc/trait-aliases.rs b/tests/rustdoc/trait-aliases.rs new file mode 100644 index 0000000000000..1be93f72042c2 --- /dev/null +++ b/tests/rustdoc/trait-aliases.rs @@ -0,0 +1,82 @@ +// Basic testing for trait aliases. +#![feature(trait_alias)] +#![crate_name = "it"] + +// Check the "local case" (HIR cleaning) // + +//@ has it/all.html '//a[@href="traitalias.Alias0.html"]' 'Alias0' +//@ has it/index.html '//h2[@id="trait-aliases"]' 'Trait Aliases' +//@ has it/index.html '//a[@class="traitalias"]' 'Alias0' +//@ has it/traitalias.Alias0.html +//@ has - '//*[@class="rust item-decl"]//code' 'trait Alias0 = Copy + Iterator;' +pub trait Alias0 = Copy + Iterator; + +//@ has it/traitalias.Alias1.html +//@ has - '//pre[@class="rust item-decl"]' \ +// "trait Alias1<'a, T: 'a + Clone, const N: usize> = From<[&'a T; N]>;" +pub trait Alias1<'a, T: 'a + Clone, const N: usize> = From<[&'a T; N]>; + +//@ has it/traitalias.Alias2.html +//@ has - '//pre[@class="rust item-decl"]' \ +// 'trait Alias2 = where T: From, String: Into;' +pub trait Alias2 = where T: From, String: Into; + +//@ has it/traitalias.Alias3.html +//@ has - '//pre[@class="rust item-decl"]' 'trait Alias3 = ;' +pub trait Alias3 =; + +//@ has it/traitalias.Alias4.html +//@ has - '//pre[@class="rust item-decl"]' 'trait Alias4 = ;' +pub trait Alias4 = where; + +//@ has it/fn.usage0.html +//@ has - '//pre[@class="rust item-decl"]' "pub fn usage0(_: impl Alias0)" +//@ has - '//a[@href="traitalias.Alias0.html"]' 'Alias0' +pub fn usage0(_: impl Alias0) {} + +// FIXME: One can only "disambiguate" intra-doc links to trait aliases with `type@` but not with +// `trait@` (fails to resolve) or `traitalias@` (doesn't exist). We should make at least one of +// the latter two work, right? + +//@ has it/link0/index.html +//@ has - '//a/@href' 'traitalias.Alias0.html' +//@ has - '//a/@href' 'traitalias.Alias1.html' +/// [Alias0], [type@Alias1] +pub mod link0 {} + +// Check the "extern case" (middle cleaning) // + +//@ aux-build: ext-trait-aliases.rs +extern crate ext_trait_aliases as ext; + +//@ has it/traitalias.ExtAlias0.html +//@ has - '//pre[@class="rust item-decl"]' 'trait ExtAlias0 = Copy + Iterator;' +pub use ext::ExtAlias0; + +//@ has it/traitalias.ExtAlias1.html +//@ has - '//pre[@class="rust item-decl"]' \ +// "trait ExtAlias1<'a, T, const N: usize> = From<[&'a T; N]> where T: 'a + Clone;" +pub use ext::ExtAlias1; + +//@ has it/traitalias.ExtAlias2.html +//@ has - '//pre[@class="rust item-decl"]' \ +// 'trait ExtAlias2 = where T: From, String: Into;' +pub use ext::ExtAlias2; + +//@ has it/traitalias.ExtAlias3.html +//@ has - '//pre[@class="rust item-decl"]' 'trait ExtAlias3 = Sized;' +pub use ext::ExtAlias3; + +// NOTE: Middle cleaning can't discern `= Sized` and `= where Self: Sized` and that's okay. +//@ has it/traitalias.ExtAlias4.html +//@ has - '//pre[@class="rust item-decl"]' 'trait ExtAlias4 = Sized;' +pub use ext::ExtAlias4; + +//@ has it/traitalias.ExtAlias5.html +//@ has - '//pre[@class="rust item-decl"]' 'trait ExtAlias5 = ;' +pub use ext::ExtAlias5; + +//@ has it/fn.usage1.html +//@ has - '//pre[@class="rust item-decl"]' "pub fn usage1(_: impl ExtAlias0)" +//@ has - '//a[@href="traitalias.ExtAlias0.html"]' 'ExtAlias0' +pub fn usage1(_: impl ExtAlias0) {} diff --git a/tests/rustdoc/trait_alias.rs b/tests/rustdoc/trait_alias.rs deleted file mode 100644 index bfdb9d40e2d2e..0000000000000 --- a/tests/rustdoc/trait_alias.rs +++ /dev/null @@ -1,26 +0,0 @@ -#![feature(trait_alias)] - -#![crate_name = "foo"] - -use std::fmt::Debug; - -//@ has foo/all.html '//a[@href="traitalias.CopyAlias.html"]' 'CopyAlias' -//@ has foo/all.html '//a[@href="traitalias.Alias2.html"]' 'Alias2' -//@ has foo/all.html '//a[@href="traitalias.Foo.html"]' 'Foo' - -//@ has foo/index.html '//h2[@id="trait-aliases"]' 'Trait Aliases' -//@ has foo/index.html '//a[@class="traitalias"]' 'CopyAlias' -//@ has foo/index.html '//a[@class="traitalias"]' 'Alias2' -//@ has foo/index.html '//a[@class="traitalias"]' 'Foo' - -//@ has foo/traitalias.CopyAlias.html -//@ has - '//section[@id="main-content"]/pre[@class="rust item-decl"]' 'trait CopyAlias = Copy;' -pub trait CopyAlias = Copy; -//@ has foo/traitalias.Alias2.html -//@ has - '//section[@id="main-content"]/pre[@class="rust item-decl"]' 'trait Alias2 = Copy + Debug;' -pub trait Alias2 = Copy + Debug; -//@ has foo/traitalias.Foo.html -//@ has - '//section[@id="main-content"]/pre[@class="rust item-decl"]' 'trait Foo = Into + Debug;' -pub trait Foo = Into + Debug; -//@ has foo/fn.bar.html '//a[@href="traitalias.Alias2.html"]' 'Alias2' -pub fn bar() where T: Alias2 {} From 01178849174bdff3e3e951827d9ea4884c23b758 Mon Sep 17 00:00:00 2001 From: Jake Goulding Date: Fri, 21 Mar 2025 10:09:17 -0400 Subject: [PATCH 184/266] Move eager translation to a method on `Diag` This will allow us to eagerly translate messages on a top-level diagnostic, such as a `LintDiagnostic`. As a bonus, we can remove the awkward closure passed into Subdiagnostic and make better use of `Into`. --- compiler/rustc_ast_passes/src/errors.rs | 14 +--- compiler/rustc_builtin_macros/src/errors.rs | 10 +-- compiler/rustc_const_eval/src/errors.rs | 10 +-- compiler/rustc_errors/src/diagnostic.rs | 33 ++++---- compiler/rustc_errors/src/diagnostic_impls.rs | 8 +- compiler/rustc_errors/src/lib.rs | 2 +- compiler/rustc_hir_typeck/src/errors.rs | 32 ++------ compiler/rustc_lint/src/errors.rs | 8 +- compiler/rustc_lint/src/if_let_rescope.rs | 12 +-- compiler/rustc_lint/src/lints.rs | 44 ++--------- .../src/diagnostics/subdiagnostic.rs | 15 +--- compiler/rustc_mir_build/src/errors.rs | 20 +---- .../src/lint_tail_expr_drop_order.rs | 16 ++-- compiler/rustc_parse/src/errors.rs | 9 +-- compiler/rustc_passes/src/errors.rs | 8 +- compiler/rustc_pattern_analysis/src/errors.rs | 14 +--- compiler/rustc_trait_selection/src/errors.rs | 78 ++++--------------- .../src/errors/note_and_explain.rs | 10 +-- .../ui-fulldeps/internal-lints/diagnostics.rs | 8 +- .../internal-lints/diagnostics.stderr | 18 ++--- 20 files changed, 98 insertions(+), 271 deletions(-) diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index 8e53e600f7ac6..bd139e2eb3f15 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -2,7 +2,7 @@ use rustc_ast::ParamKindOrd; use rustc_errors::codes::*; -use rustc_errors::{Applicability, Diag, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic}; +use rustc_errors::{Applicability, Diag, EmissionGuarantee, Subdiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Ident, Span, Symbol}; @@ -394,11 +394,7 @@ pub(crate) struct EmptyLabelManySpans(pub Vec); // The derive for `Vec` does multiple calls to `span_label`, adding commas between each impl Subdiagnostic for EmptyLabelManySpans { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.span_labels(self.0, ""); } } @@ -749,11 +745,7 @@ pub(crate) struct StableFeature { } impl Subdiagnostic for StableFeature { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.arg("name", self.name); diag.arg("since", self.since); diag.help(fluent::ast_passes_stable_since); diff --git a/compiler/rustc_builtin_macros/src/errors.rs b/compiler/rustc_builtin_macros/src/errors.rs index c2b1dff4cf1f7..d14ad8f40144c 100644 --- a/compiler/rustc_builtin_macros/src/errors.rs +++ b/compiler/rustc_builtin_macros/src/errors.rs @@ -1,7 +1,7 @@ use rustc_errors::codes::*; use rustc_errors::{ Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, MultiSpan, SingleLabelManySpans, - SubdiagMessageOp, Subdiagnostic, + Subdiagnostic, }; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Ident, Span, Symbol}; @@ -684,13 +684,9 @@ pub(crate) struct FormatUnusedArg { // Allow the singular form to be a subdiagnostic of the multiple-unused // form of diagnostic. impl Subdiagnostic for FormatUnusedArg { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.arg("named", self.named); - let msg = f(diag, crate::fluent_generated::builtin_macros_format_unused_arg.into()); + let msg = diag.eagerly_translate(crate::fluent_generated::builtin_macros_format_unused_arg); diag.span_label(self.span, msg); } } diff --git a/compiler/rustc_const_eval/src/errors.rs b/compiler/rustc_const_eval/src/errors.rs index e2675e2f4c900..6472aaa575812 100644 --- a/compiler/rustc_const_eval/src/errors.rs +++ b/compiler/rustc_const_eval/src/errors.rs @@ -6,7 +6,7 @@ use rustc_abi::WrappingRange; use rustc_errors::codes::*; use rustc_errors::{ Diag, DiagArgValue, DiagCtxtHandle, DiagMessage, Diagnostic, EmissionGuarantee, Level, - MultiSpan, SubdiagMessageOp, Subdiagnostic, + MultiSpan, Subdiagnostic, }; use rustc_hir::ConstContext; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; @@ -290,11 +290,7 @@ pub struct FrameNote { } impl Subdiagnostic for FrameNote { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.arg("times", self.times); diag.arg("where_", self.where_); diag.arg("instance", self.instance); @@ -302,7 +298,7 @@ impl Subdiagnostic for FrameNote { if self.has_label && !self.span.is_dummy() { span.push_span_label(self.span, fluent::const_eval_frame_note_last); } - let msg = f(diag, fluent::const_eval_frame_note.into()); + let msg = diag.eagerly_translate(fluent::const_eval_frame_note); diag.span_note(span, msg); } } diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index bd13c413a4df4..539ecfbb42e2c 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -181,22 +181,9 @@ where Self: Sized, { /// Add a subdiagnostic to an existing diagnostic. - fn add_to_diag(self, diag: &mut Diag<'_, G>) { - self.add_to_diag_with(diag, &|_, m| m); - } - - /// Add a subdiagnostic to an existing diagnostic where `f` is invoked on every message used - /// (to optionally perform eager translation). - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - f: &F, - ); + fn add_to_diag(self, diag: &mut Diag<'_, G>); } -pub trait SubdiagMessageOp = - Fn(&mut Diag<'_, G>, SubdiagMessage) -> SubdiagMessage; - /// Trait implemented by lint types. This should not be implemented manually. Instead, use /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic]. #[rustc_diagnostic_item = "LintDiagnostic"] @@ -1227,15 +1214,21 @@ impl<'a, G: EmissionGuarantee> Diag<'a, G> { /// interpolated variables). #[rustc_lint_diagnostics] pub fn subdiagnostic(&mut self, subdiagnostic: impl Subdiagnostic) -> &mut Self { - let dcx = self.dcx; - subdiagnostic.add_to_diag_with(self, &|diag, msg| { - let args = diag.args.iter(); - let msg = diag.subdiagnostic_message_to_diagnostic_message(msg); - dcx.eagerly_translate(msg, args) - }); + subdiagnostic.add_to_diag(self); self } + /// Fluent variables are not namespaced from each other, so when + /// `Diagnostic`s and `Subdiagnostic`s use the same variable name, + /// one value will clobber the other. Eagerly translating the + /// diagnostic uses the variables defined right then, before the + /// clobbering occurs. + pub fn eagerly_translate(&self, msg: impl Into) -> SubdiagMessage { + let args = self.args.iter(); + let msg = self.subdiagnostic_message_to_diagnostic_message(msg.into()); + self.dcx.eagerly_translate(msg, args) + } + with_fn! { with_span, /// Add a span. #[rustc_lint_diagnostics] diff --git a/compiler/rustc_errors/src/diagnostic_impls.rs b/compiler/rustc_errors/src/diagnostic_impls.rs index cb2e1769fa1cf..8b59ba9984c10 100644 --- a/compiler/rustc_errors/src/diagnostic_impls.rs +++ b/compiler/rustc_errors/src/diagnostic_impls.rs @@ -19,7 +19,7 @@ use {rustc_ast as ast, rustc_hir as hir}; use crate::diagnostic::DiagLocation; use crate::{ Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, ErrCode, IntoDiagArg, Level, - SubdiagMessageOp, Subdiagnostic, fluent_generated as fluent, + Subdiagnostic, fluent_generated as fluent, }; pub struct DiagArgFromDisplay<'a>(pub &'a dyn fmt::Display); @@ -384,11 +384,7 @@ pub struct SingleLabelManySpans { pub label: &'static str, } impl Subdiagnostic for SingleLabelManySpans { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.span_labels(self.spans, self.label); } } diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 75bb0e8e7b43f..c0c5dba46772a 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -47,7 +47,7 @@ pub use codes::*; pub use diagnostic::{ BugAbort, Diag, DiagArg, DiagArgMap, DiagArgName, DiagArgValue, DiagInner, DiagStyledString, Diagnostic, EmissionGuarantee, FatalAbort, IntoDiagArg, LintDiagnostic, StringPart, Subdiag, - SubdiagMessageOp, Subdiagnostic, + Subdiagnostic, }; pub use diagnostic_impls::{ DiagArgFromDisplay, DiagSymbolList, ElidedLifetimeInPathSubdiag, ExpectedLifetimeParameter, diff --git a/compiler/rustc_hir_typeck/src/errors.rs b/compiler/rustc_hir_typeck/src/errors.rs index dfaa374592bc2..9e7305430e5f5 100644 --- a/compiler/rustc_hir_typeck/src/errors.rs +++ b/compiler/rustc_hir_typeck/src/errors.rs @@ -5,7 +5,7 @@ use std::borrow::Cow; use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, DiagArgValue, DiagSymbolList, EmissionGuarantee, IntoDiagArg, MultiSpan, - SubdiagMessageOp, Subdiagnostic, + Subdiagnostic, }; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::{self, Ty}; @@ -270,11 +270,7 @@ pub(crate) struct SuggestAnnotations { pub suggestions: Vec, } impl Subdiagnostic for SuggestAnnotations { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { if self.suggestions.is_empty() { return; } @@ -337,11 +333,7 @@ pub(crate) struct TypeMismatchFruTypo { } impl Subdiagnostic for TypeMismatchFruTypo { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.arg("expr", self.expr.as_deref().unwrap_or("NONE")); // Only explain that `a ..b` is a range if it's split up @@ -599,11 +591,7 @@ pub(crate) struct RemoveSemiForCoerce { } impl Subdiagnostic for RemoveSemiForCoerce { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { let mut multispan: MultiSpan = self.semi.into(); multispan.push_span_label(self.expr, fluent::hir_typeck_remove_semi_for_coerce_expr); multispan.push_span_label(self.ret, fluent::hir_typeck_remove_semi_for_coerce_ret); @@ -778,20 +766,16 @@ pub(crate) enum CastUnknownPointerSub { } impl rustc_errors::Subdiagnostic for CastUnknownPointerSub { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { match self { CastUnknownPointerSub::To(span) => { - let msg = f(diag, crate::fluent_generated::hir_typeck_label_to); + let msg = diag.eagerly_translate(fluent::hir_typeck_label_to); diag.span_label(span, msg); - let msg = f(diag, crate::fluent_generated::hir_typeck_note); + let msg = diag.eagerly_translate(fluent::hir_typeck_note); diag.note(msg); } CastUnknownPointerSub::From(span) => { - let msg = f(diag, crate::fluent_generated::hir_typeck_label_from); + let msg = diag.eagerly_translate(fluent::hir_typeck_label_from); diag.span_label(span, msg); } } diff --git a/compiler/rustc_lint/src/errors.rs b/compiler/rustc_lint/src/errors.rs index d109a5c90305e..586e55c8055c9 100644 --- a/compiler/rustc_lint/src/errors.rs +++ b/compiler/rustc_lint/src/errors.rs @@ -1,5 +1,5 @@ use rustc_errors::codes::*; -use rustc_errors::{Diag, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic}; +use rustc_errors::{Diag, EmissionGuarantee, Subdiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_session::lint::Level; use rustc_span::{Span, Symbol}; @@ -26,11 +26,7 @@ pub(crate) enum OverruledAttributeSub { } impl Subdiagnostic for OverruledAttributeSub { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { match self { OverruledAttributeSub::DefaultSource { id } => { diag.note(fluent::lint_default_source); diff --git a/compiler/rustc_lint/src/if_let_rescope.rs b/compiler/rustc_lint/src/if_let_rescope.rs index 39ea8d8e3246c..a9b04511c6b47 100644 --- a/compiler/rustc_lint/src/if_let_rescope.rs +++ b/compiler/rustc_lint/src/if_let_rescope.rs @@ -3,9 +3,7 @@ use std::ops::ControlFlow; use hir::intravisit::{self, Visitor}; use rustc_ast::Recovered; -use rustc_errors::{ - Applicability, Diag, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic, SuggestionStyle, -}; +use rustc_errors::{Applicability, Diag, EmissionGuarantee, Subdiagnostic, SuggestionStyle}; use rustc_hir::{self as hir, HirIdSet}; use rustc_macros::{LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::adjustment::Adjust; @@ -327,11 +325,7 @@ struct IfLetRescopeRewrite { } impl Subdiagnostic for IfLetRescopeRewrite { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { let mut suggestions = vec![]; for match_head in self.match_heads { match match_head { @@ -360,7 +354,7 @@ impl Subdiagnostic for IfLetRescopeRewrite { .chain(repeat('}').take(closing_brackets.count)) .collect(), )); - let msg = f(diag, crate::fluent_generated::lint_suggestion); + let msg = diag.eagerly_translate(crate::fluent_generated::lint_suggestion); diag.multipart_suggestion_with_style( msg, suggestions, diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index 51214c8e8a4cf..8ab64fbd127af 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -6,7 +6,7 @@ use rustc_abi::ExternAbi; use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, DiagArgValue, DiagMessage, DiagStyledString, ElidedLifetimeInPathSubdiag, - EmissionGuarantee, LintDiagnostic, MultiSpan, SubdiagMessageOp, Subdiagnostic, SuggestionStyle, + EmissionGuarantee, LintDiagnostic, MultiSpan, Subdiagnostic, SuggestionStyle, }; use rustc_hir::def::Namespace; use rustc_hir::def_id::DefId; @@ -449,11 +449,7 @@ pub(crate) struct BuiltinUnpermittedTypeInitSub { } impl Subdiagnostic for BuiltinUnpermittedTypeInitSub { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { let mut err = self.err; loop { if let Some(span) = err.span { @@ -504,11 +500,7 @@ pub(crate) struct BuiltinClashingExternSub<'a> { } impl Subdiagnostic for BuiltinClashingExternSub<'_> { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { let mut expected_str = DiagStyledString::new(); expected_str.push(self.expected.fn_sig(self.tcx).to_string(), false); let mut found_str = DiagStyledString::new(); @@ -824,11 +816,7 @@ pub(crate) struct HiddenUnicodeCodepointsDiagLabels { } impl Subdiagnostic for HiddenUnicodeCodepointsDiagLabels { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { for (c, span) in self.spans { diag.span_label(span, format!("{c:?}")); } @@ -842,11 +830,7 @@ pub(crate) enum HiddenUnicodeCodepointsDiagSub { // Used because of multiple multipart_suggestion and note impl Subdiagnostic for HiddenUnicodeCodepointsDiagSub { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { match self { HiddenUnicodeCodepointsDiagSub::Escape { spans } => { diag.multipart_suggestion_with_style( @@ -1015,11 +999,7 @@ pub(crate) struct NonBindingLetSub { } impl Subdiagnostic for NonBindingLetSub { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { let can_suggest_binding = self.drop_fn_start_end.is_some() || !self.is_assign_desugar; if can_suggest_binding { @@ -1303,11 +1283,7 @@ pub(crate) enum NonSnakeCaseDiagSub { } impl Subdiagnostic for NonSnakeCaseDiagSub { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { match self { NonSnakeCaseDiagSub::Label { span } => { diag.span_label(span, fluent::lint_label); @@ -1629,11 +1605,7 @@ pub(crate) enum OverflowingBinHexSign { } impl Subdiagnostic for OverflowingBinHexSign { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { match self { OverflowingBinHexSign::Positive => { diag.note(fluent::lint_positive_note); diff --git a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs index 909083d5e8652..bc9516b2e0c67 100644 --- a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs @@ -20,14 +20,12 @@ use crate::diagnostics::utils::{ /// The central struct for constructing the `add_to_diag` method from an annotated struct. pub(crate) struct SubdiagnosticDerive { diag: syn::Ident, - f: syn::Ident, } impl SubdiagnosticDerive { pub(crate) fn new() -> Self { let diag = format_ident!("diag"); - let f = format_ident!("f"); - Self { diag, f } + Self { diag } } pub(crate) fn into_tokens(self, mut structure: Structure<'_>) -> TokenStream { @@ -86,19 +84,16 @@ impl SubdiagnosticDerive { }; let diag = &self.diag; - let f = &self.f; // FIXME(edition_2024): Fix the `keyword_idents_2024` lint to not trigger here? #[allow(keyword_idents_2024)] let ret = structure.gen_impl(quote! { gen impl rustc_errors::Subdiagnostic for @Self { - fn add_to_diag_with<__G, __F>( + fn add_to_diag<__G>( self, #diag: &mut rustc_errors::Diag<'_, __G>, - #f: &__F ) where __G: rustc_errors::EmissionGuarantee, - __F: rustc_errors::SubdiagMessageOp<__G>, { #implementation } @@ -384,11 +379,10 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> { Ok(quote! {}) } "subdiagnostic" => { - let f = &self.parent.f; let diag = &self.parent.diag; let binding = &info.binding; self.has_subdiagnostic = true; - Ok(quote! { #binding.add_to_diag_with(#diag, #f); }) + Ok(quote! { #binding.add_to_diag(#diag); }) } _ => { let mut span_attrs = vec![]; @@ -531,12 +525,11 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> { let span_field = self.span_field.value_ref(); let diag = &self.parent.diag; - let f = &self.parent.f; let mut calls = TokenStream::new(); for (kind, slug, no_span) in kind_slugs { let message = format_ident!("__message"); calls.extend( - quote! { let #message = #f(#diag, crate::fluent_generated::#slug.into()); }, + quote! { let #message = #diag.eagerly_translate(crate::fluent_generated::#slug); }, ); let name = format_ident!( diff --git a/compiler/rustc_mir_build/src/errors.rs b/compiler/rustc_mir_build/src/errors.rs index 0e16f871b16f9..ae09db5023527 100644 --- a/compiler/rustc_mir_build/src/errors.rs +++ b/compiler/rustc_mir_build/src/errors.rs @@ -2,7 +2,7 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, - MultiSpan, SubdiagMessageOp, Subdiagnostic, pluralize, + MultiSpan, Subdiagnostic, pluralize, }; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::{self, Ty}; @@ -546,11 +546,7 @@ pub(crate) struct UnsafeNotInheritedLintNote { } impl Subdiagnostic for UnsafeNotInheritedLintNote { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.span_note(self.signature_span, fluent::mir_build_unsafe_fn_safe_body); let body_start = self.body_span.shrink_to_lo(); let body_end = self.body_span.shrink_to_hi(); @@ -1031,11 +1027,7 @@ pub(crate) struct Variant { } impl<'tcx> Subdiagnostic for AdtDefinedHere<'tcx> { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.arg("ty", self.ty); let mut spans = MultiSpan::from(self.adt_def_span); @@ -1117,11 +1109,7 @@ pub(crate) struct Rust2024IncompatiblePatSugg { } impl Subdiagnostic for Rust2024IncompatiblePatSugg { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { // Format and emit explanatory notes about default binding modes. Reversing the spans' order // means if we have nested spans, the innermost ones will be visited first. for (span, def_br_mutbl) in self.default_mode_labels.into_iter().rev() { diff --git a/compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs b/compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs index 29a9133abe93d..537f152938ef3 100644 --- a/compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs +++ b/compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs @@ -512,23 +512,17 @@ struct LocalLabel<'a> { /// A custom `Subdiagnostic` implementation so that the notes are delivered in a specific order impl Subdiagnostic for LocalLabel<'_> { - fn add_to_diag_with< - G: rustc_errors::EmissionGuarantee, - F: rustc_errors::SubdiagMessageOp, - >( - self, - diag: &mut rustc_errors::Diag<'_, G>, - f: &F, - ) { + fn add_to_diag(self, diag: &mut rustc_errors::Diag<'_, G>) { diag.arg("name", self.name); diag.arg("is_generated_name", self.is_generated_name); diag.arg("is_dropped_first_edition_2024", self.is_dropped_first_edition_2024); - let msg = f(diag, crate::fluent_generated::mir_transform_tail_expr_local.into()); + let msg = diag.eagerly_translate(crate::fluent_generated::mir_transform_tail_expr_local); diag.span_label(self.span, msg); for dtor in self.destructors { - dtor.add_to_diag_with(diag, f); + dtor.add_to_diag(diag); } - let msg = f(diag, crate::fluent_generated::mir_transform_label_local_epilogue); + let msg = + diag.eagerly_translate(crate::fluent_generated::mir_transform_label_local_epilogue); diag.span_label(self.span, msg); } } diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index dfdef018bc374..57534bc8c318d 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -7,8 +7,7 @@ use rustc_ast::util::parser::ExprPrecedence; use rustc_ast::{Path, Visibility}; use rustc_errors::codes::*; use rustc_errors::{ - Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, SubdiagMessageOp, - Subdiagnostic, + Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, Subdiagnostic, }; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_session::errors::ExprParenthesesNeeded; @@ -1551,11 +1550,7 @@ pub(crate) struct FnTraitMissingParen { } impl Subdiagnostic for FnTraitMissingParen { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.span_label(self.span, crate::fluent_generated::parse_fn_trait_missing_paren); diag.span_suggestion_short( self.span.shrink_to_hi(), diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 85eddafefcd56..995fc85676e84 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -5,7 +5,7 @@ use rustc_ast::Label; use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, DiagCtxtHandle, DiagSymbolList, Diagnostic, EmissionGuarantee, Level, - MultiSpan, SubdiagMessageOp, Subdiagnostic, + MultiSpan, Subdiagnostic, }; use rustc_hir::{self as hir, ExprKind, Target}; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; @@ -1852,11 +1852,7 @@ pub(crate) struct UnusedVariableStringInterp { } impl Subdiagnostic for UnusedVariableStringInterp { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.span_label(self.lit, crate::fluent_generated::passes_maybe_string_interpolation); diag.multipart_suggestion( crate::fluent_generated::passes_string_interpolation_only_works, diff --git a/compiler/rustc_pattern_analysis/src/errors.rs b/compiler/rustc_pattern_analysis/src/errors.rs index 1f7852e5190d2..e60930d6cd21c 100644 --- a/compiler/rustc_pattern_analysis/src/errors.rs +++ b/compiler/rustc_pattern_analysis/src/errors.rs @@ -1,4 +1,4 @@ -use rustc_errors::{Diag, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic}; +use rustc_errors::{Diag, EmissionGuarantee, Subdiagnostic}; use rustc_macros::{LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::Ty; use rustc_span::Span; @@ -55,11 +55,7 @@ pub struct Overlap { } impl Subdiagnostic for Overlap { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { let Overlap { span, range } = self; // FIXME(mejrs) unfortunately `#[derive(LintDiagnostic)]` @@ -103,11 +99,7 @@ pub struct GappedRange { } impl Subdiagnostic for GappedRange { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { let GappedRange { span, gap, first_range } = self; // FIXME(mejrs) unfortunately `#[derive(LintDiagnostic)]` diff --git a/compiler/rustc_trait_selection/src/errors.rs b/compiler/rustc_trait_selection/src/errors.rs index 4e5581fb1da0d..756d9a57b935c 100644 --- a/compiler/rustc_trait_selection/src/errors.rs +++ b/compiler/rustc_trait_selection/src/errors.rs @@ -4,7 +4,7 @@ use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, DiagCtxtHandle, DiagMessage, DiagStyledString, Diagnostic, - EmissionGuarantee, IntoDiagArg, Level, MultiSpan, SubdiagMessageOp, Subdiagnostic, + EmissionGuarantee, IntoDiagArg, Level, MultiSpan, Subdiagnostic, }; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; @@ -107,11 +107,7 @@ pub enum AdjustSignatureBorrow { } impl Subdiagnostic for AdjustSignatureBorrow { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { match self { AdjustSignatureBorrow::Borrow { to_borrow } => { diag.arg("len", to_borrow.len()); @@ -381,11 +377,7 @@ pub enum RegionOriginNote<'a> { } impl Subdiagnostic for RegionOriginNote<'_> { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { let mut label_or_note = |span, msg: DiagMessage| { let sub_count = diag.children.iter().filter(|d| d.span.is_dummy()).count(); let expanded_sub_count = diag.children.iter().filter(|d| !d.span.is_dummy()).count(); @@ -446,11 +438,7 @@ pub enum LifetimeMismatchLabels { } impl Subdiagnostic for LifetimeMismatchLabels { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { match self { LifetimeMismatchLabels::InRet { param_span, ret_span, span, label_var1 } => { diag.span_label(param_span, fluent::trait_selection_declared_different); @@ -495,11 +483,7 @@ pub struct AddLifetimeParamsSuggestion<'a> { } impl Subdiagnostic for AddLifetimeParamsSuggestion<'_> { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { let mut mk_suggestion = || { let Some(anon_reg) = self.tcx.is_suitable_region(self.generic_param_scope, self.sub) else { @@ -689,11 +673,7 @@ pub struct IntroducesStaticBecauseUnmetLifetimeReq { } impl Subdiagnostic for IntroducesStaticBecauseUnmetLifetimeReq { - fn add_to_diag_with>( - mut self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(mut self, diag: &mut Diag<'_, G>) { self.unmet_requirements .push_span_label(self.binding_span, fluent::trait_selection_msl_introduces_static); diag.span_note(self.unmet_requirements, fluent::trait_selection_msl_unmet_req); @@ -1008,17 +988,13 @@ pub struct ConsiderBorrowingParamHelp { } impl Subdiagnostic for ConsiderBorrowingParamHelp { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { let mut type_param_span: MultiSpan = self.spans.clone().into(); for &span in &self.spans { // Seems like we can't call f() here as Into is required type_param_span.push_span_label(span, fluent::trait_selection_tid_consider_borrowing); } - let msg = f(diag, fluent::trait_selection_tid_param_help.into()); + let msg = diag.eagerly_translate(fluent::trait_selection_tid_param_help); diag.span_help(type_param_span, msg); } } @@ -1053,18 +1029,14 @@ pub struct DynTraitConstraintSuggestion { } impl Subdiagnostic for DynTraitConstraintSuggestion { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { let mut multi_span: MultiSpan = vec![self.span].into(); multi_span.push_span_label(self.span, fluent::trait_selection_dtcs_has_lifetime_req_label); multi_span .push_span_label(self.ident.span, fluent::trait_selection_dtcs_introduces_requirement); - let msg = f(diag, fluent::trait_selection_dtcs_has_req_note.into()); + let msg = diag.eagerly_translate(fluent::trait_selection_dtcs_has_req_note); diag.span_note(multi_span, msg); - let msg = f(diag, fluent::trait_selection_dtcs_suggestion.into()); + let msg = diag.eagerly_translate(fluent::trait_selection_dtcs_suggestion); diag.span_suggestion_verbose( self.span.shrink_to_hi(), msg, @@ -1101,11 +1073,7 @@ pub struct ReqIntroducedLocations { } impl Subdiagnostic for ReqIntroducedLocations { - fn add_to_diag_with>( - mut self, - diag: &mut Diag<'_, G>, - f: &F, - ) { + fn add_to_diag(mut self, diag: &mut Diag<'_, G>) { for sp in self.spans { self.span.push_span_label(sp, fluent::trait_selection_ril_introduced_here); } @@ -1114,7 +1082,7 @@ impl Subdiagnostic for ReqIntroducedLocations { self.span.push_span_label(self.fn_decl_span, fluent::trait_selection_ril_introduced_by); } self.span.push_span_label(self.cause_span, fluent::trait_selection_ril_because_of); - let msg = f(diag, fluent::trait_selection_ril_static_introduced_by.into()); + let msg = diag.eagerly_translate(fluent::trait_selection_ril_static_introduced_by); diag.span_note(self.span, msg); } } @@ -1513,13 +1481,9 @@ pub struct SuggestTuplePatternMany { } impl Subdiagnostic for SuggestTuplePatternMany { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.arg("path", self.path); - let message = f(diag, crate::fluent_generated::trait_selection_stp_wrap_many.into()); + let message = diag.eagerly_translate(fluent::trait_selection_stp_wrap_many); diag.multipart_suggestions( message, self.compatible_variants.into_iter().map(|variant| { @@ -1752,11 +1716,7 @@ pub struct AddPreciseCapturingAndParams { } impl Subdiagnostic for AddPreciseCapturingAndParams { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.arg("new_lifetime", self.new_lifetime); diag.multipart_suggestion_verbose( fluent::trait_selection_precise_capturing_new_but_apit, @@ -1896,11 +1856,7 @@ pub struct AddPreciseCapturingForOvercapture { } impl Subdiagnostic for AddPreciseCapturingForOvercapture { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { let applicability = if self.apit_spans.is_empty() { Applicability::MachineApplicable } else { diff --git a/compiler/rustc_trait_selection/src/errors/note_and_explain.rs b/compiler/rustc_trait_selection/src/errors/note_and_explain.rs index e4ab78b62477f..84e7686fdd3fc 100644 --- a/compiler/rustc_trait_selection/src/errors/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/errors/note_and_explain.rs @@ -1,4 +1,4 @@ -use rustc_errors::{Diag, EmissionGuarantee, IntoDiagArg, SubdiagMessageOp, Subdiagnostic}; +use rustc_errors::{Diag, EmissionGuarantee, IntoDiagArg, Subdiagnostic}; use rustc_hir::def_id::LocalDefId; use rustc_middle::bug; use rustc_middle::ty::{self, TyCtxt}; @@ -162,17 +162,13 @@ impl RegionExplanation<'_> { } impl Subdiagnostic for RegionExplanation<'_> { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - f: &F, - ) { + fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.arg("pref_kind", self.prefix); diag.arg("suff_kind", self.suffix); diag.arg("desc_kind", self.desc.kind); diag.arg("desc_arg", self.desc.arg); - let msg = f(diag, fluent::trait_selection_region_explanation.into()); + let msg = diag.eagerly_translate(fluent::trait_selection_region_explanation); if let Some(span) = self.desc.span { diag.span_note(span, msg); } else { diff --git a/tests/ui-fulldeps/internal-lints/diagnostics.rs b/tests/ui-fulldeps/internal-lints/diagnostics.rs index 442f9d72c3f19..1238fefd5bc03 100644 --- a/tests/ui-fulldeps/internal-lints/diagnostics.rs +++ b/tests/ui-fulldeps/internal-lints/diagnostics.rs @@ -15,7 +15,7 @@ extern crate rustc_span; use rustc_errors::{ Diag, DiagCtxtHandle, DiagInner, DiagMessage, Diagnostic, EmissionGuarantee, Level, - LintDiagnostic, SubdiagMessage, SubdiagMessageOp, Subdiagnostic, + LintDiagnostic, SubdiagMessage, Subdiagnostic, }; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::Span; @@ -56,10 +56,9 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for TranslatableInDiagnostic { pub struct UntranslatableInAddtoDiag; impl Subdiagnostic for UntranslatableInAddtoDiag { - fn add_to_diag_with>( + fn add_to_diag( self, diag: &mut Diag<'_, G>, - f: &F, ) { diag.note("untranslatable diagnostic"); //~^ ERROR diagnostics should be created using translatable messages @@ -69,10 +68,9 @@ impl Subdiagnostic for UntranslatableInAddtoDiag { pub struct TranslatableInAddtoDiag; impl Subdiagnostic for TranslatableInAddtoDiag { - fn add_to_diag_with>( + fn add_to_diag( self, diag: &mut Diag<'_, G>, - f: &F, ) { diag.note(crate::fluent_generated::no_crate_note); } diff --git a/tests/ui-fulldeps/internal-lints/diagnostics.stderr b/tests/ui-fulldeps/internal-lints/diagnostics.stderr index 36dd3cf4be798..b260c4b7afefb 100644 --- a/tests/ui-fulldeps/internal-lints/diagnostics.stderr +++ b/tests/ui-fulldeps/internal-lints/diagnostics.stderr @@ -11,19 +11,19 @@ LL | #![deny(rustc::untranslatable_diagnostic)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostics should be created using translatable messages - --> $DIR/diagnostics.rs:64:19 + --> $DIR/diagnostics.rs:63:19 | LL | diag.note("untranslatable diagnostic"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostics should be created using translatable messages - --> $DIR/diagnostics.rs:85:19 + --> $DIR/diagnostics.rs:83:19 | LL | diag.note("untranslatable diagnostic"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostics should only be created in `Diagnostic`/`Subdiagnostic`/`LintDiagnostic` impls - --> $DIR/diagnostics.rs:99:21 + --> $DIR/diagnostics.rs:97:21 | LL | let _diag = dcx.struct_err(crate::fluent_generated::no_crate_example); | ^^^^^^^^^^ @@ -35,37 +35,37 @@ LL | #![deny(rustc::diagnostic_outside_of_impl)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostics should only be created in `Diagnostic`/`Subdiagnostic`/`LintDiagnostic` impls - --> $DIR/diagnostics.rs:102:21 + --> $DIR/diagnostics.rs:100:21 | LL | let _diag = dcx.struct_err("untranslatable diagnostic"); | ^^^^^^^^^^ error: diagnostics should be created using translatable messages - --> $DIR/diagnostics.rs:102:32 + --> $DIR/diagnostics.rs:100:32 | LL | let _diag = dcx.struct_err("untranslatable diagnostic"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostics should be created using translatable messages - --> $DIR/diagnostics.rs:120:7 + --> $DIR/diagnostics.rs:118:7 | LL | f("untranslatable diagnostic", crate::fluent_generated::no_crate_example); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostics should be created using translatable messages - --> $DIR/diagnostics.rs:122:50 + --> $DIR/diagnostics.rs:120:50 | LL | f(crate::fluent_generated::no_crate_example, "untranslatable diagnostic"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostics should be created using translatable messages - --> $DIR/diagnostics.rs:124:7 + --> $DIR/diagnostics.rs:122:7 | LL | f("untranslatable diagnostic", "untranslatable diagnostic"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostics should be created using translatable messages - --> $DIR/diagnostics.rs:124:36 + --> $DIR/diagnostics.rs:122:36 | LL | f("untranslatable diagnostic", "untranslatable diagnostic"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ From 675360ae4e79b515a6645f98d7998507ad215164 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 22 Oct 2024 12:08:30 +1100 Subject: [PATCH 185/266] Remove some unnecessary lifetimes. `FlowSensitiveAnalysis` is only instantiated with the first two lifetimes being the same. --- .../src/check_consts/check.rs | 2 +- .../src/check_consts/resolver.rs | 24 +++++++++---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 2b74c849f1ae2..b600b8918dd01 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -34,7 +34,7 @@ use crate::check_consts::is_fn_or_trait_safe_to_expose_on_stable; use crate::errors; type QualifResults<'mir, 'tcx, Q> = - rustc_mir_dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'mir, 'mir, 'tcx, Q>>; + rustc_mir_dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'mir, 'tcx, Q>>; #[derive(Copy, Clone, PartialEq, Eq, Debug)] enum ConstConditionsHold { diff --git a/compiler/rustc_const_eval/src/check_consts/resolver.rs b/compiler/rustc_const_eval/src/check_consts/resolver.rs index 8cee282311f03..9f7fcc509a587 100644 --- a/compiler/rustc_const_eval/src/check_consts/resolver.rs +++ b/compiler/rustc_const_eval/src/check_consts/resolver.rs @@ -22,17 +22,17 @@ use super::{ConstCx, Qualif, qualifs}; /// qualified immediately after it is borrowed or its address escapes. The borrow must allow for /// mutation, which includes shared borrows of places with interior mutability. The type of /// borrowed place must contain the qualif. -struct TransferFunction<'a, 'mir, 'tcx, Q> { - ccx: &'a ConstCx<'mir, 'tcx>, - state: &'a mut State, +struct TransferFunction<'mir, 'tcx, Q> { + ccx: &'mir ConstCx<'mir, 'tcx>, + state: &'mir mut State, _qualif: PhantomData, } -impl<'a, 'mir, 'tcx, Q> TransferFunction<'a, 'mir, 'tcx, Q> +impl<'mir, 'tcx, Q> TransferFunction<'mir, 'tcx, Q> where Q: Qualif, { - fn new(ccx: &'a ConstCx<'mir, 'tcx>, state: &'a mut State) -> Self { + fn new(ccx: &'mir ConstCx<'mir, 'tcx>, state: &'mir mut State) -> Self { TransferFunction { ccx, state, _qualif: PhantomData } } @@ -124,7 +124,7 @@ where } } -impl<'tcx, Q> Visitor<'tcx> for TransferFunction<'_, '_, 'tcx, Q> +impl<'tcx, Q> Visitor<'tcx> for TransferFunction<'_, 'tcx, Q> where Q: Qualif, { @@ -228,20 +228,20 @@ where } /// The dataflow analysis used to propagate qualifs on arbitrary CFGs. -pub(super) struct FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q> { - ccx: &'a ConstCx<'mir, 'tcx>, +pub(super) struct FlowSensitiveAnalysis<'mir, 'tcx, Q> { + ccx: &'mir ConstCx<'mir, 'tcx>, _qualif: PhantomData, } -impl<'a, 'mir, 'tcx, Q> FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q> +impl<'mir, 'tcx, Q> FlowSensitiveAnalysis<'mir, 'tcx, Q> where Q: Qualif, { - pub(super) fn new(_: Q, ccx: &'a ConstCx<'mir, 'tcx>) -> Self { + pub(super) fn new(_: Q, ccx: &'mir ConstCx<'mir, 'tcx>) -> Self { FlowSensitiveAnalysis { ccx, _qualif: PhantomData } } - fn transfer_function(&self, state: &'a mut State) -> TransferFunction<'a, 'mir, 'tcx, Q> { + fn transfer_function(&self, state: &'mir mut State) -> TransferFunction<'mir, 'tcx, Q> { TransferFunction::::new(self.ccx, state) } } @@ -313,7 +313,7 @@ impl JoinSemiLattice for State { } } -impl<'tcx, Q> Analysis<'tcx> for FlowSensitiveAnalysis<'_, '_, 'tcx, Q> +impl<'tcx, Q> Analysis<'tcx> for FlowSensitiveAnalysis<'_, 'tcx, Q> where Q: Qualif, { From 99a60eb97f49bb63cb89f865ff1edd26decd7165 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 22 Oct 2024 13:41:09 +1100 Subject: [PATCH 186/266] `intern_with_temp_alloc` is for `DummyMachine` only. --- compiler/rustc_const_eval/src/interpret/intern.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_const_eval/src/interpret/intern.rs b/compiler/rustc_const_eval/src/interpret/intern.rs index e4b2fe5d153e1..8f0cb197c4455 100644 --- a/compiler/rustc_const_eval/src/interpret/intern.rs +++ b/compiler/rustc_const_eval/src/interpret/intern.rs @@ -30,6 +30,7 @@ use super::{ AllocId, Allocation, InterpCx, MPlaceTy, Machine, MemoryKind, PlaceTy, err_ub, interp_ok, }; use crate::const_eval; +use crate::const_eval::DummyMachine; use crate::errors::NestedStaticInThreadLocal; pub trait CompileTimeMachine<'tcx, T> = Machine< @@ -323,14 +324,17 @@ pub fn intern_const_alloc_for_constprop<'tcx, T, M: CompileTimeMachine<'tcx, T>> interp_ok(()) } -impl<'tcx, M: super::intern::CompileTimeMachine<'tcx, !>> InterpCx<'tcx, M> { +impl<'tcx> InterpCx<'tcx, DummyMachine> { /// A helper function that allocates memory for the layout given and gives you access to mutate /// it. Once your own mutation code is done, the backing `Allocation` is removed from the /// current `Memory` and interned as read-only into the global memory. pub fn intern_with_temp_alloc( &mut self, layout: TyAndLayout<'tcx>, - f: impl FnOnce(&mut InterpCx<'tcx, M>, &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx, ()>, + f: impl FnOnce( + &mut InterpCx<'tcx, DummyMachine>, + &PlaceTy<'tcx, CtfeProvenance>, + ) -> InterpResult<'tcx, ()>, ) -> InterpResult<'tcx, AllocId> { // `allocate` picks a fresh AllocId that we will associate with its data below. let dest = self.allocate(layout, MemoryKind::Stack)?; From 5636312c71e3e4eb7f1afc3e945bd7dc11697d4c Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Thu, 17 Apr 2025 11:50:24 +0800 Subject: [PATCH 187/266] git: ignore `60600a6fa403216bfd66e04f948b1822f6450af7` for blame purposes It was simply breaking up compiletest's `runtest.rs` and isn't very useful in git blame. --- .git-blame-ignore-revs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index d2a017bd2a023..af071c706856e 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -31,3 +31,5 @@ ec2cc761bc7067712ecc7734502f703fe3b024c8 c682aa162b0d41e21cc6748f4fecfe01efb69d1f # reformat with updated edition 2024 1fcae03369abb4c2cc180cd5a49e1f4440a81300 +# Breaking up of compiletest runtest.rs +60600a6fa403216bfd66e04f948b1822f6450af7 From 5a38550a39a99b1cd98f9be769e4f1face3d1256 Mon Sep 17 00:00:00 2001 From: Ross Smyth <18294397+RossSmyth@users.noreply.github.com> Date: Wed, 2 Apr 2025 20:33:37 -0400 Subject: [PATCH 188/266] Deduplicate nix code And clean it up a little. --- src/tools/nix-dev-shell/flake.nix | 46 +++++++--------- src/tools/nix-dev-shell/shell.nix | 38 +++++++------ src/tools/nix-dev-shell/x/default.nix | 77 ++++++++++++++++++++++++--- 3 files changed, 111 insertions(+), 50 deletions(-) diff --git a/src/tools/nix-dev-shell/flake.nix b/src/tools/nix-dev-shell/flake.nix index 1b838bd2f7b37..b8287de5fcf09 100644 --- a/src/tools/nix-dev-shell/flake.nix +++ b/src/tools/nix-dev-shell/flake.nix @@ -1,32 +1,24 @@ { description = "rustc dev shell"; - inputs = { - nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; - flake-utils.url = "github:numtide/flake-utils"; - }; + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; - outputs = { self, nixpkgs, flake-utils, ... }: - flake-utils.lib.eachDefaultSystem (system: - let - pkgs = import nixpkgs { inherit system; }; - x = import ./x { inherit pkgs; }; - in - { - devShells.default = with pkgs; mkShell { - name = "rustc-dev-shell"; - nativeBuildInputs = with pkgs; [ - binutils cmake ninja pkg-config python3 git curl cacert patchelf nix - ]; - buildInputs = with pkgs; [ - openssl glibc.out glibc.static x - ]; - # Avoid creating text files for ICEs. - RUSTC_ICE = "0"; - # Provide `libstdc++.so.6` for the self-contained lld. - # Provide `libz.so.1`. - LD_LIBRARY_PATH = "${with pkgs; lib.makeLibraryPath [stdenv.cc.cc.lib zlib]}"; - }; - } - ); + outputs = + { + self, + nixpkgs, + }: + let + inherit (nixpkgs) lib; + forEachSystem = lib.genAttrs lib.systems.flakeExposed; + in + { + devShells = forEachSystem (system: { + default = nixpkgs.legacyPackages.${system}.callPackage ./shell.nix { }; + }); + + packages = forEachSystem (system: { + default = nixpkgs.legacyPackages.${system}.callPackage ./x { }; + }); + }; } diff --git a/src/tools/nix-dev-shell/shell.nix b/src/tools/nix-dev-shell/shell.nix index a3f5969bd812d..0adbacf7e8d56 100644 --- a/src/tools/nix-dev-shell/shell.nix +++ b/src/tools/nix-dev-shell/shell.nix @@ -1,18 +1,26 @@ -{ pkgs ? import {} }: -let - x = import ./x { inherit pkgs; }; +{ + pkgs ? import { }, +}: +let + inherit (pkgs.lib) lists attrsets; + + x = pkgs.callPackage ./x { }; + inherit (x.passthru) cacert env; in pkgs.mkShell { - name = "rustc"; - nativeBuildInputs = with pkgs; [ - binutils cmake ninja pkg-config python3 git curl cacert patchelf nix - ]; - buildInputs = with pkgs; [ - openssl glibc.out glibc.static x - ]; - # Avoid creating text files for ICEs. - RUSTC_ICE = "0"; - # Provide `libstdc++.so.6` for the self-contained lld. - # Provide `libz.so.1` - LD_LIBRARY_PATH = "${with pkgs; lib.makeLibraryPath [stdenv.cc.cc.lib zlib]}"; + name = "rustc-shell"; + + inputsFrom = [ x ]; + packages = [ + pkgs.git + pkgs.nix + x + # Get the runtime deps of the x wrapper + ] ++ lists.flatten (attrsets.attrValues env); + + env = { + # Avoid creating text files for ICEs. + RUSTC_ICE = 0; + SSL_CERT_FILE = cacert; + }; } diff --git a/src/tools/nix-dev-shell/x/default.nix b/src/tools/nix-dev-shell/x/default.nix index e6dfbad6f19c8..422c1c4a2aed8 100644 --- a/src/tools/nix-dev-shell/x/default.nix +++ b/src/tools/nix-dev-shell/x/default.nix @@ -1,22 +1,83 @@ { - pkgs ? import { }, + pkgs, + lib, + stdenv, + rustc, + python3, + makeBinaryWrapper, + # Bootstrap + curl, + pkg-config, + libiconv, + openssl, + patchelf, + cacert, + zlib, + # LLVM Deps + ninja, + cmake, + glibc, }: -pkgs.stdenv.mkDerivation { - name = "x"; +stdenv.mkDerivation (self: { + strictDeps = true; + name = "x-none"; + + outputs = [ + "out" + "unwrapped" + ]; src = ./x.rs; dontUnpack = true; - nativeBuildInputs = with pkgs; [ rustc ]; + nativeBuildInputs = [ + rustc + makeBinaryWrapper + ]; + env.PYTHON = python3.interpreter; buildPhase = '' - PYTHON=${pkgs.lib.getExe pkgs.python3} rustc -Copt-level=3 --crate-name x $src --out-dir $out/bin + rustc -Copt-level=3 --crate-name x $src --out-dir $unwrapped/bin ''; - meta = with pkgs.lib; { + installPhase = + let + inherit (self.passthru) cacert env; + in + '' + makeWrapper $unwrapped/bin/x $out/bin/x \ + --set-default SSL_CERT_FILE ${cacert} \ + --prefix CPATH ";" "${lib.makeSearchPath "include" env.cpath}" \ + --prefix PATH : ${lib.makeBinPath env.path} \ + --prefix LD_LIBRARY_PATH : ${lib.makeLibraryPath env.ldLib} + ''; + + # For accessing them in the devshell + passthru = { + env = { + cpath = [ libiconv ]; + path = [ + python3 + patchelf + curl + pkg-config + cmake + ninja + stdenv.cc + ]; + ldLib = [ + openssl + zlib + stdenv.cc.cc.lib + ]; + }; + cacert = "${cacert}/etc/ssl/certs/ca-bundle.crt"; + }; + + meta = { description = "Helper for rust-lang/rust x.py"; homepage = "https://github.com/rust-lang/rust/blob/master/src/tools/x"; - license = licenses.mit; + license = lib.licenses.mit; mainProgram = "x"; }; -} +}) From 62146748d8b422fcbeb4b0c6e02a8e7a576f4909 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Tue, 15 Apr 2025 20:15:54 +0200 Subject: [PATCH 189/266] rustdoc/clean: Change terminology of items pertaining to (formal) fn params from "argument" to "parameter" --- src/librustdoc/clean/mod.rs | 150 +++++++++------------ src/librustdoc/clean/types.rs | 16 +-- src/librustdoc/html/format.rs | 54 ++++---- src/librustdoc/html/render/search_index.rs | 12 +- src/librustdoc/json/conversions.rs | 9 +- 5 files changed, 107 insertions(+), 134 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index fe9dc9a9e2145..249a822076ecd 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1052,7 +1052,7 @@ fn clean_fn_or_proc_macro<'tcx>( match macro_kind { Some(kind) => clean_proc_macro(item, name, kind, cx), None => { - let mut func = clean_function(cx, sig, generics, FunctionArgs::Body(body_id)); + let mut func = clean_function(cx, sig, generics, ParamsSrc::Body(body_id)); clean_fn_decl_legacy_const_generics(&mut func, attrs); FunctionItem(func) } @@ -1071,16 +1071,11 @@ fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[hir::Attrib for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.lit()).enumerate() { match literal.kind { ast::LitKind::Int(a, _) => { - let param = func.generics.params.remove(0); - if let GenericParamDef { - name, - kind: GenericParamDefKind::Const { ty, .. }, - .. - } = param - { - func.decl.inputs.values.insert( + let GenericParamDef { name, kind, .. } = func.generics.params.remove(0); + if let GenericParamDefKind::Const { ty, .. } = kind { + func.decl.inputs.insert( a.get() as _, - Argument { name: Some(name), type_: *ty, is_const: true }, + Parameter { name: Some(name), type_: *ty, is_const: true }, ); } else { panic!("unexpected non const in position {pos}"); @@ -1092,7 +1087,7 @@ fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[hir::Attrib } } -enum FunctionArgs<'tcx> { +enum ParamsSrc<'tcx> { Body(hir::BodyId), Idents(&'tcx [Option]), } @@ -1101,30 +1096,26 @@ fn clean_function<'tcx>( cx: &mut DocContext<'tcx>, sig: &hir::FnSig<'tcx>, generics: &hir::Generics<'tcx>, - args: FunctionArgs<'tcx>, + params: ParamsSrc<'tcx>, ) -> Box { let (generics, decl) = enter_impl_trait(cx, |cx| { - // NOTE: generics must be cleaned before args + // NOTE: Generics must be cleaned before params. let generics = clean_generics(generics, cx); - let args = match args { - FunctionArgs::Body(body_id) => { - clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id) - } - FunctionArgs::Idents(idents) => { - clean_args_from_types_and_names(cx, sig.decl.inputs, idents) - } + let params = match params { + ParamsSrc::Body(body_id) => clean_params_via_body(cx, sig.decl.inputs, body_id), + ParamsSrc::Idents(idents) => clean_params(cx, sig.decl.inputs, idents), }; - let decl = clean_fn_decl_with_args(cx, sig.decl, Some(&sig.header), args); + let decl = clean_fn_decl_with_params(cx, sig.decl, Some(&sig.header), params); (generics, decl) }); Box::new(Function { decl, generics }) } -fn clean_args_from_types_and_names<'tcx>( +fn clean_params<'tcx>( cx: &mut DocContext<'tcx>, types: &[hir::Ty<'tcx>], idents: &[Option], -) -> Arguments { +) -> Vec { fn nonempty_name(ident: &Option) -> Option { if let Some(ident) = ident && ident.name != kw::Underscore @@ -1143,44 +1134,38 @@ fn clean_args_from_types_and_names<'tcx>( None }; - Arguments { - values: types - .iter() - .enumerate() - .map(|(i, ty)| Argument { - type_: clean_ty(ty, cx), - name: idents.get(i).and_then(nonempty_name).or(default_name), - is_const: false, - }) - .collect(), - } + types + .iter() + .enumerate() + .map(|(i, ty)| Parameter { + name: idents.get(i).and_then(nonempty_name).or(default_name), + type_: clean_ty(ty, cx), + is_const: false, + }) + .collect() } -fn clean_args_from_types_and_body_id<'tcx>( +fn clean_params_via_body<'tcx>( cx: &mut DocContext<'tcx>, types: &[hir::Ty<'tcx>], body_id: hir::BodyId, -) -> Arguments { - let body = cx.tcx.hir_body(body_id); - - Arguments { - values: types - .iter() - .zip(body.params) - .map(|(ty, param)| Argument { - name: Some(name_from_pat(param.pat)), - type_: clean_ty(ty, cx), - is_const: false, - }) - .collect(), - } +) -> Vec { + types + .iter() + .zip(cx.tcx.hir_body(body_id).params) + .map(|(ty, param)| Parameter { + name: Some(name_from_pat(param.pat)), + type_: clean_ty(ty, cx), + is_const: false, + }) + .collect() } -fn clean_fn_decl_with_args<'tcx>( +fn clean_fn_decl_with_params<'tcx>( cx: &mut DocContext<'tcx>, decl: &hir::FnDecl<'tcx>, header: Option<&hir::FnHeader>, - args: Arguments, + params: Vec, ) -> FnDecl { let mut output = match decl.output { hir::FnRetTy::Return(typ) => clean_ty(typ, cx), @@ -1191,7 +1176,7 @@ fn clean_fn_decl_with_args<'tcx>( { output = output.sugared_async_return_type(); } - FnDecl { inputs: args, output, c_variadic: decl.c_variadic } + FnDecl { inputs: params, output, c_variadic: decl.c_variadic } } fn clean_poly_fn_sig<'tcx>( @@ -1201,8 +1186,6 @@ fn clean_poly_fn_sig<'tcx>( ) -> FnDecl { let mut names = did.map_or(&[] as &[_], |did| cx.tcx.fn_arg_idents(did)).iter(); - // We assume all empty tuples are default return type. This theoretically can discard `-> ()`, - // but shouldn't change any code meaning. let mut output = clean_middle_ty(sig.output(), cx, None, None); // If the return type isn't an `impl Trait`, we can safely assume that this @@ -1215,25 +1198,21 @@ fn clean_poly_fn_sig<'tcx>( output = output.sugared_async_return_type(); } - FnDecl { - output, - c_variadic: sig.skip_binder().c_variadic, - inputs: Arguments { - values: sig - .inputs() - .iter() - .map(|t| Argument { - type_: clean_middle_ty(t.map_bound(|t| *t), cx, None, None), - name: Some(if let Some(Some(ident)) = names.next() { - ident.name - } else { - kw::Underscore - }), - is_const: false, - }) - .collect(), - }, - } + let params = sig + .inputs() + .iter() + .map(|t| Parameter { + type_: clean_middle_ty(t.map_bound(|t| *t), cx, None, None), + name: Some(if let Some(Some(ident)) = names.next() { + ident.name + } else { + kw::Underscore + }), + is_const: false, + }) + .collect(); + + FnDecl { inputs: params, output, c_variadic: sig.skip_binder().c_variadic } } fn clean_trait_ref<'tcx>(trait_ref: &hir::TraitRef<'tcx>, cx: &mut DocContext<'tcx>) -> Path { @@ -1273,11 +1252,11 @@ fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext RequiredAssocConstItem(generics, Box::new(clean_ty(ty, cx))) } hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => { - let m = clean_function(cx, sig, trait_item.generics, FunctionArgs::Body(body)); + let m = clean_function(cx, sig, trait_item.generics, ParamsSrc::Body(body)); MethodItem(m, None) } hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(idents)) => { - let m = clean_function(cx, sig, trait_item.generics, FunctionArgs::Idents(idents)); + let m = clean_function(cx, sig, trait_item.generics, ParamsSrc::Idents(idents)); RequiredMethodItem(m) } hir::TraitItemKind::Type(bounds, Some(default)) => { @@ -1318,7 +1297,7 @@ pub(crate) fn clean_impl_item<'tcx>( type_: clean_ty(ty, cx), })), hir::ImplItemKind::Fn(ref sig, body) => { - let m = clean_function(cx, sig, impl_.generics, FunctionArgs::Body(body)); + let m = clean_function(cx, sig, impl_.generics, ParamsSrc::Body(body)); let defaultness = cx.tcx.defaultness(impl_.owner_id); MethodItem(m, Some(defaultness)) } @@ -1390,14 +1369,14 @@ pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocCo } ty::AssocItemContainer::Trait => tcx.types.self_param, }; - let self_arg_ty = + let self_param_ty = tcx.fn_sig(assoc_item.def_id).instantiate_identity().input(0).skip_binder(); - if self_arg_ty == self_ty { - item.decl.inputs.values[0].type_ = SelfTy; - } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() + if self_param_ty == self_ty { + item.decl.inputs[0].type_ = SelfTy; + } else if let ty::Ref(_, ty, _) = *self_param_ty.kind() && ty == self_ty { - match item.decl.inputs.values[0].type_ { + match item.decl.inputs[0].type_ { BorrowedRef { ref mut type_, .. } => **type_ = SelfTy, _ => unreachable!(), } @@ -2611,15 +2590,15 @@ fn clean_bare_fn_ty<'tcx>( cx: &mut DocContext<'tcx>, ) -> BareFunctionDecl { let (generic_params, decl) = enter_impl_trait(cx, |cx| { - // NOTE: generics must be cleaned before args + // NOTE: Generics must be cleaned before params. let generic_params = bare_fn .generic_params .iter() .filter(|p| !is_elided_lifetime(p)) .map(|x| clean_generic_param(cx, None, x)) .collect(); - let args = clean_args_from_types_and_names(cx, bare_fn.decl.inputs, bare_fn.param_idents); - let decl = clean_fn_decl_with_args(cx, bare_fn.decl, None, args); + let params = clean_params(cx, bare_fn.decl.inputs, bare_fn.param_idents); + let decl = clean_fn_decl_with_params(cx, bare_fn.decl, None, params); (generic_params, decl) }); BareFunctionDecl { safety: bare_fn.safety, abi: bare_fn.abi, decl, generic_params } @@ -2629,7 +2608,6 @@ fn clean_unsafe_binder_ty<'tcx>( unsafe_binder_ty: &hir::UnsafeBinderTy<'tcx>, cx: &mut DocContext<'tcx>, ) -> UnsafeBinderTy { - // NOTE: generics must be cleaned before args let generic_params = unsafe_binder_ty .generic_params .iter() @@ -3155,7 +3133,7 @@ fn clean_maybe_renamed_foreign_item<'tcx>( cx.with_param_env(def_id, |cx| { let kind = match item.kind { hir::ForeignItemKind::Fn(sig, idents, generics) => ForeignFunctionItem( - clean_function(cx, &sig, generics, FunctionArgs::Idents(idents)), + clean_function(cx, &sig, generics, ParamsSrc::Idents(idents)), sig.header.safety(), ), hir::ForeignItemKind::Static(ty, mutability, safety) => ForeignStaticItem( diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index f58cdfc6b5eef..cceafcbbb228e 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -1407,32 +1407,28 @@ pub(crate) struct Function { #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub(crate) struct FnDecl { - pub(crate) inputs: Arguments, + pub(crate) inputs: Vec, pub(crate) output: Type, pub(crate) c_variadic: bool, } impl FnDecl { pub(crate) fn receiver_type(&self) -> Option<&Type> { - self.inputs.values.first().and_then(|v| v.to_receiver()) + self.inputs.first().and_then(|v| v.to_receiver()) } } +/// A function parameter. #[derive(Clone, PartialEq, Eq, Debug, Hash)] -pub(crate) struct Arguments { - pub(crate) values: Vec, -} - -#[derive(Clone, PartialEq, Eq, Debug, Hash)] -pub(crate) struct Argument { - pub(crate) type_: Type, +pub(crate) struct Parameter { pub(crate) name: Option, + pub(crate) type_: Type, /// This field is used to represent "const" arguments from the `rustc_legacy_const_generics` /// feature. More information in . pub(crate) is_const: bool, } -impl Argument { +impl Parameter { pub(crate) fn to_receiver(&self) -> Option<&Type> { if self.name == Some(kw::SelfLower) { Some(&self.type_) } else { None } } diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 9ac328f7495d7..299fd6b9adbb0 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -1186,8 +1186,8 @@ impl clean::Impl { { primitive_link(f, PrimitiveType::Array, format_args!("[{name}; N]"), cx)?; } else if let clean::BareFunction(bare_fn) = &type_ - && let [clean::Argument { type_: clean::Type::Generic(name), .. }] = - &bare_fn.decl.inputs.values[..] + && let [clean::Parameter { type_: clean::Type::Generic(name), .. }] = + &bare_fn.decl.inputs[..] && (self.kind.is_fake_variadic() || self.kind.is_auto()) { // Hardcoded anchor library/core/src/primitive_docs.rs @@ -1234,22 +1234,20 @@ impl clean::Impl { } } -impl clean::Arguments { - pub(crate) fn print(&self, cx: &Context<'_>) -> impl Display { - fmt::from_fn(move |f| { - self.values - .iter() - .map(|input| { - fmt::from_fn(|f| { - if let Some(name) = input.name { - write!(f, "{}: ", name)?; - } - input.type_.print(cx).fmt(f) - }) +pub(crate) fn print_params(params: &[clean::Parameter], cx: &Context<'_>) -> impl Display { + fmt::from_fn(move |f| { + params + .iter() + .map(|param| { + fmt::from_fn(|f| { + if let Some(name) = param.name { + write!(f, "{}: ", name)?; + } + param.type_.print(cx).fmt(f) }) - .joined(", ", f) - }) - } + }) + .joined(", ", f) + }) } // Implements Write but only counts the bytes "written". @@ -1281,16 +1279,16 @@ impl clean::FnDecl { if f.alternate() { write!( f, - "({args:#}{ellipsis}){arrow:#}", - args = self.inputs.print(cx), + "({params:#}{ellipsis}){arrow:#}", + params = print_params(&self.inputs, cx), ellipsis = ellipsis, arrow = self.print_output(cx) ) } else { write!( f, - "({args}{ellipsis}){arrow}", - args = self.inputs.print(cx), + "({params}{ellipsis}){arrow}", + params = print_params(&self.inputs, cx), ellipsis = ellipsis, arrow = self.print_output(cx) ) @@ -1336,14 +1334,14 @@ impl clean::FnDecl { write!(f, "(")?; if let Some(n) = line_wrapping_indent - && !self.inputs.values.is_empty() + && !self.inputs.is_empty() { write!(f, "\n{}", Indent(n + 4))?; } - let last_input_index = self.inputs.values.len().checked_sub(1); - for (i, input) in self.inputs.values.iter().enumerate() { - if let Some(selfty) = input.to_receiver() { + let last_input_index = self.inputs.len().checked_sub(1); + for (i, param) in self.inputs.iter().enumerate() { + if let Some(selfty) = param.to_receiver() { match selfty { clean::SelfTy => { write!(f, "self")?; @@ -1361,13 +1359,13 @@ impl clean::FnDecl { } } } else { - if input.is_const { + if param.is_const { write!(f, "const ")?; } - if let Some(name) = input.name { + if let Some(name) = param.name { write!(f, "{}: ", name)?; } - input.type_.print(cx).fmt(f)?; + param.type_.print(cx).fmt(f)?; } match (line_wrapping_indent, last_input_index) { (_, None) => (), diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index 1360ab94cb1ce..aff8684ee3a09 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -1112,7 +1112,7 @@ fn simplify_fn_type<'a, 'tcx>( } Type::BareFunction(ref bf) => { let mut ty_generics = Vec::new(); - for ty in bf.decl.inputs.values.iter().map(|arg| &arg.type_) { + for ty in bf.decl.inputs.iter().map(|arg| &arg.type_) { simplify_fn_type( self_, generics, @@ -1418,15 +1418,15 @@ fn get_fn_inputs_and_outputs( (None, &func.generics) }; - let mut arg_types = Vec::new(); - for arg in decl.inputs.values.iter() { + let mut param_types = Vec::new(); + for param in decl.inputs.iter() { simplify_fn_type( self_, generics, - &arg.type_, + ¶m.type_, tcx, 0, - &mut arg_types, + &mut param_types, &mut rgen, false, cache, @@ -1439,7 +1439,7 @@ fn get_fn_inputs_and_outputs( let mut simplified_params = rgen.into_iter().collect::>(); simplified_params.sort_by_key(|(_, (idx, _))| -idx); ( - arg_types, + param_types, ret_types, simplified_params .iter() diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 5d85a4676b7e9..dab23f8e42a3d 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -609,11 +609,12 @@ impl FromClean for FunctionSignature { let clean::FnDecl { inputs, output, c_variadic } = decl; FunctionSignature { inputs: inputs - .values .into_iter() - // `_` is the most sensible name for missing param names. - .map(|arg| { - (arg.name.unwrap_or(kw::Underscore).to_string(), arg.type_.into_json(renderer)) + .map(|param| { + // `_` is the most sensible name for missing param names. + let name = param.name.unwrap_or(kw::Underscore).to_string(); + let type_ = param.type_.into_json(renderer); + (name, type_) }) .collect(), output: if output.is_unit() { None } else { Some(output.into_json(renderer)) }, From 82ff0a0e6a4be3aab167446ef1529018aa3f1fd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Wed, 16 Apr 2025 12:56:49 +0200 Subject: [PATCH 190/266] rustdoc: Properly clean fn params in all contexts --- src/librustdoc/clean/mod.rs | 58 +++++++++---------- src/librustdoc/clean/utils.rs | 9 ++- tests/rustdoc/anon-fn-params.rs | 25 ++++++++ tests/rustdoc/assoc-fns.rs | 13 +++++ tests/rustdoc/auxiliary/ext-anon-fn-params.rs | 7 +++ tests/rustdoc/ffi.rs | 4 ++ .../auxiliary/{fn-type.rs => fn-ptr-ty.rs} | 0 .../inline_cross/default-generic-args.rs | 8 +-- .../inline_cross/{fn-type.rs => fn-ptr-ty.rs} | 6 +- tests/rustdoc/inline_cross/impl_trait.rs | 2 +- 10 files changed, 89 insertions(+), 43 deletions(-) create mode 100644 tests/rustdoc/anon-fn-params.rs create mode 100644 tests/rustdoc/assoc-fns.rs create mode 100644 tests/rustdoc/auxiliary/ext-anon-fn-params.rs rename tests/rustdoc/inline_cross/auxiliary/{fn-type.rs => fn-ptr-ty.rs} (100%) rename tests/rustdoc/inline_cross/{fn-type.rs => fn-ptr-ty.rs} (71%) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 249a822076ecd..034ecb2f6c1a7 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1103,7 +1103,10 @@ fn clean_function<'tcx>( let generics = clean_generics(generics, cx); let params = match params { ParamsSrc::Body(body_id) => clean_params_via_body(cx, sig.decl.inputs, body_id), - ParamsSrc::Idents(idents) => clean_params(cx, sig.decl.inputs, idents), + // Let's not perpetuate anon params from Rust 2015; use `_` for them. + ParamsSrc::Idents(idents) => clean_params(cx, sig.decl.inputs, idents, |ident| { + Some(ident.map_or(kw::Underscore, |ident| ident.name)) + }), }; let decl = clean_fn_decl_with_params(cx, sig.decl, Some(&sig.header), params); (generics, decl) @@ -1115,30 +1118,13 @@ fn clean_params<'tcx>( cx: &mut DocContext<'tcx>, types: &[hir::Ty<'tcx>], idents: &[Option], + postprocess: impl Fn(Option) -> Option, ) -> Vec { - fn nonempty_name(ident: &Option) -> Option { - if let Some(ident) = ident - && ident.name != kw::Underscore - { - Some(ident.name) - } else { - None - } - } - - // If at least one argument has a name, use `_` as the name of unnamed - // arguments. Otherwise omit argument names. - let default_name = if idents.iter().any(|ident| nonempty_name(ident).is_some()) { - Some(kw::Underscore) - } else { - None - }; - types .iter() .enumerate() .map(|(i, ty)| Parameter { - name: idents.get(i).and_then(nonempty_name).or(default_name), + name: postprocess(idents[i]), type_: clean_ty(ty, cx), is_const: false, }) @@ -1184,8 +1170,6 @@ fn clean_poly_fn_sig<'tcx>( did: Option, sig: ty::PolyFnSig<'tcx>, ) -> FnDecl { - let mut names = did.map_or(&[] as &[_], |did| cx.tcx.fn_arg_idents(did)).iter(); - let mut output = clean_middle_ty(sig.output(), cx, None, None); // If the return type isn't an `impl Trait`, we can safely assume that this @@ -1198,16 +1182,20 @@ fn clean_poly_fn_sig<'tcx>( output = output.sugared_async_return_type(); } + let mut idents = did.map(|did| cx.tcx.fn_arg_idents(did)).unwrap_or_default().iter().copied(); + + // If this comes from a fn item, let's not perpetuate anon params from Rust 2015; use `_` for them. + // If this comes from a fn ptr ty, we just keep params unnamed since it's more conventional stylistically. + // Since the param name is not part of the semantic type, these params never bear a name unlike + // in the HIR case, thus we can't peform any fancy fallback logic unlike `clean_bare_fn_ty`. + let fallback = did.map(|_| kw::Underscore); + let params = sig .inputs() .iter() - .map(|t| Parameter { - type_: clean_middle_ty(t.map_bound(|t| *t), cx, None, None), - name: Some(if let Some(Some(ident)) = names.next() { - ident.name - } else { - kw::Underscore - }), + .map(|ty| Parameter { + name: idents.next().flatten().map(|ident| ident.name).or(fallback), + type_: clean_middle_ty(ty.map_bound(|ty| *ty), cx, None, None), is_const: false, }) .collect(); @@ -2597,7 +2585,17 @@ fn clean_bare_fn_ty<'tcx>( .filter(|p| !is_elided_lifetime(p)) .map(|x| clean_generic_param(cx, None, x)) .collect(); - let params = clean_params(cx, bare_fn.decl.inputs, bare_fn.param_idents); + // Since it's more conventional stylistically, elide the name of all params called `_` + // unless there's at least one interestingly named param in which case don't elide any + // name since mixing named and unnamed params is less legible. + let filter = |ident: Option| { + ident.map(|ident| ident.name).filter(|&ident| ident != kw::Underscore) + }; + let fallback = + bare_fn.param_idents.iter().copied().find_map(filter).map(|_| kw::Underscore); + let params = clean_params(cx, bare_fn.decl.inputs, bare_fn.param_idents, |ident| { + filter(ident).or(fallback) + }); let decl = clean_fn_decl_with_params(cx, bare_fn.decl, None, params); (generic_params, decl) }); diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 8ee08edec1996..af7986d030ee7 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -303,13 +303,12 @@ pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol { debug!("trying to get a name from pattern: {p:?}"); Symbol::intern(&match &p.kind { - // FIXME(never_patterns): does this make sense? - PatKind::Missing => unreachable!(), - PatKind::Wild - | PatKind::Err(_) + PatKind::Err(_) + | PatKind::Missing // Let's not perpetuate anon params from Rust 2015; use `_` for them. | PatKind::Never + | PatKind::Range(..) | PatKind::Struct(..) - | PatKind::Range(..) => { + | PatKind::Wild => { return kw::Underscore; } PatKind::Binding(_, _, ident, _) => return ident.name, diff --git a/tests/rustdoc/anon-fn-params.rs b/tests/rustdoc/anon-fn-params.rs new file mode 100644 index 0000000000000..9af1af3d3fa3f --- /dev/null +++ b/tests/rustdoc/anon-fn-params.rs @@ -0,0 +1,25 @@ +// Test that we render the deprecated anonymous trait function parameters from Rust 2015 as +// underscores in order not to perpetuate it and for legibility. + +//@ edition: 2015 +#![expect(anonymous_parameters)] + +// Check the "local case" (HIR cleaning) // + +//@ has anon_fn_params/trait.Trait.html +pub trait Trait { + //@ has - '//*[@id="tymethod.required"]' 'fn required(_: Option, _: impl Fn(&str) -> bool)' + fn required(Option, impl Fn(&str) -> bool); + //@ has - '//*[@id="method.provided"]' 'fn provided(_: [i32; 2])' + fn provided([i32; 2]) {} +} + +// Check the "extern case" (middle cleaning) // + +//@ aux-build: ext-anon-fn-params.rs +extern crate ext_anon_fn_params; + +//@ has anon_fn_params/trait.ExtTrait.html +//@ has - '//*[@id="tymethod.required"]' 'fn required(_: Option, _: impl Fn(&str) -> bool)' +//@ has - '//*[@id="method.provided"]' 'fn provided(_: [i32; 2])' +pub use ext_anon_fn_params::Trait as ExtTrait; diff --git a/tests/rustdoc/assoc-fns.rs b/tests/rustdoc/assoc-fns.rs new file mode 100644 index 0000000000000..6ffbebc3d27ef --- /dev/null +++ b/tests/rustdoc/assoc-fns.rs @@ -0,0 +1,13 @@ +// Basic testing for associated functions (in traits, trait impls & inherent impls). + +//@ has assoc_fns/trait.Trait.html +pub trait Trait { + //@ has - '//*[@id="tymethod.required"]' 'fn required(first: i32, second: &str)' + fn required(first: i32, second: &str); + + //@ has - '//*[@id="method.provided"]' 'fn provided(only: ())' + fn provided(only: ()) {} + + //@ has - '//*[@id="tymethod.params_are_unnamed"]' 'fn params_are_unnamed(_: i32, _: u32)' + fn params_are_unnamed(_: i32, _: u32); +} diff --git a/tests/rustdoc/auxiliary/ext-anon-fn-params.rs b/tests/rustdoc/auxiliary/ext-anon-fn-params.rs new file mode 100644 index 0000000000000..1acb919ca64f5 --- /dev/null +++ b/tests/rustdoc/auxiliary/ext-anon-fn-params.rs @@ -0,0 +1,7 @@ +//@ edition: 2015 +#![expect(anonymous_parameters)] + +pub trait Trait { + fn required(Option, impl Fn(&str) -> bool); + fn provided([i32; 2]) {} +} diff --git a/tests/rustdoc/ffi.rs b/tests/rustdoc/ffi.rs index 5ba7cdba91096..524fb0edefb6e 100644 --- a/tests/rustdoc/ffi.rs +++ b/tests/rustdoc/ffi.rs @@ -9,4 +9,8 @@ pub use lib::foreigner; extern "C" { //@ has ffi/fn.another.html //pre 'pub unsafe extern "C" fn another(cold_as_ice: u32)' pub fn another(cold_as_ice: u32); + + //@ has ffi/fn.params_are_unnamed.html //pre \ + // 'pub unsafe extern "C" fn params_are_unnamed(_: i32, _: u32)' + pub fn params_are_unnamed(_: i32, _: u32); } diff --git a/tests/rustdoc/inline_cross/auxiliary/fn-type.rs b/tests/rustdoc/inline_cross/auxiliary/fn-ptr-ty.rs similarity index 100% rename from tests/rustdoc/inline_cross/auxiliary/fn-type.rs rename to tests/rustdoc/inline_cross/auxiliary/fn-ptr-ty.rs diff --git a/tests/rustdoc/inline_cross/default-generic-args.rs b/tests/rustdoc/inline_cross/default-generic-args.rs index 0469221b3d858..5124fbdf8daeb 100644 --- a/tests/rustdoc/inline_cross/default-generic-args.rs +++ b/tests/rustdoc/inline_cross/default-generic-args.rs @@ -53,17 +53,17 @@ pub use default_generic_args::R2; //@ has user/type.H0.html // Check that we handle higher-ranked regions correctly: -//@ has - '//*[@class="rust item-decl"]//code' "fn(_: for<'a> fn(_: Re<'a>))" +//@ has - '//*[@class="rust item-decl"]//code' "fn(for<'a> fn(Re<'a>))" pub use default_generic_args::H0; //@ has user/type.H1.html // Check that we don't conflate distinct universially quantified regions (#1): -//@ has - '//*[@class="rust item-decl"]//code' "for<'b> fn(_: for<'a> fn(_: Re<'a, &'b ()>))" +//@ has - '//*[@class="rust item-decl"]//code' "for<'b> fn(for<'a> fn(Re<'a, &'b ()>))" pub use default_generic_args::H1; //@ has user/type.H2.html // Check that we don't conflate distinct universially quantified regions (#2): -//@ has - '//*[@class="rust item-decl"]//code' "for<'a> fn(_: for<'b> fn(_: Re<'a, &'b ()>))" +//@ has - '//*[@class="rust item-decl"]//code' "for<'a> fn(for<'b> fn(Re<'a, &'b ()>))" pub use default_generic_args::H2; //@ has user/type.P0.html @@ -86,7 +86,7 @@ pub use default_generic_args::A0; // Demonstrates that we currently don't elide generic arguments that are alpha-equivalent to their // respective generic parameter (after instantiation) for perf reasons (it would require us to // create an inference context). -//@ has - '//*[@class="rust item-decl"]//code' "Alpha fn(_: &'arbitrary ())>" +//@ has - '//*[@class="rust item-decl"]//code' "Alpha fn(&'arbitrary ())>" pub use default_generic_args::A1; //@ has user/type.M0.html diff --git a/tests/rustdoc/inline_cross/fn-type.rs b/tests/rustdoc/inline_cross/fn-ptr-ty.rs similarity index 71% rename from tests/rustdoc/inline_cross/fn-type.rs rename to tests/rustdoc/inline_cross/fn-ptr-ty.rs index 8db6f65f421fb..0105962252172 100644 --- a/tests/rustdoc/inline_cross/fn-type.rs +++ b/tests/rustdoc/inline_cross/fn-ptr-ty.rs @@ -2,11 +2,11 @@ // They should be rendered exactly as the user wrote it, i.e., in source order and with unused // parameters present, not stripped. -//@ aux-crate:fn_type=fn-type.rs +//@ aux-crate:fn_ptr_ty=fn-ptr-ty.rs //@ edition: 2021 #![crate_name = "user"] //@ has user/type.F.html //@ has - '//*[@class="rust item-decl"]//code' \ -// "for<'z, 'a, '_unused> fn(_: &'z for<'b> fn(_: &'b str), _: &'a ()) -> &'a ();" -pub use fn_type::F; +// "for<'z, 'a, '_unused> fn(&'z for<'b> fn(&'b str), &'a ()) -> &'a ();" +pub use fn_ptr_ty::F; diff --git a/tests/rustdoc/inline_cross/impl_trait.rs b/tests/rustdoc/inline_cross/impl_trait.rs index e6baf33660acb..468ac0830619b 100644 --- a/tests/rustdoc/inline_cross/impl_trait.rs +++ b/tests/rustdoc/inline_cross/impl_trait.rs @@ -29,7 +29,7 @@ pub use impl_trait_aux::func4; //@ has impl_trait/fn.func5.html //@ has - '//pre[@class="rust item-decl"]' "func5(" //@ has - '//pre[@class="rust item-decl"]' "_f: impl for<'any> Fn(&'any str, &'any str) -> bool + for<'r> Other = ()>," -//@ has - '//pre[@class="rust item-decl"]' "_a: impl for<'beta, 'alpha, '_gamma> Auxiliary<'alpha, Item<'beta> = fn(_: &'beta ())>" +//@ has - '//pre[@class="rust item-decl"]' "_a: impl for<'beta, 'alpha, '_gamma> Auxiliary<'alpha, Item<'beta> = fn(&'beta ())>" //@ !has - '//pre[@class="rust item-decl"]' 'where' pub use impl_trait_aux::func5; From bf2696311be53bed4fe976bb25bed81f0d7477ce Mon Sep 17 00:00:00 2001 From: Maksim Bondarenkov Date: Thu, 17 Apr 2025 12:53:17 +0300 Subject: [PATCH 191/266] bootstrap: enable zlib for LLVM when we compile it for profiling when compiling target LLVM with `opt-dist local` on Windows/MinGW, profraw files are being compressed with zlib, so compiling without it will make `llvm-profdata` complain about lacking of zlib support. this error is shown: `profile uses zlib compression but the profile reader was built without zlib support` example from llvm test suite: https://github.com/llvm/llvm-project/blob/76b5fcbf975547251faaeed8b567ea09d139a607/llvm/test/tools/llvm-profdata/nocompress.test#L15 --- src/bootstrap/download-ci-llvm-stamp | 2 +- src/bootstrap/src/core/build_steps/llvm.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/bootstrap/download-ci-llvm-stamp b/src/bootstrap/download-ci-llvm-stamp index e157ff233bbf7..b70d452b427c8 100644 --- a/src/bootstrap/download-ci-llvm-stamp +++ b/src/bootstrap/download-ci-llvm-stamp @@ -1,4 +1,4 @@ Change this file to make users of the `download-ci-llvm` configuration download a new version of LLVM from CI, even if the LLVM submodule hasn’t changed. -Last change is for: https://github.com/rust-lang/rust/pull/138784 +Last change is for: https://github.com/rust-lang/rust/pull/139931 diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index 69a8bd59f16ca..6e84b83d17dcc 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -370,8 +370,8 @@ impl Step for Llvm { cfg.define("LLVM_PROFDATA_FILE", path); } - // Libraries for ELF section compression. - if !target.is_windows() { + // Libraries for ELF section compression and profraw files merging. + if !target.is_msvc() { cfg.define("LLVM_ENABLE_ZLIB", "ON"); } else { cfg.define("LLVM_ENABLE_ZLIB", "OFF"); From 62a104d99e801f80c3740902ccc344dcf909f71d Mon Sep 17 00:00:00 2001 From: Maksim Bondarenkov Date: Thu, 17 Apr 2025 13:01:22 +0300 Subject: [PATCH 192/266] opt-dist: add a flag for running tests when using `opt-dist local` user probably won't need to run tests (for various reasons). currently the only way to disable them is to set `TRY_DIST_BUILD=1`, which is not obvious and can be bad for non-CI envronments (as I guess) --- src/tools/opt-dist/src/environment.rs | 5 +++++ src/tools/opt-dist/src/main.rs | 10 +++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/tools/opt-dist/src/environment.rs b/src/tools/opt-dist/src/environment.rs index 90d0ca717b25c..9342d164be411 100644 --- a/src/tools/opt-dist/src/environment.rs +++ b/src/tools/opt-dist/src/environment.rs @@ -25,6 +25,7 @@ pub struct Environment { prebuilt_rustc_perf: Option, use_bolt: bool, shared_llvm: bool, + run_tests: bool, } impl Environment { @@ -101,6 +102,10 @@ impl Environment { pub fn benchmark_cargo_config(&self) -> &[String] { &self.benchmark_cargo_config } + + pub fn run_tests(&self) -> bool { + self.run_tests + } } /// What is the extension of binary executables on this platform? diff --git a/src/tools/opt-dist/src/main.rs b/src/tools/opt-dist/src/main.rs index ac5d294f07ed1..4cc6a9a41f082 100644 --- a/src/tools/opt-dist/src/main.rs +++ b/src/tools/opt-dist/src/main.rs @@ -94,6 +94,10 @@ enum EnvironmentCmd { /// Arguments passed to `rustc-perf --cargo-config ` when running benchmarks. #[arg(long)] benchmark_cargo_config: Vec, + + /// Perform tests after final build if it's not a try build + #[arg(long)] + run_tests: bool, }, /// Perform an optimized build on Linux CI, from inside Docker. LinuxCi { @@ -125,6 +129,7 @@ fn create_environment(args: Args) -> anyhow::Result<(Environment, Vec)> skipped_tests, benchmark_cargo_config, shared, + run_tests, } => { let env = EnvironmentBuilder::default() .host_tuple(target_triple) @@ -138,6 +143,7 @@ fn create_environment(args: Args) -> anyhow::Result<(Environment, Vec)> .use_bolt(use_bolt) .skipped_tests(skipped_tests) .benchmark_cargo_config(benchmark_cargo_config) + .run_tests(run_tests) .build()?; (env, shared.build_args) @@ -160,6 +166,7 @@ fn create_environment(args: Args) -> anyhow::Result<(Environment, Vec)> // FIXME: Enable bolt for aarch64 once it's fixed upstream. Broken as of December 2024. .use_bolt(!is_aarch64) .skipped_tests(vec![]) + .run_tests(true) .build()?; (env, shared.build_args) @@ -179,6 +186,7 @@ fn create_environment(args: Args) -> anyhow::Result<(Environment, Vec)> .shared_llvm(false) .use_bolt(false) .skipped_tests(vec![]) + .run_tests(true) .build()?; (env, shared.build_args) @@ -344,7 +352,7 @@ fn execute_pipeline( // possible regressions. // The tests are not executed for try builds, which can be in various broken states, so we don't // want to gatekeep them with tests. - if !is_try_build() { + if !is_try_build() && env.run_tests() { timer.section("Run tests", |_| run_tests(env))?; } From 289a23e0e2691e2c4f14427d8495c1c78f3f0d7b Mon Sep 17 00:00:00 2001 From: lcnr Date: Wed, 16 Apr 2025 10:45:59 +0200 Subject: [PATCH 193/266] do not emit `OpaqueCast` projections with `-Znext-solver` --- .../rustc_hir_typeck/src/expr_use_visitor.rs | 25 ++++++++++------- compiler/rustc_middle/src/hir/place.rs | 2 ++ compiler/rustc_middle/src/mir/syntax.rs | 2 ++ .../src/builder/matches/match_pair.rs | 25 +++++++++-------- .../src/post_analysis_normalize.rs | 28 ++++++++++--------- 5 files changed, 48 insertions(+), 34 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index 27df8f0e98a13..0511f4e25ad3d 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -1502,16 +1502,21 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx let mut projections = base_place.place.projections; let node_ty = self.cx.typeck_results().node_type(node); - // Opaque types can't have field projections, but we can instead convert - // the current place in-place (heh) to the hidden type, and then apply all - // follow up projections on that. - if node_ty != place_ty - && self - .cx - .try_structurally_resolve_type(self.cx.tcx().hir_span(base_place.hir_id), place_ty) - .is_impl_trait() - { - projections.push(Projection { kind: ProjectionKind::OpaqueCast, ty: node_ty }); + if !self.cx.tcx().next_trait_solver_globally() { + // Opaque types can't have field projections, but we can instead convert + // the current place in-place (heh) to the hidden type, and then apply all + // follow up projections on that. + if node_ty != place_ty + && self + .cx + .try_structurally_resolve_type( + self.cx.tcx().hir_span(base_place.hir_id), + place_ty, + ) + .is_impl_trait() + { + projections.push(Projection { kind: ProjectionKind::OpaqueCast, ty: node_ty }); + } } projections.push(Projection { kind, ty }); PlaceWithHirId::new(node, base_place.place.base_ty, base_place.place.base, projections) diff --git a/compiler/rustc_middle/src/hir/place.rs b/compiler/rustc_middle/src/hir/place.rs index 60ce8544aa0ed..c3d10615cf10c 100644 --- a/compiler/rustc_middle/src/hir/place.rs +++ b/compiler/rustc_middle/src/hir/place.rs @@ -40,6 +40,8 @@ pub enum ProjectionKind { /// A conversion from an opaque type to its hidden type so we can /// do further projections on it. + /// + /// This is unused if `-Znext-solver` is enabled. OpaqueCast, } diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index c7561f8afef9a..304b3caa6e19f 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -1242,6 +1242,8 @@ pub enum ProjectionElem { /// Like an explicit cast from an opaque type to a concrete type, but without /// requiring an intermediate variable. + /// + /// This is unused with `-Znext-solver`. OpaqueCast(T), /// A transmute from an unsafe binder to the type that it wraps. This is a projection diff --git a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs index 9670c1716f585..d66b38c5b005c 100644 --- a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs +++ b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs @@ -101,18 +101,21 @@ impl<'tcx> MatchPairTree<'tcx> { place_builder = resolved; } - // Only add the OpaqueCast projection if the given place is an opaque type and the - // expected type from the pattern is not. - let may_need_cast = match place_builder.base() { - PlaceBase::Local(local) => { - let ty = - Place::ty_from(local, place_builder.projection(), &cx.local_decls, cx.tcx).ty; - ty != pattern.ty && ty.has_opaque_types() + if !cx.tcx.next_trait_solver_globally() { + // Only add the OpaqueCast projection if the given place is an opaque type and the + // expected type from the pattern is not. + let may_need_cast = match place_builder.base() { + PlaceBase::Local(local) => { + let ty = + Place::ty_from(local, place_builder.projection(), &cx.local_decls, cx.tcx) + .ty; + ty != pattern.ty && ty.has_opaque_types() + } + _ => true, + }; + if may_need_cast { + place_builder = place_builder.project(ProjectionElem::OpaqueCast(pattern.ty)); } - _ => true, - }; - if may_need_cast { - place_builder = place_builder.project(ProjectionElem::OpaqueCast(pattern.ty)); } let place = place_builder.try_to_place(cx); diff --git a/compiler/rustc_mir_transform/src/post_analysis_normalize.rs b/compiler/rustc_mir_transform/src/post_analysis_normalize.rs index 76c2f082c0bfc..5599dee4ccad3 100644 --- a/compiler/rustc_mir_transform/src/post_analysis_normalize.rs +++ b/compiler/rustc_mir_transform/src/post_analysis_normalize.rs @@ -39,20 +39,22 @@ impl<'tcx> MutVisitor<'tcx> for PostAnalysisNormalizeVisitor<'tcx> { _context: PlaceContext, _location: Location, ) { - // Performance optimization: don't reintern if there is no `OpaqueCast` to remove. - if place.projection.iter().all(|elem| !matches!(elem, ProjectionElem::OpaqueCast(_))) { - return; + if !self.tcx.next_trait_solver_globally() { + // `OpaqueCast` projections are only needed if there are opaque types on which projections + // are performed. After the `PostAnalysisNormalize` pass, all opaque types are replaced with their + // hidden types, so we don't need these projections anymore. + // + // Performance optimization: don't reintern if there is no `OpaqueCast` to remove. + if place.projection.iter().any(|elem| matches!(elem, ProjectionElem::OpaqueCast(_))) { + place.projection = self.tcx.mk_place_elems( + &place + .projection + .into_iter() + .filter(|elem| !matches!(elem, ProjectionElem::OpaqueCast(_))) + .collect::>(), + ); + }; } - // `OpaqueCast` projections are only needed if there are opaque types on which projections - // are performed. After the `PostAnalysisNormalize` pass, all opaque types are replaced with their - // hidden types, so we don't need these projections anymore. - place.projection = self.tcx.mk_place_elems( - &place - .projection - .into_iter() - .filter(|elem| !matches!(elem, ProjectionElem::OpaqueCast(_))) - .collect::>(), - ); self.super_place(place, _context, _location); } From c85b5fcd07907a82f158df31a4f36fea608dab42 Mon Sep 17 00:00:00 2001 From: lcnr Date: Thu, 17 Apr 2025 12:36:27 +0200 Subject: [PATCH 194/266] check OpaqueCast tests with next-solver --- .../cross_inference_pattern_bug_no_type.rs | 1 - tests/ui/type-alias-impl-trait/destructure_tait-ice-113594.rs | 2 ++ tests/ui/type-alias-impl-trait/tait-normalize.rs | 2 ++ 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/ui/type-alias-impl-trait/cross_inference_pattern_bug_no_type.rs b/tests/ui/type-alias-impl-trait/cross_inference_pattern_bug_no_type.rs index 736a9dfb49033..be8b7fa6a9352 100644 --- a/tests/ui/type-alias-impl-trait/cross_inference_pattern_bug_no_type.rs +++ b/tests/ui/type-alias-impl-trait/cross_inference_pattern_bug_no_type.rs @@ -1,6 +1,5 @@ //@ compile-flags: --crate-type=lib //@ edition: 2021 -//@ rustc-env:RUST_BACKTRACE=0 //@ check-pass // tracked in https://github.com/rust-lang/rust/issues/96572 diff --git a/tests/ui/type-alias-impl-trait/destructure_tait-ice-113594.rs b/tests/ui/type-alias-impl-trait/destructure_tait-ice-113594.rs index a3b1aba70411f..a42ea083d740c 100644 --- a/tests/ui/type-alias-impl-trait/destructure_tait-ice-113594.rs +++ b/tests/ui/type-alias-impl-trait/destructure_tait-ice-113594.rs @@ -1,3 +1,5 @@ +//@ revisions: current next +//@ [next] compile-flags: -Znext-solver //@ build-pass //@ edition: 2021 diff --git a/tests/ui/type-alias-impl-trait/tait-normalize.rs b/tests/ui/type-alias-impl-trait/tait-normalize.rs index 38e09b6087b64..a34d167bcc391 100644 --- a/tests/ui/type-alias-impl-trait/tait-normalize.rs +++ b/tests/ui/type-alias-impl-trait/tait-normalize.rs @@ -1,3 +1,5 @@ +//@ revisions: current next +//@ [next] compile-flags: -Znext-solver //@ check-pass #![feature(type_alias_impl_trait)] From d20f84847886389e25c0669dc48a8890491793df Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Thu, 17 Apr 2025 16:54:07 +0800 Subject: [PATCH 195/266] compiletest: add specific `//@ ignore-auxiliary` for test support files This is for files that *participate* in actual tests but should not be built by `compiletest` (i.e. these files are involved through `mod xxx;` or `include!()` or `#[path = "xxx"]`, etc.). A specialized directive like `//@ ignore-auxiliary` makes it way easier to audit disabled tests via `//@ ignore-test`. --- src/tools/compiletest/src/directive-list.rs | 1 + src/tools/compiletest/src/header/cfg.rs | 4 ++++ src/tools/compiletest/src/header/tests.rs | 6 ++++++ 3 files changed, 11 insertions(+) diff --git a/src/tools/compiletest/src/directive-list.rs b/src/tools/compiletest/src/directive-list.rs index 086a8a67456f3..44c52c8c7663d 100644 --- a/src/tools/compiletest/src/directive-list.rs +++ b/src/tools/compiletest/src/directive-list.rs @@ -44,6 +44,7 @@ const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "ignore-arm-unknown-linux-gnueabihf", "ignore-arm-unknown-linux-musleabi", "ignore-arm-unknown-linux-musleabihf", + "ignore-auxiliary", "ignore-avr", "ignore-beta", "ignore-cdb", diff --git a/src/tools/compiletest/src/header/cfg.rs b/src/tools/compiletest/src/header/cfg.rs index c369fff97f4f0..f1f1384afb971 100644 --- a/src/tools/compiletest/src/header/cfg.rs +++ b/src/tools/compiletest/src/header/cfg.rs @@ -100,6 +100,10 @@ fn parse_cfg_name_directive<'a>( name: "test", message: "always" } + condition! { + name: "auxiliary", + message: "used by another main test file" + } condition! { name: &config.target, allowed_names: &target_cfgs.all_targets, diff --git a/src/tools/compiletest/src/header/tests.rs b/src/tools/compiletest/src/header/tests.rs index 3a8c3748de99f..2525e0adc8385 100644 --- a/src/tools/compiletest/src/header/tests.rs +++ b/src/tools/compiletest/src/header/tests.rs @@ -940,3 +940,9 @@ fn test_supported_crate_types() { "//@ needs-crate-type: bin, cdylib, dylib, lib, proc-macro, rlib, staticlib" )); } + +#[test] +fn test_ignore_auxiliary() { + let config = cfg().build(); + assert!(check_ignore(&config, "//@ ignore-auxiliary")); +} From d1178faa9394579a1befd2cbf9e4ecc7aeb7432b Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Thu, 17 Apr 2025 17:01:14 +0800 Subject: [PATCH 196/266] tests: refine disable reason for `tests/debuginfo/drop-locations.rs` --- tests/debuginfo/drop-locations.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/debuginfo/drop-locations.rs b/tests/debuginfo/drop-locations.rs index a55cf7b50a81a..91b3da5c34a8e 100644 --- a/tests/debuginfo/drop-locations.rs +++ b/tests/debuginfo/drop-locations.rs @@ -1,5 +1,7 @@ //@ ignore-android -//@ ignore-test: #128971 + +// FIXME: stepping with "next" in a debugger skips past end-of-scope drops +//@ ignore-test (broken, see #128971) #![allow(unused)] From 6bbee334fd77aed1c5267b97fea0c8e458f84e22 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Thu, 17 Apr 2025 17:04:30 +0800 Subject: [PATCH 197/266] rustc-dev-guide: document `//@ ignore-auxiliary` --- src/doc/rustc-dev-guide/src/tests/best-practices.md | 2 ++ src/doc/rustc-dev-guide/src/tests/directives.md | 3 +++ 2 files changed, 5 insertions(+) diff --git a/src/doc/rustc-dev-guide/src/tests/best-practices.md b/src/doc/rustc-dev-guide/src/tests/best-practices.md index 6905ee13283a6..2bdc7f3a2431b 100644 --- a/src/doc/rustc-dev-guide/src/tests/best-practices.md +++ b/src/doc/rustc-dev-guide/src/tests/best-practices.md @@ -175,6 +175,8 @@ See [compiletest directives] for a listing of directives. - For `ignore-*`/`needs-*`/`only-*` directives, unless extremely obvious, provide a brief remark on why the directive is needed. E.g. `"//@ ignore-wasi (wasi codegens the main symbol differently)"`. +- When using `//@ ignore-auxiliary`, specify the corresponding main test files, + e.g. ``//@ ignore-auxiliary (used by `./foo.rs`)``. ## FileCheck best practices diff --git a/src/doc/rustc-dev-guide/src/tests/directives.md b/src/doc/rustc-dev-guide/src/tests/directives.md index 0aad8be982ff4..dae659e6317b4 100644 --- a/src/doc/rustc-dev-guide/src/tests/directives.md +++ b/src/doc/rustc-dev-guide/src/tests/directives.md @@ -124,6 +124,9 @@ means the test won't be compiled or run. * `ignore-X` where `X` is a target detail or other criteria on which to ignore the test (see below) * `only-X` is like `ignore-X`, but will *only* run the test on that target or stage +* `ignore-auxiliary` is intended for files that *participate* in one or more other + main test files but that `compiletest` should not try to build the file itself. + Please backlink to which main test is actually using the auxiliary file. * `ignore-test` always ignores the test. This can be used to temporarily disable a test if it is currently not working, but you want to keep it in tree to re-enable it later. From 35a4140723c7424da012b9eca5e38cd8325ccb12 Mon Sep 17 00:00:00 2001 From: petr sumbera - Sun Microsystems - Prague Czech Republic Date: Thu, 17 Apr 2025 13:39:46 +0200 Subject: [PATCH 198/266] update libc --- Cargo.lock | 4 ++-- src/tools/rust-analyzer/Cargo.lock | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3d0e294217912..a2f8511e170eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2022,9 +2022,9 @@ checksum = "9fa0e2a1fcbe2f6be6c42e342259976206b383122fc152e872795338b5a3f3a7" [[package]] name = "libc" -version = "0.2.171" +version = "0.2.172" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" +checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" [[package]] name = "libdbus-sys" diff --git a/src/tools/rust-analyzer/Cargo.lock b/src/tools/rust-analyzer/Cargo.lock index 745a8097c8a50..2dbb3f5d69ca3 100644 --- a/src/tools/rust-analyzer/Cargo.lock +++ b/src/tools/rust-analyzer/Cargo.lock @@ -902,9 +902,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.169" +version = "0.2.172" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" +checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" [[package]] name = "libloading" From 89cac55bb85e91ad4d90f9e0bcf0c0e065b88a7d Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Thu, 17 Apr 2025 17:22:56 +0800 Subject: [PATCH 199/266] tests: use `//@ ignore-auxiliary` with backlinked primary test file --- tests/codegen/remap_path_prefix/aux_mod.rs | 2 +- tests/ui/borrowck/move-error-snippets-ext.rs | 2 +- tests/ui/codemap_tests/two_files_data.rs | 2 +- tests/ui/conditional-compilation/module_with_cfg.rs | 2 +- tests/ui/cross/cross-file-errors/underscore.rs | 2 +- .../directory_ownership/macro_expanded_mod_helper/foo/bar.rs | 2 +- .../directory_ownership/macro_expanded_mod_helper/foo/mod.rs | 2 +- tests/ui/lint/expansion-time-include.rs | 2 +- tests/ui/lint/known-tool-in-submodule/submodule.rs | 2 +- tests/ui/lint/lint_pre_expansion_extern_module_aux.rs | 2 +- tests/ui/lint/unknown-lints/other.rs | 4 +--- tests/ui/macros/auxiliary/macro-include-items-expr.rs | 2 -- tests/ui/macros/auxiliary/macro-include-items-item.rs | 2 -- tests/ui/macros/include-single-expr-helper-1.rs | 2 +- tests/ui/macros/include-single-expr-helper.rs | 2 +- tests/ui/macros/issue-69838-dir/bar.rs | 2 +- tests/ui/macros/issue-69838-dir/included.rs | 2 +- tests/ui/macros/macro-expanded-include/foo/mod.rs | 2 +- tests/ui/missing_non_modrs_mod/foo.rs | 3 +-- tests/ui/missing_non_modrs_mod/foo_inline.rs | 2 +- tests/ui/missing_non_modrs_mod/missing_non_modrs_mod.stderr | 2 +- tests/ui/modules/mod_file_aux.rs | 3 +-- tests/ui/modules_and_files_visibility/mod_file_aux.rs | 2 +- .../ui/modules_and_files_visibility/mod_file_disambig_aux.rs | 2 +- .../modules_and_files_visibility/mod_file_disambig_aux/mod.rs | 2 +- tests/ui/non_modrs_mods/foors_mod.rs | 4 +--- tests/ui/non_modrs_mods_and_inline_mods/x.rs | 2 +- tests/ui/non_modrs_mods_and_inline_mods/x/y/z/mod.rs | 2 +- tests/ui/numbers-arithmetic/saturating-float-casts-impl.rs | 2 +- tests/ui/parser/circular_modules_hello.rs | 2 +- .../circular-module-with-doc-comment-issue-97589/recursive.rs | 2 +- tests/ui/parser/issues/issue-48508-aux.rs | 3 +-- tests/ui/proc-macro/module.rs | 2 +- tests/ui/proc-macro/module_with_attrs.rs | 2 +- tests/ui/proc-macro/outer/inner.rs | 2 +- .../pretty-print-hack/allsorts-rental-0.5.6/src/lib.rs | 2 +- tests/ui/proc-macro/pretty-print-hack/rental-0.5.5/src/lib.rs | 2 +- tests/ui/proc-macro/pretty-print-hack/rental-0.5.6/src/lib.rs | 2 +- tests/ui/runtime/backtrace-debuginfo-aux.rs | 3 +-- 39 files changed, 37 insertions(+), 49 deletions(-) diff --git a/tests/codegen/remap_path_prefix/aux_mod.rs b/tests/codegen/remap_path_prefix/aux_mod.rs index c37e91c705ccd..3217e9e51e750 100644 --- a/tests/codegen/remap_path_prefix/aux_mod.rs +++ b/tests/codegen/remap_path_prefix/aux_mod.rs @@ -1,4 +1,4 @@ -//@ ignore-test: this is not a test +//@ ignore-auxiliary (used by `./main.rs`) #[inline] pub fn some_aux_mod_function() -> i32 { diff --git a/tests/ui/borrowck/move-error-snippets-ext.rs b/tests/ui/borrowck/move-error-snippets-ext.rs index f8103228cf81c..6dd68438f179c 100644 --- a/tests/ui/borrowck/move-error-snippets-ext.rs +++ b/tests/ui/borrowck/move-error-snippets-ext.rs @@ -1,4 +1,4 @@ -//@ ignore-test (auxiliary, used by other tests) +//@ ignore-auxiliary (used by `./move-error-snippets.rs`) macro_rules! aaa { ($c:ident) => {{ diff --git a/tests/ui/codemap_tests/two_files_data.rs b/tests/ui/codemap_tests/two_files_data.rs index a4e4cf7e896ed..82852f6cfbdff 100644 --- a/tests/ui/codemap_tests/two_files_data.rs +++ b/tests/ui/codemap_tests/two_files_data.rs @@ -1,4 +1,4 @@ -//@ ignore-test (auxiliary, used by other tests) +//@ ignore-auxiliary (used by `./two_files.rs`) trait Foo { } diff --git a/tests/ui/conditional-compilation/module_with_cfg.rs b/tests/ui/conditional-compilation/module_with_cfg.rs index 778379fa6ea7a..b713689c63c83 100644 --- a/tests/ui/conditional-compilation/module_with_cfg.rs +++ b/tests/ui/conditional-compilation/module_with_cfg.rs @@ -1,3 +1,3 @@ -//@ ignore-test (auxiliary, used by other tests) +//@ ignore-auxiliary (used by `./inner-cfg-non-inline-mod.rs`) #![cfg_attr(all(), cfg(FALSE))] diff --git a/tests/ui/cross/cross-file-errors/underscore.rs b/tests/ui/cross/cross-file-errors/underscore.rs index 9d075735393d0..73eb36cec24cb 100644 --- a/tests/ui/cross/cross-file-errors/underscore.rs +++ b/tests/ui/cross/cross-file-errors/underscore.rs @@ -1,4 +1,4 @@ -//@ ignore-test (auxiliary, used by other tests) +//@ ignore-auxiliary (used by `./main.rs`) #![crate_type = "lib"] macro_rules! underscore { diff --git a/tests/ui/directory_ownership/macro_expanded_mod_helper/foo/bar.rs b/tests/ui/directory_ownership/macro_expanded_mod_helper/foo/bar.rs index 1d832a36ef500..2ccdd798c73d5 100644 --- a/tests/ui/directory_ownership/macro_expanded_mod_helper/foo/bar.rs +++ b/tests/ui/directory_ownership/macro_expanded_mod_helper/foo/bar.rs @@ -1 +1 @@ -//@ ignore-test not a test, auxiliary +//@ ignore-auxiliary (used by `../../macro-expanded-mod.rs`) diff --git a/tests/ui/directory_ownership/macro_expanded_mod_helper/foo/mod.rs b/tests/ui/directory_ownership/macro_expanded_mod_helper/foo/mod.rs index 08349ba6747d4..9009f80c69104 100644 --- a/tests/ui/directory_ownership/macro_expanded_mod_helper/foo/mod.rs +++ b/tests/ui/directory_ownership/macro_expanded_mod_helper/foo/mod.rs @@ -1,3 +1,3 @@ -//@ ignore-test not a test, auxiliary +//@ ignore-auxiliary (used by `../../macro-expanded-mod.rs`) mod_decl!(bar); diff --git a/tests/ui/lint/expansion-time-include.rs b/tests/ui/lint/expansion-time-include.rs index 3ecc01b045c41..cbe3510f04ae2 100644 --- a/tests/ui/lint/expansion-time-include.rs +++ b/tests/ui/lint/expansion-time-include.rs @@ -1,4 +1,4 @@ -//@ ignore-test auxiliary file for expansion-time.rs +//@ ignore-auxiliary (used by `./expansion-time.rs`) 1 2 diff --git a/tests/ui/lint/known-tool-in-submodule/submodule.rs b/tests/ui/lint/known-tool-in-submodule/submodule.rs index 0bb2b93d53b73..9c24964e94f92 100644 --- a/tests/ui/lint/known-tool-in-submodule/submodule.rs +++ b/tests/ui/lint/known-tool-in-submodule/submodule.rs @@ -1,4 +1,4 @@ -//@ ignore-test: not a test +//@ ignore-auxiliary (used by `./root.rs`) #[allow(tool::lint)] pub fn foo() {} diff --git a/tests/ui/lint/lint_pre_expansion_extern_module_aux.rs b/tests/ui/lint/lint_pre_expansion_extern_module_aux.rs index 6e16a796ff19d..10e3c0f956440 100644 --- a/tests/ui/lint/lint_pre_expansion_extern_module_aux.rs +++ b/tests/ui/lint/lint_pre_expansion_extern_module_aux.rs @@ -1,3 +1,3 @@ -//@ ignore-test: not a test +//@ ignore-auxiliary (used by `./lint-pre-expansion-extern-module.rs`) pub fn try() {} diff --git a/tests/ui/lint/unknown-lints/other.rs b/tests/ui/lint/unknown-lints/other.rs index 253335849161e..7770bc59108d7 100644 --- a/tests/ui/lint/unknown-lints/other.rs +++ b/tests/ui/lint/unknown-lints/other.rs @@ -1,6 +1,4 @@ -//@ ignore-test (auxiliary) - -// Companion to allow-in-other-module.rs +//@ ignore-auxiliary (used by `./allow-in-other-module.rs`) // This should not warn. #![allow(not_a_real_lint)] diff --git a/tests/ui/macros/auxiliary/macro-include-items-expr.rs b/tests/ui/macros/auxiliary/macro-include-items-expr.rs index 7394f194b80ea..d00491fd7e5bb 100644 --- a/tests/ui/macros/auxiliary/macro-include-items-expr.rs +++ b/tests/ui/macros/auxiliary/macro-include-items-expr.rs @@ -1,3 +1 @@ -// ignore-test: this is not a test - 1 diff --git a/tests/ui/macros/auxiliary/macro-include-items-item.rs b/tests/ui/macros/auxiliary/macro-include-items-item.rs index 7d54745e03bff..761cd00218977 100644 --- a/tests/ui/macros/auxiliary/macro-include-items-item.rs +++ b/tests/ui/macros/auxiliary/macro-include-items-item.rs @@ -1,3 +1 @@ -// ignore-test: this is not a test - fn foo() { bar() } diff --git a/tests/ui/macros/include-single-expr-helper-1.rs b/tests/ui/macros/include-single-expr-helper-1.rs index ddeeb982f64cd..6802719afa1b3 100644 --- a/tests/ui/macros/include-single-expr-helper-1.rs +++ b/tests/ui/macros/include-single-expr-helper-1.rs @@ -1,4 +1,4 @@ -//@ ignore-test auxiliary file for include-single-expr.rs +//@ ignore-auxiliary (used by `./include-single-expr.rs`) 0 diff --git a/tests/ui/macros/include-single-expr-helper.rs b/tests/ui/macros/include-single-expr-helper.rs index e8ad9746b02cd..bd75bbbd583e6 100644 --- a/tests/ui/macros/include-single-expr-helper.rs +++ b/tests/ui/macros/include-single-expr-helper.rs @@ -1,4 +1,4 @@ -//@ ignore-test auxiliary file for include-single-expr.rs +//@ ignore-auxiliary (used by `./include-single-expr.rs`) 0 10 diff --git a/tests/ui/macros/issue-69838-dir/bar.rs b/tests/ui/macros/issue-69838-dir/bar.rs index 4433005b85f15..6f91f8e2ffadc 100644 --- a/tests/ui/macros/issue-69838-dir/bar.rs +++ b/tests/ui/macros/issue-69838-dir/bar.rs @@ -1,3 +1,3 @@ -//@ ignore-test -- this is an auxiliary file as part of another test. +//@ ignore-auxiliary (used by `../issue-69838-mods-relative-to-included-path.rs`) pub fn i_am_in_bar() {} diff --git a/tests/ui/macros/issue-69838-dir/included.rs b/tests/ui/macros/issue-69838-dir/included.rs index 11fcd3eff725d..328334d5e66af 100644 --- a/tests/ui/macros/issue-69838-dir/included.rs +++ b/tests/ui/macros/issue-69838-dir/included.rs @@ -1,3 +1,3 @@ -//@ ignore-test -- this is an auxiliary file as part of another test. +//@ ignore-auxiliary (used by `../issue-69838-mods-relative-to-included-path.rs`) pub mod bar; diff --git a/tests/ui/macros/macro-expanded-include/foo/mod.rs b/tests/ui/macros/macro-expanded-include/foo/mod.rs index 926d84c93e58f..4e6d9e4aea407 100644 --- a/tests/ui/macros/macro-expanded-include/foo/mod.rs +++ b/tests/ui/macros/macro-expanded-include/foo/mod.rs @@ -1,4 +1,4 @@ -//@ ignore-test (auxiliary, used by other tests) +//@ ignore-auxiliary (used by `../test.rs`) macro_rules! m { () => { include!("file.txt"); } diff --git a/tests/ui/missing_non_modrs_mod/foo.rs b/tests/ui/missing_non_modrs_mod/foo.rs index dd3e970b8c6e9..afdc5e39b84d2 100644 --- a/tests/ui/missing_non_modrs_mod/foo.rs +++ b/tests/ui/missing_non_modrs_mod/foo.rs @@ -1,4 +1,3 @@ -// -//@ ignore-test this is just a helper for the real test in this dir +//@ ignore-auxiliary (used by `./missing_non_modrs_mod.rs`) mod missing; diff --git a/tests/ui/missing_non_modrs_mod/foo_inline.rs b/tests/ui/missing_non_modrs_mod/foo_inline.rs index 9d46e9bdd0c36..ed6d3a49101da 100644 --- a/tests/ui/missing_non_modrs_mod/foo_inline.rs +++ b/tests/ui/missing_non_modrs_mod/foo_inline.rs @@ -1,4 +1,4 @@ -//@ ignore-test this is just a helper for the real test in this dir +//@ ignore-auxiliary (used by `./missing_non_modrs_mod_inline.rs`) mod inline { mod missing; diff --git a/tests/ui/missing_non_modrs_mod/missing_non_modrs_mod.stderr b/tests/ui/missing_non_modrs_mod/missing_non_modrs_mod.stderr index 4e48799318b6b..c084fbf00c26f 100644 --- a/tests/ui/missing_non_modrs_mod/missing_non_modrs_mod.stderr +++ b/tests/ui/missing_non_modrs_mod/missing_non_modrs_mod.stderr @@ -1,5 +1,5 @@ error[E0583]: file not found for module `missing` - --> $DIR/foo.rs:4:1 + --> $DIR/foo.rs:3:1 | LL | mod missing; | ^^^^^^^^^^^^ diff --git a/tests/ui/modules/mod_file_aux.rs b/tests/ui/modules/mod_file_aux.rs index f37296b3af0be..eec38d189b4a8 100644 --- a/tests/ui/modules/mod_file_aux.rs +++ b/tests/ui/modules/mod_file_aux.rs @@ -1,4 +1,3 @@ -//@ run-pass -//@ ignore-test Not a test. Used by other tests +//@ ignore-auxiliary (used by `./mod_file_with_path_attr.rs` and `mod_file.rs`) pub fn foo() -> isize { 10 } diff --git a/tests/ui/modules_and_files_visibility/mod_file_aux.rs b/tests/ui/modules_and_files_visibility/mod_file_aux.rs index 77390da75f8f3..6fac8dae3d766 100644 --- a/tests/ui/modules_and_files_visibility/mod_file_aux.rs +++ b/tests/ui/modules_and_files_visibility/mod_file_aux.rs @@ -1,3 +1,3 @@ -//@ ignore-test Not a test. Used by other tests +//@ ignore-auxiliary (used by `./mod_file_correct_spans.rs`) pub fn foo() -> isize { 10 } diff --git a/tests/ui/modules_and_files_visibility/mod_file_disambig_aux.rs b/tests/ui/modules_and_files_visibility/mod_file_disambig_aux.rs index e00b5629c0833..9a0b1c4b0d8e8 100644 --- a/tests/ui/modules_and_files_visibility/mod_file_disambig_aux.rs +++ b/tests/ui/modules_and_files_visibility/mod_file_disambig_aux.rs @@ -1 +1 @@ -//@ ignore-test not a test. aux file +//@ ignore-auxiliary (used by `./mod_file_disambig.rs`) diff --git a/tests/ui/modules_and_files_visibility/mod_file_disambig_aux/mod.rs b/tests/ui/modules_and_files_visibility/mod_file_disambig_aux/mod.rs index e00b5629c0833..232c933c4cbfc 100644 --- a/tests/ui/modules_and_files_visibility/mod_file_disambig_aux/mod.rs +++ b/tests/ui/modules_and_files_visibility/mod_file_disambig_aux/mod.rs @@ -1 +1 @@ -//@ ignore-test not a test. aux file +//@ ignore-auxiliary (used by `../mod_file_disambig.rs`) diff --git a/tests/ui/non_modrs_mods/foors_mod.rs b/tests/ui/non_modrs_mods/foors_mod.rs index b215e5f09e93e..dfaa11bfe13f3 100644 --- a/tests/ui/non_modrs_mods/foors_mod.rs +++ b/tests/ui/non_modrs_mods/foors_mod.rs @@ -1,6 +1,4 @@ -//@ run-pass -// -//@ ignore-test: not a test, used by non_modrs_mods.rs +//@ ignore-auxiliary (used by `./non_modrs_mods.rs`) pub mod inner_modrs_mod; pub mod inner_foors_mod; diff --git a/tests/ui/non_modrs_mods_and_inline_mods/x.rs b/tests/ui/non_modrs_mods_and_inline_mods/x.rs index c4548d39fad88..38ff011d40956 100644 --- a/tests/ui/non_modrs_mods_and_inline_mods/x.rs +++ b/tests/ui/non_modrs_mods_and_inline_mods/x.rs @@ -1,4 +1,4 @@ -//@ ignore-test: not a test +//@ ignore-auxiliary (used by `./non_modrs_mods_and_inline_mods.rs`) pub mod y { pub mod z; diff --git a/tests/ui/non_modrs_mods_and_inline_mods/x/y/z/mod.rs b/tests/ui/non_modrs_mods_and_inline_mods/x/y/z/mod.rs index ec7b7de78d8b7..cac5e274fbed6 100644 --- a/tests/ui/non_modrs_mods_and_inline_mods/x/y/z/mod.rs +++ b/tests/ui/non_modrs_mods_and_inline_mods/x/y/z/mod.rs @@ -1 +1 @@ -//@ ignore-test: not a test +//@ ignore-auxiliary (used by `../../../non_modrs_mods_and_inline_mods.rs`) diff --git a/tests/ui/numbers-arithmetic/saturating-float-casts-impl.rs b/tests/ui/numbers-arithmetic/saturating-float-casts-impl.rs index 4b176ef5caa60..4e578f6132fc2 100644 --- a/tests/ui/numbers-arithmetic/saturating-float-casts-impl.rs +++ b/tests/ui/numbers-arithmetic/saturating-float-casts-impl.rs @@ -1,4 +1,4 @@ -//@ ignore-test (auxiliary, used by other tests) +//@ ignore-auxiliary (used by `./saturating-float-casts.rs` and `./saturating-float-casts-wasm.rs`) // Tests saturating float->int casts. See u128-as-f32.rs for the opposite direction. // diff --git a/tests/ui/parser/circular_modules_hello.rs b/tests/ui/parser/circular_modules_hello.rs index eb0284d8b410f..540752ea2311f 100644 --- a/tests/ui/parser/circular_modules_hello.rs +++ b/tests/ui/parser/circular_modules_hello.rs @@ -1,4 +1,4 @@ -//@ ignore-test: this is an auxiliary file for circular-modules-main.rs +//@ ignore-auxiliary (used by `./circular-modules-main.rs`) #[path = "circular_modules_main.rs"] mod circular_modules_main; diff --git a/tests/ui/parser/issues/circular-module-with-doc-comment-issue-97589/recursive.rs b/tests/ui/parser/issues/circular-module-with-doc-comment-issue-97589/recursive.rs index 3d758be8c0553..2e9a15eb06dae 100644 --- a/tests/ui/parser/issues/circular-module-with-doc-comment-issue-97589/recursive.rs +++ b/tests/ui/parser/issues/circular-module-with-doc-comment-issue-97589/recursive.rs @@ -1,4 +1,4 @@ -//@ ignore-test: this is an auxiliary file for circular-module-with-doc-comment-issue-97589.rs +//@ ignore-auxiliary (used by `./circular-module-with-doc-comment-issue-97589.rs`) //! this comment caused the circular dependency checker to break diff --git a/tests/ui/parser/issues/issue-48508-aux.rs b/tests/ui/parser/issues/issue-48508-aux.rs index 0f2b4427383fd..0bf6490edf4db 100644 --- a/tests/ui/parser/issues/issue-48508-aux.rs +++ b/tests/ui/parser/issues/issue-48508-aux.rs @@ -1,5 +1,4 @@ -//@ run-pass -//@ ignore-test Not a test. Used by issue-48508.rs +//@ ignore-auxiliary (used by `./issue-48508.rs`) pub fn other() -> f64 { let µ = 1.0; diff --git a/tests/ui/proc-macro/module.rs b/tests/ui/proc-macro/module.rs index 210c05988bf23..5878f1b7ddd8a 100644 --- a/tests/ui/proc-macro/module.rs +++ b/tests/ui/proc-macro/module.rs @@ -1 +1 @@ -//@ ignore-test (auxiliary, used by other tests) +//@ ignore-auxiliary (used by `./attributes-on-modules-fail.rs`) diff --git a/tests/ui/proc-macro/module_with_attrs.rs b/tests/ui/proc-macro/module_with_attrs.rs index 8a4ca92e44b6c..7e4ec978736f1 100644 --- a/tests/ui/proc-macro/module_with_attrs.rs +++ b/tests/ui/proc-macro/module_with_attrs.rs @@ -1,4 +1,4 @@ -//@ ignore-test (auxiliary, used by other tests) +//@ ignore-auxiliary (used by `../inner-attr-non-inline-mod.rs`) #![rustfmt::skip] #![print_attr] diff --git a/tests/ui/proc-macro/outer/inner.rs b/tests/ui/proc-macro/outer/inner.rs index 210c05988bf23..d0f2087321f45 100644 --- a/tests/ui/proc-macro/outer/inner.rs +++ b/tests/ui/proc-macro/outer/inner.rs @@ -1 +1 @@ -//@ ignore-test (auxiliary, used by other tests) +//@ ignore-auxiliary (used by `../attributes-on-modules-fail.rs`) diff --git a/tests/ui/proc-macro/pretty-print-hack/allsorts-rental-0.5.6/src/lib.rs b/tests/ui/proc-macro/pretty-print-hack/allsorts-rental-0.5.6/src/lib.rs index f89098f3a5ecc..a27176a38e224 100644 --- a/tests/ui/proc-macro/pretty-print-hack/allsorts-rental-0.5.6/src/lib.rs +++ b/tests/ui/proc-macro/pretty-print-hack/allsorts-rental-0.5.6/src/lib.rs @@ -1,4 +1,4 @@ -//@ ignore-test (auxiliary, used by other tests) +//@ ignore-auxiliary (used by `../../../pretty-print-hack-show.rs`) #[derive(Print)] enum ProceduralMasqueradeDummyType { diff --git a/tests/ui/proc-macro/pretty-print-hack/rental-0.5.5/src/lib.rs b/tests/ui/proc-macro/pretty-print-hack/rental-0.5.5/src/lib.rs index f89098f3a5ecc..a27176a38e224 100644 --- a/tests/ui/proc-macro/pretty-print-hack/rental-0.5.5/src/lib.rs +++ b/tests/ui/proc-macro/pretty-print-hack/rental-0.5.5/src/lib.rs @@ -1,4 +1,4 @@ -//@ ignore-test (auxiliary, used by other tests) +//@ ignore-auxiliary (used by `../../../pretty-print-hack-show.rs`) #[derive(Print)] enum ProceduralMasqueradeDummyType { diff --git a/tests/ui/proc-macro/pretty-print-hack/rental-0.5.6/src/lib.rs b/tests/ui/proc-macro/pretty-print-hack/rental-0.5.6/src/lib.rs index f89098f3a5ecc..765ee4be656e3 100644 --- a/tests/ui/proc-macro/pretty-print-hack/rental-0.5.6/src/lib.rs +++ b/tests/ui/proc-macro/pretty-print-hack/rental-0.5.6/src/lib.rs @@ -1,4 +1,4 @@ -//@ ignore-test (auxiliary, used by other tests) +//@ ignore-auxiliary (used by `../../../pretty-print-hack/hide.rs`) #[derive(Print)] enum ProceduralMasqueradeDummyType { diff --git a/tests/ui/runtime/backtrace-debuginfo-aux.rs b/tests/ui/runtime/backtrace-debuginfo-aux.rs index 24180ed219665..4493fa51f9503 100644 --- a/tests/ui/runtime/backtrace-debuginfo-aux.rs +++ b/tests/ui/runtime/backtrace-debuginfo-aux.rs @@ -1,5 +1,4 @@ -//@ run-pass -//@ ignore-test: not a test, used by backtrace-debuginfo.rs to test file!() +//@ ignore-auxiliary (used by `./backtrace-debuginfo.rs` to test `file!()`) #[inline(never)] pub fn callback(f: F) where F: FnOnce((&'static str, u32)) { From 6c5a481f939d85b12f358b0be26dcf62aac568e0 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Thu, 17 Apr 2025 18:17:30 +0800 Subject: [PATCH 200/266] tests: remove unused auxiliaries under `tests/ui/directory_ownership/` --- tests/ui/directory_ownership/mod_file_not_owning_aux1.rs | 6 ------ tests/ui/directory_ownership/mod_file_not_owning_aux2.rs | 1 - tests/ui/directory_ownership/mod_file_not_owning_aux3.rs | 3 --- 3 files changed, 10 deletions(-) delete mode 100644 tests/ui/directory_ownership/mod_file_not_owning_aux1.rs delete mode 100644 tests/ui/directory_ownership/mod_file_not_owning_aux2.rs delete mode 100644 tests/ui/directory_ownership/mod_file_not_owning_aux3.rs diff --git a/tests/ui/directory_ownership/mod_file_not_owning_aux1.rs b/tests/ui/directory_ownership/mod_file_not_owning_aux1.rs deleted file mode 100644 index 6d6884fef0400..0000000000000 --- a/tests/ui/directory_ownership/mod_file_not_owning_aux1.rs +++ /dev/null @@ -1,6 +0,0 @@ -//@ ignore-test this is not a test - -macro_rules! m { - () => { mod mod_file_not_owning_aux2; } -} -m!(); diff --git a/tests/ui/directory_ownership/mod_file_not_owning_aux2.rs b/tests/ui/directory_ownership/mod_file_not_owning_aux2.rs deleted file mode 100644 index 76f1c1a727632..0000000000000 --- a/tests/ui/directory_ownership/mod_file_not_owning_aux2.rs +++ /dev/null @@ -1 +0,0 @@ -//@ ignore-test this is not a test diff --git a/tests/ui/directory_ownership/mod_file_not_owning_aux3.rs b/tests/ui/directory_ownership/mod_file_not_owning_aux3.rs deleted file mode 100644 index 96a5780d971f5..0000000000000 --- a/tests/ui/directory_ownership/mod_file_not_owning_aux3.rs +++ /dev/null @@ -1,3 +0,0 @@ -//@ ignore-test this is not a test - -mod mod_file_not_owning_aux2; From c1d21003bb6d9f1f1bd3f0e5f6edc453c602dcad Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 17 Apr 2025 08:34:54 -0400 Subject: [PATCH 201/266] Update to nightly-2025-04-17 --- rust-toolchain | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain b/rust-toolchain index 940b3de9f7453..fd898c59707b0 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2025-01-12" +channel = "nightly-2025-04-17" components = ["rust-src", "rustc-dev", "llvm-tools-preview"] From cc81c706e460c2d8a97a7006664136b62fd2c59e Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 27 Mar 2025 09:22:28 -0400 Subject: [PATCH 202/266] Fix patches --- ...022-core-Disable-not-compiling-tests.patch | 44 ------------------- ...0028-core-Disable-long-running-tests.patch | 26 +++++------ 2 files changed, 13 insertions(+), 57 deletions(-) delete mode 100644 patches/0022-core-Disable-not-compiling-tests.patch diff --git a/patches/0022-core-Disable-not-compiling-tests.patch b/patches/0022-core-Disable-not-compiling-tests.patch deleted file mode 100644 index 70e3e2ba7fee1..0000000000000 --- a/patches/0022-core-Disable-not-compiling-tests.patch +++ /dev/null @@ -1,44 +0,0 @@ -From af0e237f056fa838c77463381a19b0dc993c0a35 Mon Sep 17 00:00:00 2001 -From: None -Date: Sun, 1 Sep 2024 11:42:17 -0400 -Subject: [PATCH] Disable not compiling tests - ---- - library/core/tests/Cargo.toml | 14 ++++++++++++++ - library/core/tests/lib.rs | 1 + - 2 files changed, 15 insertions(+) - create mode 100644 library/core/tests/Cargo.toml - -diff --git a/library/core/tests/Cargo.toml b/library/core/tests/Cargo.toml -new file mode 100644 -index 0000000..ca326ac ---- /dev/null -+++ b/library/core/tests/Cargo.toml -@@ -0,0 +1,14 @@ -+[workspace] -+ -+[package] -+name = "coretests" -+version = "0.0.0" -+edition = "2021" -+ -+[lib] -+name = "coretests" -+path = "lib.rs" -+ -+[dependencies] -+rand = { version = "0.8.5", default-features = false } -+rand_xorshift = { version = "0.3.0", default-features = false } -diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs -index a4a7946..ecfe43f 100644 ---- a/library/core/tests/lib.rs -+++ b/library/core/tests/lib.rs -@@ -1,4 +1,5 @@ - // tidy-alphabetical-start -+#![cfg(test)] - #![cfg_attr(target_has_atomic = "128", feature(integer_atomics))] - #![cfg_attr(test, feature(cfg_match))] - #![feature(alloc_layout_extra)] --- -2.47.1 - diff --git a/patches/0028-core-Disable-long-running-tests.patch b/patches/0028-core-Disable-long-running-tests.patch index dc1beae6d2e71..20df4245cfdf2 100644 --- a/patches/0028-core-Disable-long-running-tests.patch +++ b/patches/0028-core-Disable-long-running-tests.patch @@ -1,17 +1,17 @@ -From eb703e627e7a84f1cd8d0d87f0f69da1f0acf765 Mon Sep 17 00:00:00 2001 -From: bjorn3 -Date: Fri, 3 Dec 2021 12:16:30 +0100 +From ec2d0dc77fb484d926b45bb626b0db6a4bb0ab5c Mon Sep 17 00:00:00 2001 +From: None +Date: Thu, 27 Mar 2025 09:20:41 -0400 Subject: [PATCH] Disable long running tests --- - library/core/tests/slice.rs | 2 ++ + library/coretests/tests/slice.rs | 2 ++ 1 file changed, 2 insertions(+) -diff --git a/library/core/tests/slice.rs b/library/core/tests/slice.rs -index 8402833..84592e0 100644 ---- a/library/core/tests/slice.rs -+++ b/library/core/tests/slice.rs -@@ -2462,6 +2462,7 @@ take_tests! { +diff --git a/library/coretests/tests/slice.rs b/library/coretests/tests/slice.rs +index d17e681..fba5cd6 100644 +--- a/library/coretests/tests/slice.rs ++++ b/library/coretests/tests/slice.rs +@@ -2486,6 +2486,7 @@ split_off_tests! { #[cfg(not(miri))] // unused in Miri const EMPTY_MAX: &'static [()] = &[(); usize::MAX]; @@ -19,14 +19,14 @@ index 8402833..84592e0 100644 // can't be a constant due to const mutability rules #[cfg(not(miri))] // unused in Miri macro_rules! empty_max_mut { -@@ -2485,6 +2486,7 @@ take_tests! { - (take_mut_oob_max_range_to_inclusive, (..=usize::MAX), None, empty_max_mut!()), - (take_mut_in_bounds_max_range_from, (usize::MAX..), Some(&mut [] as _), empty_max_mut!()), +@@ -2509,6 +2510,7 @@ split_off_tests! { + (split_off_mut_oob_max_range_to_inclusive, (..=usize::MAX), None, empty_max_mut!()), + (split_off_mut_in_bounds_max_range_from, (usize::MAX..), Some(&mut [] as _), empty_max_mut!()), } +*/ #[test] fn test_slice_from_ptr_range() { -- -2.26.2.7.g19db9cfb68 +2.49.0 From be75a58538154cbe901efea7807d7830d3d064c4 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 13 Apr 2025 07:48:56 -0400 Subject: [PATCH 203/266] Fix compilation --- src/abi.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/abi.rs b/src/abi.rs index 1f522f64c9cf9..3b0ab9f004264 100644 --- a/src/abi.rs +++ b/src/abi.rs @@ -9,7 +9,7 @@ use rustc_middle::ty::Ty; use rustc_middle::ty::layout::LayoutOf; #[cfg(feature = "master")] use rustc_session::config; -use rustc_target::abi::call::{ArgAttributes, CastTarget, FnAbi, PassMode}; +use rustc_target::callconv::{ArgAttributes, CastTarget, FnAbi, PassMode}; #[cfg(feature = "master")] use rustc_target::callconv::Conv; @@ -239,7 +239,7 @@ impl<'gcc, 'tcx> FnAbiGccExt<'gcc, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { } #[cfg(feature = "master")] -pub fn conv_to_fn_attribute<'gcc>(conv: Conv, _arch: &str) -> Option> { +pub fn conv_to_fn_attribute<'gcc>(conv: Conv, arch: &str) -> Option> { // TODO: handle the calling conventions returning None. let attribute = match conv { Conv::C @@ -250,20 +250,19 @@ pub fn conv_to_fn_attribute<'gcc>(conv: Conv, _arch: &str) -> Option return None, Conv::PreserveMost => return None, Conv::PreserveAll => return None, - /*Conv::GpuKernel => { + Conv::GpuKernel => { if arch == "amdgpu" { return None } else if arch == "nvptx64" { return None } else { - panic!("Architecture {arch} does not support GpuKernel calling convention"); + panic!("Architecture {} does not support GpuKernel calling convention", arch); } - }*/ + } Conv::AvrInterrupt => return None, Conv::AvrNonBlockingInterrupt => return None, Conv::ArmAapcs => return None, Conv::Msp430Intr => return None, - Conv::PtxKernel => return None, Conv::X86Fastcall => return None, Conv::X86Intr => return None, Conv::X86Stdcall => return None, From 5c832e5ece3c55295bbc8c9f58962a2a57e75147 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 27 Mar 2025 14:28:56 -0400 Subject: [PATCH 204/266] Remove most of builtins hack since it's not necessary anymore --- src/context.rs | 28 +--------------------------- 1 file changed, 1 insertion(+), 27 deletions(-) diff --git a/src/context.rs b/src/context.rs index 964f1f265591e..73718994e6417 100644 --- a/src/context.rs +++ b/src/context.rs @@ -215,33 +215,7 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { let bool_type = context.new_type::(); let mut functions = FxHashMap::default(); - let builtins = [ - "__builtin_unreachable", - "abort", - "__builtin_expect", /*"__builtin_expect_with_probability",*/ - "__builtin_constant_p", - "__builtin_add_overflow", - "__builtin_mul_overflow", - "__builtin_saddll_overflow", - /*"__builtin_sadd_overflow",*/ - "__builtin_smulll_overflow", /*"__builtin_smul_overflow",*/ - "__builtin_ssubll_overflow", - /*"__builtin_ssub_overflow",*/ "__builtin_sub_overflow", - "__builtin_uaddll_overflow", - "__builtin_uadd_overflow", - "__builtin_umulll_overflow", - "__builtin_umul_overflow", - "__builtin_usubll_overflow", - "__builtin_usub_overflow", - "__builtin_powif", - "__builtin_powi", - "fabsf", - "fabs", - "copysignf", - "copysign", - "nearbyintf", - "nearbyint", - ]; + let builtins = ["abort"]; for builtin in builtins.iter() { functions.insert(builtin.to_string(), context.get_builtin_function(builtin)); From e1fa74b4a9ed699d0abf3c98113b3cc11baa81d6 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 27 Mar 2025 12:14:14 -0400 Subject: [PATCH 205/266] Implement copysignf128 --- src/intrinsic/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/intrinsic/mod.rs b/src/intrinsic/mod.rs index f38622074f18b..d22f4229e2374 100644 --- a/src/intrinsic/mod.rs +++ b/src/intrinsic/mod.rs @@ -78,6 +78,7 @@ fn get_simple_intrinsic<'gcc, 'tcx>( sym::maxnumf64 => "fmax", sym::copysignf32 => "copysignf", sym::copysignf64 => "copysign", + sym::copysignf128 => "copysignl", sym::floorf32 => "floorf", sym::floorf64 => "floor", sym::ceilf32 => "ceilf", From 9a453d46f42c40b91d004064a4cc12f7c28c7fc7 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 27 Mar 2025 14:33:03 -0400 Subject: [PATCH 206/266] Update other patches --- ...001-Disable-libstd-and-libtest-dylib.patch | 18 ++++++----- ...0001-core-Disable-portable-simd-test.patch | 32 ++++++++----------- 2 files changed, 23 insertions(+), 27 deletions(-) diff --git a/patches/cross_patches/0001-Disable-libstd-and-libtest-dylib.patch b/patches/cross_patches/0001-Disable-libstd-and-libtest-dylib.patch index c220f53040f05..fa360fe9e74e7 100644 --- a/patches/cross_patches/0001-Disable-libstd-and-libtest-dylib.patch +++ b/patches/cross_patches/0001-Disable-libstd-and-libtest-dylib.patch @@ -1,19 +1,18 @@ -From 966beefe08be6045bfcca26079b76a7a80413080 Mon Sep 17 00:00:00 2001 +From b2911e732d1bf0e28872495c4c47af1dad3c7911 Mon Sep 17 00:00:00 2001 From: None -Date: Thu, 28 Sep 2023 17:37:38 -0400 +Date: Thu, 27 Mar 2025 14:30:10 -0400 Subject: [PATCH] Disable libstd and libtest dylib --- - library/std/Cargo.toml | 2 +- - library/test/Cargo.toml | 2 +- - 2 files changed, 2 insertions(+), 2 deletions(-) + library/std/Cargo.toml | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/Cargo.toml b/library/std/Cargo.toml -index 5b21355..cb0c49b 100644 +index 176da60..c183cdb 100644 --- a/library/std/Cargo.toml +++ b/library/std/Cargo.toml -@@ -9,7 +9,7 @@ description = "The Rust Standard Library" - edition = "2021" +@@ -10,7 +10,7 @@ edition = "2024" + autobenches = false [lib] -crate-type = ["dylib", "rlib"] @@ -21,3 +20,6 @@ index 5b21355..cb0c49b 100644 [dependencies] alloc = { path = "../alloc", public = true } +-- +2.49.0 + diff --git a/patches/libgccjit12/0001-core-Disable-portable-simd-test.patch b/patches/libgccjit12/0001-core-Disable-portable-simd-test.patch index 9ef5e0e4f4672..9d5b2dc537d2c 100644 --- a/patches/libgccjit12/0001-core-Disable-portable-simd-test.patch +++ b/patches/libgccjit12/0001-core-Disable-portable-simd-test.patch @@ -1,25 +1,17 @@ -From 124a11ce086952a5794d5cfbaa45175809497b81 Mon Sep 17 00:00:00 2001 +From 1a8f6b8e39f343959d4d2e6b6957a6d780ac3fc0 Mon Sep 17 00:00:00 2001 From: None -Date: Sat, 18 Nov 2023 10:50:36 -0500 -Subject: [PATCH] [core] Disable portable-simd test +Date: Thu, 27 Mar 2025 14:32:14 -0400 +Subject: [PATCH] Disable portable-simd test --- - library/core/tests/lib.rs | 2 -- - 1 file changed, 2 deletions(-) + library/coretests/tests/lib.rs | 1 - + 1 file changed, 1 deletion(-) -diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs -index b71786c..cf484d5 100644 ---- a/library/core/tests/lib.rs -+++ b/library/core/tests/lib.rs -@@ -87,7 +87,6 @@ - #![feature(numfmt)] - #![feature(pattern)] - #![feature(pointer_is_aligned_to)] --#![feature(portable_simd)] - #![feature(ptr_metadata)] - #![feature(slice_from_ptr_range)] - #![feature(slice_internals)] -@@ -155,7 +154,6 @@ mod pin; +diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs +index 79022fe..9223b2f 100644 +--- a/library/coretests/tests/lib.rs ++++ b/library/coretests/tests/lib.rs +@@ -165,7 +165,6 @@ mod pin; mod pin_macro; mod ptr; mod result; @@ -27,4 +19,6 @@ index b71786c..cf484d5 100644 mod slice; mod str; mod str_lossy; --- 2.45.2 +-- +2.49.0 + From f9822772e8781ed30a89aa4494e47c42b4397133 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 27 Mar 2025 14:33:38 -0400 Subject: [PATCH 207/266] Fix libcore tests --- build_system/src/test.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build_system/src/test.rs b/build_system/src/test.rs index 297cd7d71316e..df4ac85233b02 100644 --- a/build_system/src/test.rs +++ b/build_system/src/test.rs @@ -678,7 +678,7 @@ fn test_projects(env: &Env, args: &TestArg) -> Result<(), String> { fn test_libcore(env: &Env, args: &TestArg) -> Result<(), String> { // FIXME: create a function "display_if_not_quiet" or something along the line. println!("[TEST] libcore"); - let path = get_sysroot_dir().join("sysroot_src/library/core/tests"); + let path = get_sysroot_dir().join("sysroot_src/library/coretests"); let _ = remove_dir_all(path.join("target")); run_cargo_command(&[&"test"], Some(&path), env, args)?; Ok(()) From 5cf2bbc4e2c82961f2e82fbacc39fcf5f332e371 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 27 Mar 2025 14:34:44 -0400 Subject: [PATCH 208/266] Fix clippy warnings --- src/abi.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/abi.rs b/src/abi.rs index 3b0ab9f004264..6fdb03fb85b57 100644 --- a/src/abi.rs +++ b/src/abi.rs @@ -251,6 +251,8 @@ pub fn conv_to_fn_attribute<'gcc>(conv: Conv, arch: &str) -> Option return None, Conv::PreserveAll => return None, Conv::GpuKernel => { + // TODO(antoyo): remove clippy allow attribute when this is implemented. + #[allow(clippy::if_same_then_else)] if arch == "amdgpu" { return None } else if arch == "nvptx64" { From ecf0a1eea3714a9c9f79bf1f3a53e6feb6c631f5 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 13 Apr 2025 08:28:02 -0400 Subject: [PATCH 209/266] Update GCC version --- libgccjit.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libgccjit.version b/libgccjit.version index dfdc222c00fcb..125b04004b07f 100644 --- a/libgccjit.version +++ b/libgccjit.version @@ -1 +1 @@ -d6f5a708104a98199ac0f01a3b6b279a0f7c66d3 +0ea98a1365b81f7488073512c850e8ee951a4afd From ec44cfdfb4a74d19f522984e2e2e226a3b76df9a Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 27 Mar 2025 15:28:31 -0400 Subject: [PATCH 210/266] Fix tests --- example/mini_core.rs | 16 ++++++++++++++++ tests/run/abort1.rs | 2 +- tests/run/abort2.rs | 2 +- tests/run/assign.rs | 2 +- tests/run/closure.rs | 2 +- tests/run/mut_ref.rs | 2 +- tests/run/static.rs | 2 +- 7 files changed, 22 insertions(+), 6 deletions(-) diff --git a/example/mini_core.rs b/example/mini_core.rs index 32501530cfac1..c554a87b8256c 100644 --- a/example/mini_core.rs +++ b/example/mini_core.rs @@ -138,6 +138,14 @@ impl Mul for u8 { } } +impl Mul for i32 { + type Output = Self; + + fn mul(self, rhs: Self) -> Self::Output { + self * rhs + } +} + impl Mul for usize { type Output = Self; @@ -248,6 +256,14 @@ impl Sub for i16 { } } +impl Sub for i32 { + type Output = Self; + + fn sub(self, rhs: Self) -> Self { + self - rhs + } +} + #[lang = "rem"] pub trait Rem { type Output; diff --git a/tests/run/abort1.rs b/tests/run/abort1.rs index ae7e457d1cd3f..ff2bb75ece22a 100644 --- a/tests/run/abort1.rs +++ b/tests/run/abort1.rs @@ -3,7 +3,7 @@ // Run-time: // status: signal -#![feature(no_core, start)] +#![feature(no_core)] #![no_std] #![no_core] #![no_main] diff --git a/tests/run/abort2.rs b/tests/run/abort2.rs index 28fad0107f759..781f518e0b222 100644 --- a/tests/run/abort2.rs +++ b/tests/run/abort2.rs @@ -3,7 +3,7 @@ // Run-time: // status: signal -#![feature(no_core, start)] +#![feature(no_core)] #![no_std] #![no_core] #![no_main] diff --git a/tests/run/assign.rs b/tests/run/assign.rs index a54d0b20def3b..4535ab5778e93 100644 --- a/tests/run/assign.rs +++ b/tests/run/assign.rs @@ -23,7 +23,7 @@ fn inc(num: isize) -> isize { } #[no_mangle] -extern "C" fn main(mut argc: i32, _argv: *const *const u8) -> i32 { +extern "C" fn main(mut argc: isize, _argv: *const *const u8) -> i32 { argc = inc(argc); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc); diff --git a/tests/run/closure.rs b/tests/run/closure.rs index b827a26140020..a8a3fadfed47b 100644 --- a/tests/run/closure.rs +++ b/tests/run/closure.rs @@ -17,7 +17,7 @@ extern crate mini_core; use mini_core::*; #[no_mangle] -extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { +extern "C" fn main(argc: isize, _argv: *const *const u8) -> i32 { let string = "Arg: %d\n\0"; let mut closure = || unsafe { libc::printf(string as *const str as *const i8, argc); diff --git a/tests/run/mut_ref.rs b/tests/run/mut_ref.rs index 5fa5df751a32f..fa50d5bc5d3d3 100644 --- a/tests/run/mut_ref.rs +++ b/tests/run/mut_ref.rs @@ -27,7 +27,7 @@ fn update_num(num: &mut isize) { } #[no_mangle] -extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { +extern "C" fn main(mut argc: isize, _argv: *const *const u8) -> i32 { let mut test = test(argc); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field); diff --git a/tests/run/static.rs b/tests/run/static.rs index c58151f8417b5..1e36cf4f3d316 100644 --- a/tests/run/static.rs +++ b/tests/run/static.rs @@ -34,7 +34,7 @@ static mut TEST2: Test = Test { field: 14 }; static mut WITH_REF: WithRef = WithRef { refe: unsafe { &TEST } }; #[no_mangle] -extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { +extern "C" fn main(argc: isize, _argv: *const *const u8) -> i32 { unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, CONSTANT); libc::printf(b"%ld\n\0" as *const u8 as *const i8, TEST2.field); From bc0bc8d5e1a1a38ee5a342e614e490e490bc5604 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 27 Mar 2025 15:36:15 -0400 Subject: [PATCH 211/266] Fix int_to_float_cast for f128 --- src/int.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/int.rs b/src/int.rs index f3552d9b12fcb..b5fcb534747d2 100644 --- a/src/int.rs +++ b/src/int.rs @@ -905,6 +905,7 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { let name_suffix = match self.type_kind(dest_typ) { TypeKind::Float => "tisf", TypeKind::Double => "tidf", + TypeKind::FP128 => "tixf", kind => panic!("cannot cast a non-native integer to type {:?}", kind), }; let sign = if signed { "" } else { "un" }; From 6504f4c09ce9e3c72084e647fab8e6565d79573e Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 13 Apr 2025 08:40:42 -0400 Subject: [PATCH 212/266] Format --- src/abi.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/abi.rs b/src/abi.rs index 6fdb03fb85b57..a96b18e01c087 100644 --- a/src/abi.rs +++ b/src/abi.rs @@ -9,9 +9,9 @@ use rustc_middle::ty::Ty; use rustc_middle::ty::layout::LayoutOf; #[cfg(feature = "master")] use rustc_session::config; -use rustc_target::callconv::{ArgAttributes, CastTarget, FnAbi, PassMode}; #[cfg(feature = "master")] use rustc_target::callconv::Conv; +use rustc_target::callconv::{ArgAttributes, CastTarget, FnAbi, PassMode}; use crate::builder::Builder; use crate::context::CodegenCx; @@ -254,9 +254,9 @@ pub fn conv_to_fn_attribute<'gcc>(conv: Conv, arch: &str) -> Option Date: Sun, 13 Apr 2025 08:58:32 -0400 Subject: [PATCH 213/266] Fix tests --- tests/failing-ui-tests.txt | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tests/failing-ui-tests.txt b/tests/failing-ui-tests.txt index 0babc748f98b9..12dc7f726aab7 100644 --- a/tests/failing-ui-tests.txt +++ b/tests/failing-ui-tests.txt @@ -31,7 +31,6 @@ tests/ui/unwind-no-uwtable.rs tests/ui/parser/unclosed-delimiter-in-dep.rs tests/ui/consts/missing_span_in_backtrace.rs tests/ui/drop/dynamic-drop.rs -tests/ui/issues/issue-40883.rs tests/ui/issues/issue-43853.rs tests/ui/issues/issue-47364.rs tests/ui/macros/rfc-2011-nicer-assert-messages/assert-without-captures-does-not-create-unnecessary-code.rs @@ -100,14 +99,12 @@ tests/ui/codegen/equal-pointers-unequal/as-cast/basic.rs tests/ui/codegen/equal-pointers-unequal/as-cast/inline1.rs tests/ui/codegen/equal-pointers-unequal/as-cast/print.rs tests/ui/codegen/equal-pointers-unequal/as-cast/inline2.rs -tests/ui/codegen/equal-pointers-unequal/as-cast/print3.rs tests/ui/codegen/equal-pointers-unequal/as-cast/segfault.rs tests/ui/codegen/equal-pointers-unequal/exposed-provenance/function.rs tests/ui/codegen/equal-pointers-unequal/exposed-provenance/basic.rs tests/ui/codegen/equal-pointers-unequal/as-cast/zero.rs tests/ui/codegen/equal-pointers-unequal/exposed-provenance/inline1.rs tests/ui/codegen/equal-pointers-unequal/exposed-provenance/print.rs -tests/ui/codegen/equal-pointers-unequal/exposed-provenance/print3.rs tests/ui/codegen/equal-pointers-unequal/exposed-provenance/inline2.rs tests/ui/codegen/equal-pointers-unequal/exposed-provenance/segfault.rs tests/ui/codegen/equal-pointers-unequal/exposed-provenance/zero.rs @@ -115,8 +112,8 @@ tests/ui/codegen/equal-pointers-unequal/strict-provenance/basic.rs tests/ui/codegen/equal-pointers-unequal/strict-provenance/function.rs tests/ui/codegen/equal-pointers-unequal/strict-provenance/print.rs tests/ui/codegen/equal-pointers-unequal/strict-provenance/inline1.rs -tests/ui/codegen/equal-pointers-unequal/strict-provenance/print3.rs tests/ui/codegen/equal-pointers-unequal/strict-provenance/inline2.rs tests/ui/codegen/equal-pointers-unequal/strict-provenance/segfault.rs tests/ui/codegen/equal-pointers-unequal/strict-provenance/zero.rs tests/ui/simd/simd-bitmask-notpow2.rs +tests/ui/codegen/StackColoring-not-blowup-stack-issue-40883.rs From 0d773175cc41901f1a558a9b45239c67c3fa0df6 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 13 Apr 2025 10:25:10 -0400 Subject: [PATCH 214/266] Add support for simd_insert_dyn and simd_extract_dyn --- src/intrinsic/simd.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/intrinsic/simd.rs b/src/intrinsic/simd.rs index 8b454ab2a4241..6d40d5297f1a0 100644 --- a/src/intrinsic/simd.rs +++ b/src/intrinsic/simd.rs @@ -399,7 +399,7 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( } #[cfg(feature = "master")] - if name == sym::simd_insert { + if name == sym::simd_insert || name == sym::simd_insert_dyn { require!( in_elem == arg_tys[2], InvalidMonomorphization::InsertedType { @@ -410,6 +410,8 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( out_ty: arg_tys[2] } ); + + // TODO(antoyo): For simd_insert, check if the index is a constant of the correct size. let vector = args[0].immediate(); let index = args[1].immediate(); let value = args[2].immediate(); @@ -422,13 +424,15 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( } #[cfg(feature = "master")] - if name == sym::simd_extract { + if name == sym::simd_extract || name == sym::simd_extract_dyn { require!( ret_ty == in_elem, InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } ); + // TODO(antoyo): For simd_extract, check if the index is a constant of the correct size. let vector = args[0].immediate(); - return Ok(bx.context.new_vector_access(None, vector, args[1].immediate()).to_rvalue()); + let index = args[1].immediate(); + return Ok(bx.context.new_vector_access(None, vector, index).to_rvalue()); } if name == sym::simd_select { From 4b5940ad77cf9a95cf78bef1ecc6fa84ef1fc0ce Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 15 Apr 2025 12:51:28 -0400 Subject: [PATCH 215/266] Fix overflow operations --- src/int.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/int.rs b/src/int.rs index b5fcb534747d2..9b5b0fde6e2f1 100644 --- a/src/int.rs +++ b/src/int.rs @@ -404,7 +404,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let ret_indirect = matches!(fn_abi.ret.mode, PassMode::Indirect { .. }); - let result = if ret_indirect { + let call = if ret_indirect { let res_value = self.current_func().new_local(self.location, res_type, "result_value"); let res_addr = res_value.get_address(self.location); let res_param_type = res_type.make_pointer(); @@ -432,8 +432,17 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { ); self.context.new_call(self.location, func, &[lhs, rhs, overflow_addr]) }; - - (result, self.context.new_cast(self.location, overflow_value, self.bool_type).to_rvalue()) + // NOTE: we must assign the result of the operation to a variable at this point to make + // sure it will be evaluated by libgccjit now. + // Otherwise, it will only be evaluated when the rvalue for the call is used somewhere else + // and overflow_value will not be initialized at the correct point in the program. + let result = self.current_func().new_local(self.location, res_type, "result"); + self.block.add_assignment(self.location, result, call); + + ( + result.to_rvalue(), + self.context.new_cast(self.location, overflow_value, self.bool_type).to_rvalue(), + ) } pub fn gcc_icmp( @@ -865,6 +874,7 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { let value_type = value.get_type(); if self.is_native_int_type_or_bool(dest_typ) && self.is_native_int_type_or_bool(value_type) { + // TODO: use self.location. self.context.new_cast(None, value, dest_typ) } else if self.is_native_int_type_or_bool(dest_typ) { self.context.new_cast(None, self.low(value), dest_typ) From 06af88e06cd464809bbe3c2ab073d2d575d185e6 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 15 Apr 2025 13:28:27 -0400 Subject: [PATCH 216/266] Add new failing test --- tests/failing-ui-tests.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/failing-ui-tests.txt b/tests/failing-ui-tests.txt index 12dc7f726aab7..499c1a962311c 100644 --- a/tests/failing-ui-tests.txt +++ b/tests/failing-ui-tests.txt @@ -117,3 +117,4 @@ tests/ui/codegen/equal-pointers-unequal/strict-provenance/segfault.rs tests/ui/codegen/equal-pointers-unequal/strict-provenance/zero.rs tests/ui/simd/simd-bitmask-notpow2.rs tests/ui/codegen/StackColoring-not-blowup-stack-issue-40883.rs +tests/ui/uninhabited/uninhabited-transparent-return-abi.rs From 8562110e0d8ef293563200d15d466c012e936ff7 Mon Sep 17 00:00:00 2001 From: xizheyin Date: Tue, 15 Apr 2025 15:03:11 +0800 Subject: [PATCH 217/266] Hide unstable print kinds within emit_unknown_print_request_help in stable channel Signed-off-by: xizheyin --- compiler/rustc_session/src/config.rs | 37 +++++++++++++------ .../help-diff.diff | 7 ++++ .../rmake.rs | 33 +++++++++++++++++ .../stable-invalid-print-request-help.err | 5 +++ .../unstable-invalid-print-request-help.err | 5 +++ 5 files changed, 75 insertions(+), 12 deletions(-) create mode 100644 tests/run-make/print-request-help-stable-unstable/help-diff.diff create mode 100644 tests/run-make/print-request-help-stable-unstable/rmake.rs create mode 100644 tests/run-make/print-request-help-stable-unstable/stable-invalid-print-request-help.err create mode 100644 tests/run-make/print-request-help-stable-unstable/unstable-invalid-print-request-help.err diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index bdd54a15147b4..d00c08739619a 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -2069,7 +2069,8 @@ fn collect_print_requests( check_print_request_stability(early_dcx, unstable_opts, (print_name, *print_kind)); *print_kind } else { - emit_unknown_print_request_help(early_dcx, req) + let is_nightly = nightly_options::match_is_nightly_build(matches); + emit_unknown_print_request_help(early_dcx, req, is_nightly) }; let out = out.unwrap_or(OutFileName::Stdout); @@ -2093,25 +2094,37 @@ fn check_print_request_stability( unstable_opts: &UnstableOptions, (print_name, print_kind): (&str, PrintKind), ) { + if !is_print_request_stable(print_kind) && !unstable_opts.unstable_options { + early_dcx.early_fatal(format!( + "the `-Z unstable-options` flag must also be passed to enable the `{print_name}` \ + print option" + )); + } +} + +fn is_print_request_stable(print_kind: PrintKind) -> bool { match print_kind { PrintKind::AllTargetSpecsJson | PrintKind::CheckCfg | PrintKind::CrateRootLintLevels | PrintKind::SupportedCrateTypes - | PrintKind::TargetSpecJson - if !unstable_opts.unstable_options => - { - early_dcx.early_fatal(format!( - "the `-Z unstable-options` flag must also be passed to enable the `{print_name}` \ - print option" - )); - } - _ => {} + | PrintKind::TargetSpecJson => false, + _ => true, } } -fn emit_unknown_print_request_help(early_dcx: &EarlyDiagCtxt, req: &str) -> ! { - let prints = PRINT_KINDS.iter().map(|(name, _)| format!("`{name}`")).collect::>(); +fn emit_unknown_print_request_help(early_dcx: &EarlyDiagCtxt, req: &str, is_nightly: bool) -> ! { + let prints = PRINT_KINDS + .iter() + .filter_map(|(name, kind)| { + // If we're not on nightly, we don't want to print unstable options + if !is_nightly && !is_print_request_stable(*kind) { + None + } else { + Some(format!("`{name}`")) + } + }) + .collect::>(); let prints = prints.join(", "); let mut diag = early_dcx.early_struct_fatal(format!("unknown print request: `{req}`")); 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 new file mode 100644 index 0000000000000..07eafca327108 --- /dev/null +++ b/tests/run-make/print-request-help-stable-unstable/help-diff.diff @@ -0,0 +1,7 @@ +@@ -1,5 +1,5 @@ + 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: 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/rmake.rs b/tests/run-make/print-request-help-stable-unstable/rmake.rs new file mode 100644 index 0000000000000..a59963da5c497 --- /dev/null +++ b/tests/run-make/print-request-help-stable-unstable/rmake.rs @@ -0,0 +1,33 @@ +//! Check that unstable print requests are omitted from help if compiler is in stable channel. +//! +//! Issue: +use run_make_support::{diff, rustc, similar}; + +fn main() { + let stable_invalid_print_request_help = rustc() + .env("RUSTC_BOOTSTRAP", "-1") + .cfg("force_stable") + .print("xxx") + .run_fail() + .stderr_utf8(); + assert!(!stable_invalid_print_request_help.contains("all-target-specs-json")); + diff() + .expected_file("stable-invalid-print-request-help.err") + .actual_text("stable_invalid_print_request_help", &stable_invalid_print_request_help) + .run(); + + let unstable_invalid_print_request_help = rustc().print("xxx").run_fail().stderr_utf8(); + assert!(unstable_invalid_print_request_help.contains("all-target-specs-json")); + diff() + .expected_file("unstable-invalid-print-request-help.err") + .actual_text("unstable_invalid_print_request_help", &unstable_invalid_print_request_help) + .run(); + + let help_diff = similar::TextDiff::from_lines( + &stable_invalid_print_request_help, + &unstable_invalid_print_request_help, + ) + .unified_diff() + .to_string(); + diff().expected_file("help-diff.diff").actual_text("help_diff", help_diff).run(); +} diff --git a/tests/run-make/print-request-help-stable-unstable/stable-invalid-print-request-help.err b/tests/run-make/print-request-help-stable-unstable/stable-invalid-print-request-help.err new file mode 100644 index 0000000000000..019a578dad3e0 --- /dev/null +++ b/tests/run-make/print-request-help-stable-unstable/stable-invalid-print-request-help.err @@ -0,0 +1,5 @@ +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: 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 new file mode 100644 index 0000000000000..50ef340e3dd02 --- /dev/null +++ b/tests/run-make/print-request-help-stable-unstable/unstable-invalid-print-request-help.err @@ -0,0 +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: for more information, see the rustc book: https://doc.rust-lang.org/rustc/command-line-arguments.html#--print-print-compiler-information + From 7a5a884275b0bdbd28397c814b45f71d10b45439 Mon Sep 17 00:00:00 2001 From: Lukas Woodtli Date: Thu, 17 Apr 2025 16:07:12 +0200 Subject: [PATCH 218/266] Make C string merging test work on MIPS Assembly for MIPS uses, by convention, a different prefix for local anonymous variables. --- tests/assembly/cstring-merging.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/assembly/cstring-merging.rs b/tests/assembly/cstring-merging.rs index b5c530ac35d76..f7d0775f7affd 100644 --- a/tests/assembly/cstring-merging.rs +++ b/tests/assembly/cstring-merging.rs @@ -1,3 +1,5 @@ +// MIPS assembler uses the label prefix `$anon.` for local anonymous variables +// other architectures (including ARM and x86-64) use the prefix `.Lanon.` //@ only-linux //@ assembly-output: emit-asm //@ compile-flags: --crate-type=lib -Copt-level=3 @@ -6,13 +8,13 @@ use std::ffi::CStr; // CHECK: .section .rodata.str1.{{[12]}},"aMS" -// CHECK: .Lanon.{{.+}}: +// CHECK: {{(\.L|\$)}}anon.{{.+}}: // CHECK-NEXT: .asciz "foo" #[unsafe(no_mangle)] static CSTR: &[u8; 4] = b"foo\0"; // CHECK-NOT: .section -// CHECK: .Lanon.{{.+}}: +// CHECK: {{(\.L|\$)}}anon.{{.+}}: // CHECK-NEXT: .asciz "bar" #[unsafe(no_mangle)] pub fn cstr() -> &'static CStr { @@ -20,7 +22,7 @@ pub fn cstr() -> &'static CStr { } // CHECK-NOT: .section -// CHECK: .Lanon.{{.+}}: +// CHECK: {{(\.L|\$)}}anon.{{.+}}: // CHECK-NEXT: .asciz "baz" #[unsafe(no_mangle)] pub fn manual_cstr() -> &'static str { From d14df2652df492fe0f19c5e0ae5041b39b5a4d20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 16 Apr 2025 13:24:01 +0200 Subject: [PATCH 219/266] Make `parent` in `download_auto_job_metrics` optional --- src/ci/citool/src/main.rs | 2 +- src/ci/citool/src/metrics.rs | 23 ++++++++++++----------- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/ci/citool/src/main.rs b/src/ci/citool/src/main.rs index a1956da352f5c..0fee862f5721b 100644 --- a/src/ci/citool/src/main.rs +++ b/src/ci/citool/src/main.rs @@ -180,7 +180,7 @@ fn postprocess_metrics( } fn post_merge_report(db: JobDatabase, current: String, parent: String) -> anyhow::Result<()> { - let metrics = download_auto_job_metrics(&db, &parent, ¤t)?; + let metrics = download_auto_job_metrics(&db, Some(&parent), ¤t)?; println!("\nComparing {parent} (parent) -> {current} (this PR)\n"); diff --git a/src/ci/citool/src/metrics.rs b/src/ci/citool/src/metrics.rs index a816fb3c4f165..3d8b1ad84cf72 100644 --- a/src/ci/citool/src/metrics.rs +++ b/src/ci/citool/src/metrics.rs @@ -46,24 +46,25 @@ pub struct JobMetrics { /// `parent` and `current` should be commit SHAs. pub fn download_auto_job_metrics( job_db: &JobDatabase, - parent: &str, + parent: Option<&str>, current: &str, ) -> anyhow::Result> { let mut jobs = HashMap::default(); for job in &job_db.auto_jobs { eprintln!("Downloading metrics of job {}", job.name); - let metrics_parent = match download_job_metrics(&job.name, parent) { - Ok(metrics) => Some(metrics), - Err(error) => { - eprintln!( - r#"Did not find metrics for job `{}` at `{parent}`: {error:?}. + let metrics_parent = + parent.and_then(|parent| match download_job_metrics(&job.name, parent) { + Ok(metrics) => Some(metrics), + Err(error) => { + eprintln!( + r#"Did not find metrics for job `{}` at `{parent}`: {error:?}. Maybe it was newly added?"#, - job.name - ); - None - } - }; + job.name + ); + None + } + }); let metrics_current = download_job_metrics(&job.name, current)?; jobs.insert( job.name.clone(), From 111c15c48e618b30a0cf11d91b135d87d73053a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 16 Apr 2025 17:20:53 +0200 Subject: [PATCH 220/266] Extract function for normalizing path delimiters to `utils` --- src/ci/citool/src/analysis.rs | 13 ++++++------- src/ci/citool/src/utils.rs | 6 ++++++ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/ci/citool/src/analysis.rs b/src/ci/citool/src/analysis.rs index 9fc7c309bfbdc..62974be2dbe8c 100644 --- a/src/ci/citool/src/analysis.rs +++ b/src/ci/citool/src/analysis.rs @@ -8,9 +8,9 @@ use build_helper::metrics::{ }; use crate::github::JobInfoResolver; -use crate::metrics; use crate::metrics::{JobMetrics, JobName, get_test_suites}; use crate::utils::{output_details, pluralize}; +use crate::{metrics, utils}; /// Outputs durations of individual bootstrap steps from the gathered bootstrap invocations, /// and also a table with summarized information about executed tests. @@ -394,18 +394,17 @@ fn aggregate_tests(metrics: &JsonRoot) -> TestSuiteData { // Poor man's detection of doctests based on the "(line XYZ)" suffix let is_doctest = matches!(suite.metadata, TestSuiteMetadata::CargoPackage { .. }) && test.name.contains("(line"); - let test_entry = Test { name: generate_test_name(&test.name), stage, is_doctest }; + let test_entry = Test { + name: utils::normalize_path_delimiters(&test.name).to_string(), + stage, + is_doctest, + }; tests.insert(test_entry, test.outcome.clone()); } } TestSuiteData { tests } } -/// Normalizes Windows-style path delimiters to Unix-style paths. -fn generate_test_name(name: &str) -> String { - name.replace('\\', "/") -} - /// Prints test changes in Markdown format to stdout. fn report_test_diffs( diff: AggregatedTestDiffs, diff --git a/src/ci/citool/src/utils.rs b/src/ci/citool/src/utils.rs index a4c6ff85ef73c..0367d349a1ef4 100644 --- a/src/ci/citool/src/utils.rs +++ b/src/ci/citool/src/utils.rs @@ -1,3 +1,4 @@ +use std::borrow::Cow; use std::path::Path; use anyhow::Context; @@ -28,3 +29,8 @@ where func(); println!("\n"); } + +/// Normalizes Windows-style path delimiters to Unix-style paths. +pub fn normalize_path_delimiters(name: &str) -> Cow { + if name.contains("\\") { name.replace('\\', "/").into() } else { name.into() } +} From c8a882b7b58a7b8f6b276ab64117b55bbe2626e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Thu, 17 Apr 2025 09:41:12 +0200 Subject: [PATCH 221/266] Add command to `citool` for generating a test dashboard --- src/ci/citool/Cargo.lock | 67 ++++++ src/ci/citool/Cargo.toml | 1 + src/ci/citool/src/main.rs | 16 +- src/ci/citool/src/test_dashboard/mod.rs | 239 +++++++++++++++++++++ src/ci/citool/templates/layout.askama | 71 ++++++ src/ci/citool/templates/test_group.askama | 22 ++ src/ci/citool/templates/test_suites.askama | 18 ++ 7 files changed, 433 insertions(+), 1 deletion(-) create mode 100644 src/ci/citool/src/test_dashboard/mod.rs create mode 100644 src/ci/citool/templates/layout.askama create mode 100644 src/ci/citool/templates/test_group.askama create mode 100644 src/ci/citool/templates/test_suites.askama diff --git a/src/ci/citool/Cargo.lock b/src/ci/citool/Cargo.lock index 2fe219f368b9c..43321d12cafcd 100644 --- a/src/ci/citool/Cargo.lock +++ b/src/ci/citool/Cargo.lock @@ -64,12 +64,63 @@ version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04" +[[package]] +name = "askama" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4744ed2eef2645831b441d8f5459689ade2ab27c854488fbab1fbe94fce1a7" +dependencies = [ + "askama_derive", + "itoa", + "percent-encoding", + "serde", + "serde_json", +] + +[[package]] +name = "askama_derive" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d661e0f57be36a5c14c48f78d09011e67e0cb618f269cca9f2fd8d15b68c46ac" +dependencies = [ + "askama_parser", + "basic-toml", + "memchr", + "proc-macro2", + "quote", + "rustc-hash", + "serde", + "serde_derive", + "syn", +] + +[[package]] +name = "askama_parser" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf315ce6524c857bb129ff794935cf6d42c82a6cff60526fe2a63593de4d0d4f" +dependencies = [ + "memchr", + "serde", + "serde_derive", + "winnow", +] + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + [[package]] name = "build_helper" version = "0.1.0" @@ -104,6 +155,7 @@ name = "citool" version = "0.1.0" dependencies = [ "anyhow", + "askama", "build_helper", "clap", "csv", @@ -646,6 +698,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rustc-hash" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" + [[package]] name = "rustls" version = "0.23.23" @@ -1026,6 +1084,15 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63d3fcd9bba44b03821e7d699eeee959f3126dcc4aa8e4ae18ec617c2a5cea10" +dependencies = [ + "memchr", +] + [[package]] name = "write16" version = "1.0.0" diff --git a/src/ci/citool/Cargo.toml b/src/ci/citool/Cargo.toml index f18436a126359..0e2aba3b9e3fc 100644 --- a/src/ci/citool/Cargo.toml +++ b/src/ci/citool/Cargo.toml @@ -5,6 +5,7 @@ edition = "2021" [dependencies] anyhow = "1" +askama = "0.13" clap = { version = "4.5", features = ["derive"] } csv = "1" diff = "0.1" diff --git a/src/ci/citool/src/main.rs b/src/ci/citool/src/main.rs index 0fee862f5721b..a7a289fc3d4b1 100644 --- a/src/ci/citool/src/main.rs +++ b/src/ci/citool/src/main.rs @@ -4,6 +4,7 @@ mod datadog; mod github; mod jobs; mod metrics; +mod test_dashboard; mod utils; use std::collections::{BTreeMap, HashMap}; @@ -22,6 +23,7 @@ use crate::datadog::upload_datadog_metric; use crate::github::JobInfoResolver; use crate::jobs::RunType; use crate::metrics::{JobMetrics, download_auto_job_metrics, download_job_metrics, load_metrics}; +use crate::test_dashboard::generate_test_dashboard; use crate::utils::load_env_var; const CI_DIRECTORY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/.."); @@ -234,6 +236,14 @@ enum Args { /// Current commit that will be compared to `parent`. current: String, }, + /// Generate a directory containing a HTML dashboard of test results from a CI run. + TestDashboard { + /// Commit SHA that was tested on CI to analyze. + current: String, + /// Output path for the HTML directory. + #[clap(long)] + output_dir: PathBuf, + }, } #[derive(clap::ValueEnum, Clone)] @@ -275,7 +285,11 @@ fn main() -> anyhow::Result<()> { postprocess_metrics(metrics_path, parent, job_name)?; } Args::PostMergeReport { current, parent } => { - post_merge_report(load_db(default_jobs_file)?, current, parent)?; + post_merge_report(load_db(&default_jobs_file)?, current, parent)?; + } + Args::TestDashboard { current, output_dir } => { + let db = load_db(&default_jobs_file)?; + generate_test_dashboard(db, ¤t, &output_dir)?; } } diff --git a/src/ci/citool/src/test_dashboard/mod.rs b/src/ci/citool/src/test_dashboard/mod.rs new file mode 100644 index 0000000000000..ad9fe029e15df --- /dev/null +++ b/src/ci/citool/src/test_dashboard/mod.rs @@ -0,0 +1,239 @@ +use std::collections::{BTreeMap, HashMap}; +use std::fs::File; +use std::io::BufWriter; +use std::path::{Path, PathBuf}; + +use askama::Template; +use build_helper::metrics::{TestOutcome, TestSuiteMetadata}; + +use crate::jobs::JobDatabase; +use crate::metrics::{JobMetrics, JobName, download_auto_job_metrics, get_test_suites}; +use crate::utils::normalize_path_delimiters; + +pub struct TestInfo { + name: String, + jobs: Vec, +} + +struct JobTestResult { + job_name: String, + outcome: TestOutcome, +} + +#[derive(Default)] +struct TestSuiteInfo { + name: String, + tests: BTreeMap, +} + +/// Generate a set of HTML files into a directory that contain a dashboard of test results. +pub fn generate_test_dashboard( + db: JobDatabase, + current: &str, + output_dir: &Path, +) -> anyhow::Result<()> { + let metrics = download_auto_job_metrics(&db, None, current)?; + + let suites = gather_test_suites(&metrics); + + std::fs::create_dir_all(output_dir)?; + + let test_count = suites.test_count(); + write_page(output_dir, "index.html", &TestSuitesPage { suites, test_count })?; + + Ok(()) +} + +fn write_page(dir: &Path, name: &str, template: &T) -> anyhow::Result<()> { + let mut file = BufWriter::new(File::create(dir.join(name))?); + Template::write_into(template, &mut file)?; + Ok(()) +} + +fn gather_test_suites(job_metrics: &HashMap) -> TestSuites { + struct CoarseTestSuite<'a> { + kind: TestSuiteKind, + tests: BTreeMap>, + } + + let mut suites: HashMap = HashMap::new(); + + // First, gather tests from all jobs, stages and targets, and aggregate them per suite + for (job, metrics) in job_metrics { + let test_suites = get_test_suites(&metrics.current); + for suite in test_suites { + let (suite_name, stage, target, kind) = match &suite.metadata { + TestSuiteMetadata::CargoPackage { crates, stage, target, .. } => { + (crates.join(","), *stage, target, TestSuiteKind::Cargo) + } + TestSuiteMetadata::Compiletest { suite, stage, target, .. } => { + (suite.clone(), *stage, target, TestSuiteKind::Compiletest) + } + }; + let suite_entry = suites + .entry(suite_name.clone()) + .or_insert_with(|| CoarseTestSuite { kind, tests: Default::default() }); + let test_metadata = TestMetadata { job, stage, target }; + + for test in &suite.tests { + let test_name = normalize_test_name(&test.name, &suite_name); + let test_entry = suite_entry + .tests + .entry(test_name.clone()) + .or_insert_with(|| Test { name: test_name, passed: vec![], ignored: vec![] }); + match test.outcome { + TestOutcome::Passed => { + test_entry.passed.push(test_metadata); + } + TestOutcome::Ignored { ignore_reason: _ } => { + test_entry.ignored.push(test_metadata); + } + TestOutcome::Failed => { + eprintln!("Warning: failed test"); + } + } + } + } + } + + // Then, split the suites per directory + let mut suites = suites.into_iter().collect::>(); + suites.sort_by(|a, b| a.1.kind.cmp(&b.1.kind).then_with(|| a.0.cmp(&b.0))); + + let mut target_suites = vec![]; + for (suite_name, suite) in suites { + let suite = match suite.kind { + TestSuiteKind::Compiletest => TestSuite { + name: suite_name.clone(), + kind: TestSuiteKind::Compiletest, + group: build_test_group(&suite_name, suite.tests), + }, + TestSuiteKind::Cargo => { + let mut tests: Vec<_> = suite.tests.into_iter().collect(); + tests.sort_by(|a, b| a.0.cmp(&b.0)); + TestSuite { + name: format!("[cargo] {}", suite_name.clone()), + kind: TestSuiteKind::Cargo, + group: TestGroup { + name: suite_name, + root_tests: tests.into_iter().map(|t| t.1).collect(), + groups: vec![], + }, + } + } + }; + target_suites.push(suite); + } + + TestSuites { suites: target_suites } +} + +/// Recursively expand a test group based on filesystem hierarchy. +fn build_test_group<'a>(name: &str, tests: BTreeMap>) -> TestGroup<'a> { + let mut root_tests = vec![]; + let mut subdirs: BTreeMap>> = Default::default(); + + // Split tests into root tests and tests located in subdirectories + for (name, test) in tests { + let mut components = Path::new(&name).components().peekable(); + let subdir = components.next().unwrap(); + + if components.peek().is_none() { + // This is a root test + root_tests.push(test); + } else { + // This is a test in a nested directory + let subdir_tests = + subdirs.entry(subdir.as_os_str().to_str().unwrap().to_string()).or_default(); + let test_name = + components.into_iter().collect::().to_str().unwrap().to_string(); + subdir_tests.insert(test_name, test); + } + } + let dirs = subdirs + .into_iter() + .map(|(name, tests)| { + let group = build_test_group(&name, tests); + (name, group) + }) + .collect(); + + TestGroup { name: name.to_string(), root_tests, groups: dirs } +} + +/// Compiletest tests start with `[suite] tests/[suite]/a/b/c...`. +/// Remove the `[suite] tests/[suite]/` prefix so that we can find the filesystem path. +/// Also normalizes path delimiters. +fn normalize_test_name(name: &str, suite_name: &str) -> String { + let name = normalize_path_delimiters(name); + let name = name.as_ref(); + let name = name.strip_prefix(&format!("[{suite_name}]")).unwrap_or(name).trim(); + let name = name.strip_prefix("tests/").unwrap_or(name); + let name = name.strip_prefix(suite_name).unwrap_or(name); + name.trim_start_matches("/").to_string() +} + +#[derive(serde::Serialize)] +struct TestSuites<'a> { + suites: Vec>, +} + +impl<'a> TestSuites<'a> { + fn test_count(&self) -> u64 { + self.suites.iter().map(|suite| suite.group.test_count()).sum::() + } +} + +#[derive(serde::Serialize)] +struct TestSuite<'a> { + name: String, + kind: TestSuiteKind, + group: TestGroup<'a>, +} + +#[derive(Debug, serde::Serialize)] +struct Test<'a> { + name: String, + passed: Vec>, + ignored: Vec>, +} + +#[derive(Clone, Copy, Debug, serde::Serialize)] +struct TestMetadata<'a> { + job: &'a str, + stage: u32, + target: &'a str, +} + +// We have to use a template for the TestGroup instead of a macro, because +// macros cannot be recursive in askama at the moment. +#[derive(Template, serde::Serialize)] +#[template(path = "test_group.askama")] +/// Represents a group of tests +struct TestGroup<'a> { + name: String, + /// Tests located directly in this directory + root_tests: Vec>, + /// Nested directories with additional tests + groups: Vec<(String, TestGroup<'a>)>, +} + +impl<'a> TestGroup<'a> { + fn test_count(&self) -> u64 { + let root = self.root_tests.len() as u64; + self.groups.iter().map(|(_, group)| group.test_count()).sum::() + root + } +} + +#[derive(PartialEq, Eq, PartialOrd, Ord, serde::Serialize)] +enum TestSuiteKind { + Compiletest, + Cargo, +} + +#[derive(Template)] +#[template(path = "test_suites.askama")] +struct TestSuitesPage<'a> { + suites: TestSuites<'a>, + test_count: u64, +} diff --git a/src/ci/citool/templates/layout.askama b/src/ci/citool/templates/layout.askama new file mode 100644 index 0000000000000..2e830aaa9f583 --- /dev/null +++ b/src/ci/citool/templates/layout.askama @@ -0,0 +1,71 @@ + + + + Rust CI Test Dashboard + + + + +{% block content %}{% endblock %} + + diff --git a/src/ci/citool/templates/test_group.askama b/src/ci/citool/templates/test_group.askama new file mode 100644 index 0000000000000..a0b7fa863e577 --- /dev/null +++ b/src/ci/citool/templates/test_group.askama @@ -0,0 +1,22 @@ +
  • +
    +{{ name }} ({{ test_count() }} test{{ test_count() | pluralize }}) + +{% if !groups.is_empty() %} +
      + {% for (dir_name, subgroup) in groups %} + {{ subgroup|safe }} + {% endfor %} +
    +{% endif %} + +{% if !root_tests.is_empty() %} +
      + {% for test in root_tests %} +
    • {{ test.name }} ({{ test.passed.len() }} passed, {{ test.ignored.len() }} ignored)
    • + {% endfor %} +
    +{% endif %} + +
    +
  • diff --git a/src/ci/citool/templates/test_suites.askama b/src/ci/citool/templates/test_suites.askama new file mode 100644 index 0000000000000..a6f8d0e1abe03 --- /dev/null +++ b/src/ci/citool/templates/test_suites.askama @@ -0,0 +1,18 @@ +{% extends "layout.askama" %} + +{% block content %} +

    Rust CI Test Dashboard

    +
    +
    + Total tests: {{ test_count }} +
    + +
      + {% for suite in suites.suites %} + {% if suite.kind == TestSuiteKind::Compiletest %} + {{ suite.group|safe }} + {% endif %} + {% endfor %} +
    +
    +{% endblock %} From 50cf10231125d7b306ed92867f11771032d28eff Mon Sep 17 00:00:00 2001 From: Patrick-6 Date: Thu, 17 Apr 2025 16:23:36 +0200 Subject: [PATCH 222/266] Change function visibility to pub --- compiler/rustc_const_eval/src/interpret/eval_context.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index c1948e9f31f10..b69bc0918be82 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -268,7 +268,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// Call this on things you got out of the MIR (so it is as generic as the current /// stack frame), to bring it into the proper environment for this interpreter. - pub(super) fn instantiate_from_current_frame_and_normalize_erasing_regions< + pub fn instantiate_from_current_frame_and_normalize_erasing_regions< T: TypeFoldable>, >( &self, @@ -279,9 +279,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// Call this on things you got out of the MIR (so it is as generic as the provided /// stack frame), to bring it into the proper environment for this interpreter. - pub(super) fn instantiate_from_frame_and_normalize_erasing_regions< - T: TypeFoldable>, - >( + pub fn instantiate_from_frame_and_normalize_erasing_regions>>( &self, frame: &Frame<'tcx, M::Provenance, M::FrameExtra>, value: T, From a326afd5dd810427c72ed81e705c0d903e74edcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Thu, 17 Apr 2025 16:30:23 +0200 Subject: [PATCH 223/266] Add buttons for expanding and collapsing all test suites --- src/ci/citool/templates/layout.askama | 57 ++------------- src/ci/citool/templates/test_suites.askama | 81 +++++++++++++++++++++- 2 files changed, 84 insertions(+), 54 deletions(-) diff --git a/src/ci/citool/templates/layout.askama b/src/ci/citool/templates/layout.askama index 2e830aaa9f583..3b3b6f23741d4 100644 --- a/src/ci/citool/templates/layout.askama +++ b/src/ci/citool/templates/layout.askama @@ -3,69 +3,20 @@ Rust CI Test Dashboard {% block content %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/src/ci/citool/templates/test_suites.askama b/src/ci/citool/templates/test_suites.askama index a6f8d0e1abe03..a8cedc65f2434 100644 --- a/src/ci/citool/templates/test_suites.askama +++ b/src/ci/citool/templates/test_suites.askama @@ -4,7 +4,11 @@

    Rust CI Test Dashboard

    - Total tests: {{ test_count }} + Total tests: {{ test_count }} +
    + + +
      @@ -16,3 +20,78 @@
    {% endblock %} + +{% block styles %} +h1 { + text-align: center; + color: #333333; + margin-bottom: 30px; +} + +.summary { + display: flex; + justify-content: space-between; +} + +.test-suites { + background: white; + border-radius: 8px; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); + padding: 20px; +} + +ul { + padding-left: 0; +} + +li { + list-style: none; + padding-left: 20px; +} +summary { + margin-bottom: 5px; + padding: 6px; + background-color: #F4F4F4; + border: 1px solid #ddd; + border-radius: 4px; + cursor: pointer; +} +summary:hover { + background-color: #CFCFCF; +} + +/* Style the disclosure triangles */ +details > summary { + list-style: none; + position: relative; +} + +details > summary::before { + content: "▶"; + position: absolute; + left: -15px; + transform: rotate(0); + transition: transform 0.2s; +} + +details[open] > summary::before { + transform: rotate(90deg); +} +{% endblock %} + +{% block scripts %} + +{% endblock %} From 4b310338f8d2a67cbc863ee799206709e95da6b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Thu, 17 Apr 2025 16:35:34 +0200 Subject: [PATCH 224/266] Add a note about how to find tests that haven't been executed anywhere. --- src/ci/citool/src/test_dashboard/mod.rs | 60 ++++------------------ src/ci/citool/templates/test_suites.askama | 17 ++++-- 2 files changed, 22 insertions(+), 55 deletions(-) diff --git a/src/ci/citool/src/test_dashboard/mod.rs b/src/ci/citool/src/test_dashboard/mod.rs index ad9fe029e15df..163e9c1acea0e 100644 --- a/src/ci/citool/src/test_dashboard/mod.rs +++ b/src/ci/citool/src/test_dashboard/mod.rs @@ -10,22 +10,6 @@ use crate::jobs::JobDatabase; use crate::metrics::{JobMetrics, JobName, download_auto_job_metrics, get_test_suites}; use crate::utils::normalize_path_delimiters; -pub struct TestInfo { - name: String, - jobs: Vec, -} - -struct JobTestResult { - job_name: String, - outcome: TestOutcome, -} - -#[derive(Default)] -struct TestSuiteInfo { - name: String, - tests: BTreeMap, -} - /// Generate a set of HTML files into a directory that contain a dashboard of test results. pub fn generate_test_dashboard( db: JobDatabase, @@ -33,7 +17,6 @@ pub fn generate_test_dashboard( output_dir: &Path, ) -> anyhow::Result<()> { let metrics = download_auto_job_metrics(&db, None, current)?; - let suites = gather_test_suites(&metrics); std::fs::create_dir_all(output_dir)?; @@ -52,27 +35,27 @@ fn write_page(dir: &Path, name: &str, template: &T) -> anyhow::Resu fn gather_test_suites(job_metrics: &HashMap) -> TestSuites { struct CoarseTestSuite<'a> { - kind: TestSuiteKind, tests: BTreeMap>, } let mut suites: HashMap = HashMap::new(); // First, gather tests from all jobs, stages and targets, and aggregate them per suite + // Only work with compiletest suites. for (job, metrics) in job_metrics { let test_suites = get_test_suites(&metrics.current); for suite in test_suites { - let (suite_name, stage, target, kind) = match &suite.metadata { - TestSuiteMetadata::CargoPackage { crates, stage, target, .. } => { - (crates.join(","), *stage, target, TestSuiteKind::Cargo) + let (suite_name, stage, target) = match &suite.metadata { + TestSuiteMetadata::CargoPackage { .. } => { + continue; } TestSuiteMetadata::Compiletest { suite, stage, target, .. } => { - (suite.clone(), *stage, target, TestSuiteKind::Compiletest) + (suite.clone(), *stage, target) } }; let suite_entry = suites .entry(suite_name.clone()) - .or_insert_with(|| CoarseTestSuite { kind, tests: Default::default() }); + .or_insert_with(|| CoarseTestSuite { tests: Default::default() }); let test_metadata = TestMetadata { job, stage, target }; for test in &suite.tests { @@ -98,29 +81,13 @@ fn gather_test_suites(job_metrics: &HashMap) -> TestSuites // Then, split the suites per directory let mut suites = suites.into_iter().collect::>(); - suites.sort_by(|a, b| a.1.kind.cmp(&b.1.kind).then_with(|| a.0.cmp(&b.0))); + suites.sort_by(|a, b| a.0.cmp(&b.0)); let mut target_suites = vec![]; for (suite_name, suite) in suites { - let suite = match suite.kind { - TestSuiteKind::Compiletest => TestSuite { - name: suite_name.clone(), - kind: TestSuiteKind::Compiletest, - group: build_test_group(&suite_name, suite.tests), - }, - TestSuiteKind::Cargo => { - let mut tests: Vec<_> = suite.tests.into_iter().collect(); - tests.sort_by(|a, b| a.0.cmp(&b.0)); - TestSuite { - name: format!("[cargo] {}", suite_name.clone()), - kind: TestSuiteKind::Cargo, - group: TestGroup { - name: suite_name, - root_tests: tests.into_iter().map(|t| t.1).collect(), - groups: vec![], - }, - } - } + let suite = TestSuite { + name: suite_name.clone(), + group: build_test_group(&suite_name, suite.tests), }; target_suites.push(suite); } @@ -187,7 +154,6 @@ impl<'a> TestSuites<'a> { #[derive(serde::Serialize)] struct TestSuite<'a> { name: String, - kind: TestSuiteKind, group: TestGroup<'a>, } @@ -225,12 +191,6 @@ impl<'a> TestGroup<'a> { } } -#[derive(PartialEq, Eq, PartialOrd, Ord, serde::Serialize)] -enum TestSuiteKind { - Compiletest, - Cargo, -} - #[derive(Template)] #[template(path = "test_suites.askama")] struct TestSuitesPage<'a> { diff --git a/src/ci/citool/templates/test_suites.askama b/src/ci/citool/templates/test_suites.askama index a8cedc65f2434..bb3d9e363911d 100644 --- a/src/ci/citool/templates/test_suites.askama +++ b/src/ci/citool/templates/test_suites.askama @@ -1,10 +1,15 @@ {% extends "layout.askama" %} {% block content %} -

    Rust CI Test Dashboard

    +

    Rust CI test dashboard

    - Total tests: {{ test_count }} +
    +
    Total tests: {{ test_count }}
    +
    + To find tests that haven't been executed anywhere, click on "Open all" and search for "(0 passed". +
    +
    @@ -13,9 +18,7 @@
      {% for suite in suites.suites %} - {% if suite.kind == TestSuiteKind::Compiletest %} - {{ suite.group|safe }} - {% endif %} + {{ suite.group|safe }} {% endfor %}
    @@ -33,6 +36,10 @@ h1 { justify-content: space-between; } +.test-count { + font-size: 1.2em; +} + .test-suites { background: white; border-radius: 8px; From f9091e24a0af713378ee705c86689c1435d0b157 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 7 Apr 2025 12:35:02 -0700 Subject: [PATCH 225/266] Ignore zero-sized types in wasm future-compat warning This commit fixes a false positive of the warning triggered for #138762 and the fix is to codify that zero-sized types are "safe" in both the old and new ABIs. --- compiler/rustc_monomorphize/src/mono_checks/abi_check.rs | 5 +++++ tests/ui/lint/wasm_c_abi_transition.rs | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs index 0f5bdc8d7683f..94ee34c8b7bf3 100644 --- a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs +++ b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs @@ -111,6 +111,11 @@ fn wasm_abi_safe<'tcx>(tcx: TyCtxt<'tcx>, arg: &ArgAbi<'tcx, Ty<'tcx>>) -> bool } } + // Zero-sized types are dropped in both ABIs, so they're safe + if arg.layout.is_zst() { + return true; + } + false } diff --git a/tests/ui/lint/wasm_c_abi_transition.rs b/tests/ui/lint/wasm_c_abi_transition.rs index 1fe81679e65d0..6a933a0de036f 100644 --- a/tests/ui/lint/wasm_c_abi_transition.rs +++ b/tests/ui/lint/wasm_c_abi_transition.rs @@ -39,3 +39,9 @@ pub fn call_other_fun(x: MyType) { unsafe { other_fun(x) } //~ERROR: wasm ABI transition //~^WARN: previously accepted } + +// Zero-sized types are safe in both ABIs +#[repr(C)] +pub struct MyZstType; +#[allow(improper_ctypes_definitions)] +pub extern "C" fn zst_safe(_x: (), _y: MyZstType) {} From 1a6e0d52e5b008cfd48f78285bb3655ecfd5d73e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Thu, 17 Apr 2025 17:14:26 +0200 Subject: [PATCH 226/266] Render test revisions separately --- src/ci/citool/src/test_dashboard/mod.rs | 43 ++++++++++++++++++----- src/ci/citool/templates/test_group.askama | 13 ++++++- 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/src/ci/citool/src/test_dashboard/mod.rs b/src/ci/citool/src/test_dashboard/mod.rs index 163e9c1acea0e..c16385baa3ba4 100644 --- a/src/ci/citool/src/test_dashboard/mod.rs +++ b/src/ci/citool/src/test_dashboard/mod.rs @@ -60,19 +60,27 @@ fn gather_test_suites(job_metrics: &HashMap) -> TestSuites for test in &suite.tests { let test_name = normalize_test_name(&test.name, &suite_name); - let test_entry = suite_entry - .tests - .entry(test_name.clone()) - .or_insert_with(|| Test { name: test_name, passed: vec![], ignored: vec![] }); + let (test_name, variant_name) = match test_name.rsplit_once('#') { + Some((name, variant)) => (name.to_string(), variant.to_string()), + None => (test_name, "".to_string()), + }; + let test_entry = suite_entry.tests.entry(test_name.clone()).or_insert_with(|| { + Test { name: test_name.clone(), revisions: Default::default() } + }); + let variant_entry = test_entry + .revisions + .entry(variant_name) + .or_insert_with(|| TestResults { passed: vec![], ignored: vec![] }); + match test.outcome { TestOutcome::Passed => { - test_entry.passed.push(test_metadata); + variant_entry.passed.push(test_metadata); } TestOutcome::Ignored { ignore_reason: _ } => { - test_entry.ignored.push(test_metadata); + variant_entry.ignored.push(test_metadata); } TestOutcome::Failed => { - eprintln!("Warning: failed test"); + eprintln!("Warning: failed test {test_name}"); } } } @@ -158,12 +166,29 @@ struct TestSuite<'a> { } #[derive(Debug, serde::Serialize)] -struct Test<'a> { - name: String, +struct TestResults<'a> { passed: Vec>, ignored: Vec>, } +#[derive(Debug, serde::Serialize)] +struct Test<'a> { + name: String, + revisions: BTreeMap>, +} + +impl<'a> Test<'a> { + /// If this is a test without revisions, it will have a single entry in `revisions` with + /// an empty string as the revision name. + fn single_test(&self) -> Option<&TestResults<'a>> { + if self.revisions.len() == 1 { + self.revisions.iter().next().take_if(|e| e.0.is_empty()).map(|e| e.1) + } else { + None + } + } +} + #[derive(Clone, Copy, Debug, serde::Serialize)] struct TestMetadata<'a> { job: &'a str, diff --git a/src/ci/citool/templates/test_group.askama b/src/ci/citool/templates/test_group.askama index a0b7fa863e577..535d98e0c247f 100644 --- a/src/ci/citool/templates/test_group.askama +++ b/src/ci/citool/templates/test_group.askama @@ -13,7 +13,18 @@ {% if !root_tests.is_empty() %}
      {% for test in root_tests %} -
    • {{ test.name }} ({{ test.passed.len() }} passed, {{ test.ignored.len() }} ignored)
    • +
    • + {% if let Some(result) = test.single_test() %} + {{ test.name }} ({{ result.passed.len() }} passed, {{ result.ignored.len() }} ignored) + {% else %} + {{ test.name }} ({{ test.revisions.len() }} revision{{ test.revisions.len() | pluralize }}) +
        + {% for (revision, result) in test.revisions %} +
      • #{{ revision }} ({{ result.passed.len() }} passed, {{ result.ignored.len() }} ignored)
      • + {% endfor %} +
      + {% endif %} +
    • {% endfor %}
    {% endif %} From d2c1763336080030a235dae56f6096e9deb2ec9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Thu, 17 Apr 2025 17:18:38 +0200 Subject: [PATCH 227/266] Create a macro for rendering test results --- src/ci/citool/templates/test_group.askama | 8 ++++++-- src/ci/citool/templates/test_suites.askama | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/ci/citool/templates/test_group.askama b/src/ci/citool/templates/test_group.askama index 535d98e0c247f..ba19d9258d8a0 100644 --- a/src/ci/citool/templates/test_group.askama +++ b/src/ci/citool/templates/test_group.askama @@ -1,3 +1,7 @@ +{% macro test_result(r) -%} +passed: {{ r.passed.len() }}, ignored: {{ r.ignored.len() }} +{%- endmacro %} +
  • {{ name }} ({{ test_count() }} test{{ test_count() | pluralize }}) @@ -15,12 +19,12 @@ {% for test in root_tests %}
  • {% if let Some(result) = test.single_test() %} - {{ test.name }} ({{ result.passed.len() }} passed, {{ result.ignored.len() }} ignored) + {{ test.name }} ({% call test_result(result) %}) {% else %} {{ test.name }} ({{ test.revisions.len() }} revision{{ test.revisions.len() | pluralize }})
      {% for (revision, result) in test.revisions %} -
    • #{{ revision }} ({{ result.passed.len() }} passed, {{ result.ignored.len() }} ignored)
    • +
    • #{{ revision }} ({% call test_result(result) %})
    • {% endfor %}
    {% endif %} diff --git a/src/ci/citool/templates/test_suites.askama b/src/ci/citool/templates/test_suites.askama index bb3d9e363911d..d36e85228e2b0 100644 --- a/src/ci/citool/templates/test_suites.askama +++ b/src/ci/citool/templates/test_suites.askama @@ -7,7 +7,7 @@
    Total tests: {{ test_count }}
    - To find tests that haven't been executed anywhere, click on "Open all" and search for "(0 passed". + To find tests that haven't been executed anywhere, click on "Open all" and search for "passed: 0".
    From 83af9f57c12c25807777f0c42ecc5a9ba070b09f Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Thu, 17 Apr 2025 23:20:30 +0800 Subject: [PATCH 228/266] run-make: drop `os_pipe` workaround now that `anonymous_pipe` is stable on beta --- Cargo.lock | 11 ----------- src/tools/run-make-support/Cargo.toml | 4 ---- src/tools/run-make-support/src/lib.rs | 2 -- tests/run-make/broken-pipe-no-ice/rmake.rs | 6 ++---- 4 files changed, 2 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3d0e294217912..58d3673fcbaae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2572,16 +2572,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" -[[package]] -name = "os_pipe" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ffd2b0a5634335b135d5728d84c5e0fd726954b87111f7506a61c502280d982" -dependencies = [ - "libc", - "windows-sys 0.59.0", -] - [[package]] name = "overload" version = "0.1.1" @@ -3142,7 +3132,6 @@ dependencies = [ "gimli 0.31.1", "libc", "object 0.36.7", - "os_pipe", "regex", "serde_json", "similar", diff --git a/src/tools/run-make-support/Cargo.toml b/src/tools/run-make-support/Cargo.toml index f9beffec75085..15ed03ad5c23d 100644 --- a/src/tools/run-make-support/Cargo.toml +++ b/src/tools/run-make-support/Cargo.toml @@ -14,9 +14,5 @@ build_helper = { path = "../../build_helper" } serde_json = "1.0" libc = "0.2" -# FIXME(#137532): replace `os_pipe` with `anonymous_pipe` once it stabilizes and -# reaches beta. -os_pipe = "1.2.1" - [lib] crate-type = ["lib", "dylib"] diff --git a/src/tools/run-make-support/src/lib.rs b/src/tools/run-make-support/src/lib.rs index c75d500d2f06e..f37b38ac0b151 100644 --- a/src/tools/run-make-support/src/lib.rs +++ b/src/tools/run-make-support/src/lib.rs @@ -41,8 +41,6 @@ pub use bstr; pub use gimli; pub use libc; pub use object; -// FIXME(#137532): replace with std `anonymous_pipe` once it stabilizes and reaches beta. -pub use os_pipe; pub use regex; pub use serde_json; pub use similar; diff --git a/tests/run-make/broken-pipe-no-ice/rmake.rs b/tests/run-make/broken-pipe-no-ice/rmake.rs index 3e54b576fd421..0521b3950207d 100644 --- a/tests/run-make/broken-pipe-no-ice/rmake.rs +++ b/tests/run-make/broken-pipe-no-ice/rmake.rs @@ -14,9 +14,7 @@ use std::io::Read; use std::process::{Command, Stdio}; -// FIXME(#137532): replace `os_pipe` dependency with std `anonymous_pipe` once that stabilizes and -// reaches beta. -use run_make_support::{env_var, os_pipe}; +use run_make_support::env_var; #[derive(Debug, PartialEq)] enum Binary { @@ -25,7 +23,7 @@ enum Binary { } fn check_broken_pipe_handled_gracefully(bin: Binary, mut cmd: Command) { - let (reader, writer) = os_pipe::pipe().unwrap(); + let (reader, writer) = std::io::pipe().unwrap(); drop(reader); // close read-end cmd.stdout(writer).stderr(Stdio::piped()); From aa9cb70190bb38e466983abf0c53c6f26afab4de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Thu, 17 Apr 2025 17:25:12 +0200 Subject: [PATCH 229/266] Print number of root tests and subdirectories --- src/ci/citool/templates/test_group.askama | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/ci/citool/templates/test_group.askama b/src/ci/citool/templates/test_group.askama index ba19d9258d8a0..bdf32d00f4a19 100644 --- a/src/ci/citool/templates/test_group.askama +++ b/src/ci/citool/templates/test_group.askama @@ -4,7 +4,12 @@ passed: {{ r.passed.len() }}, ignored: {{ r.ignored.len() }}
  • -{{ name }} ({{ test_count() }} test{{ test_count() | pluralize }}) +{{ name }} ({{ test_count() }} test{{ test_count() | pluralize }}{% if !root_tests.is_empty() && root_tests.len() as u64 != test_count() -%} + , {{ root_tests.len() }} root test{{ root_tests.len() | pluralize }} +{%- endif %}{% if !groups.is_empty() -%} + , {{ groups.len() }} subdir{{ groups.len() | pluralize }} +{%- endif %}) + {% if !groups.is_empty() %}
      From 08cb187d263ec91e8e6d35b4b235eee4ecad3357 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Thu, 17 Apr 2025 17:26:40 +0200 Subject: [PATCH 230/266] Turn `test_dashboard` into a file --- src/ci/citool/src/{test_dashboard/mod.rs => test_dashboard.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/ci/citool/src/{test_dashboard/mod.rs => test_dashboard.rs} (100%) diff --git a/src/ci/citool/src/test_dashboard/mod.rs b/src/ci/citool/src/test_dashboard.rs similarity index 100% rename from src/ci/citool/src/test_dashboard/mod.rs rename to src/ci/citool/src/test_dashboard.rs From e5e5fb9d805dacdd5ceaf73254d61726d75f455a Mon Sep 17 00:00:00 2001 From: Amanieu d'Antras Date: Thu, 17 Apr 2025 17:29:32 +0200 Subject: [PATCH 231/266] Fix drop handling in `hint::select_unpredictable` This intrinsic doesn't drop the value that is not selected so this is manually done in the public function that wraps the intrinsic. --- library/core/src/hint.rs | 30 +++++++++++++++++++++--------- library/core/src/intrinsics/mod.rs | 2 ++ library/coretests/tests/hint.rs | 23 +++++++++++++++++++++++ library/coretests/tests/lib.rs | 2 ++ 4 files changed, 48 insertions(+), 9 deletions(-) create mode 100644 library/coretests/tests/hint.rs diff --git a/library/core/src/hint.rs b/library/core/src/hint.rs index f6708cc4bc912..1ca23ab6eea66 100644 --- a/library/core/src/hint.rs +++ b/library/core/src/hint.rs @@ -4,6 +4,7 @@ //! //! Hints may be compile time or runtime. +use crate::mem::MaybeUninit; use crate::{intrinsics, ub_checks}; /// Informs the compiler that the site which is calling this function is not @@ -735,9 +736,9 @@ pub const fn cold_path() { crate::intrinsics::cold_path() } -/// Returns either `true_val` or `false_val` depending on the value of `b`, -/// with a hint to the compiler that `b` is unlikely to be correctly -/// predicted by a CPU’s branch predictor. +/// Returns either `true_val` or `false_val` depending on the value of +/// `condition`, with a hint to the compiler that `condition` is unlikely to be +/// correctly predicted by a CPU’s branch predictor. /// /// This method is functionally equivalent to /// ```ignore (this is just for illustrative purposes) @@ -753,10 +754,10 @@ pub const fn cold_path() { /// search. /// /// Note however that this lowering is not guaranteed (on any platform) and -/// should not be relied upon when trying to write constant-time code. Also -/// be aware that this lowering might *decrease* performance if `condition` -/// is well-predictable. It is advisable to perform benchmarks to tell if -/// this function is useful. +/// should not be relied upon when trying to write cryptographic constant-time +/// code. Also be aware that this lowering might *decrease* performance if +/// `condition` is well-predictable. It is advisable to perform benchmarks to +/// tell if this function is useful. /// /// # Examples /// @@ -780,6 +781,17 @@ pub const fn cold_path() { /// ``` #[inline(always)] #[unstable(feature = "select_unpredictable", issue = "133962")] -pub fn select_unpredictable(b: bool, true_val: T, false_val: T) -> T { - crate::intrinsics::select_unpredictable(b, true_val, false_val) +pub fn select_unpredictable(condition: bool, true_val: T, false_val: T) -> T { + // FIXME(https://github.com/rust-lang/unsafe-code-guidelines/issues/245): + // Change this to use ManuallyDrop instead. + let mut true_val = MaybeUninit::new(true_val); + let mut false_val = MaybeUninit::new(false_val); + // SAFETY: The value that is not selected is dropped, and the selected one + // is returned. This is necessary because the intrinsic doesn't drop the + // value that is not selected. + unsafe { + crate::intrinsics::select_unpredictable(!condition, &mut true_val, &mut false_val) + .assume_init_drop(); + crate::intrinsics::select_unpredictable(condition, true_val, false_val).assume_init() + } } diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index e5604d277f57a..a01efb2adebe3 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -1327,6 +1327,8 @@ pub const fn unlikely(b: bool) -> bool { /// any safety invariants. /// /// The public form of this instrinsic is [`core::hint::select_unpredictable`]. +/// However unlike the public form, the intrinsic will not drop the value that +/// is not selected. #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] #[rustc_nounwind] diff --git a/library/coretests/tests/hint.rs b/library/coretests/tests/hint.rs new file mode 100644 index 0000000000000..032bbc1dcc80f --- /dev/null +++ b/library/coretests/tests/hint.rs @@ -0,0 +1,23 @@ +#[test] +fn select_unpredictable_drop() { + use core::cell::Cell; + struct X<'a>(&'a Cell); + impl Drop for X<'_> { + fn drop(&mut self) { + self.0.set(true); + } + } + + let a_dropped = Cell::new(false); + let b_dropped = Cell::new(false); + let a = X(&a_dropped); + let b = X(&b_dropped); + assert!(!a_dropped.get()); + assert!(!b_dropped.get()); + let selected = core::hint::select_unpredictable(core::hint::black_box(true), a, b); + assert!(!a_dropped.get()); + assert!(b_dropped.get()); + drop(selected); + assert!(a_dropped.get()); + assert!(b_dropped.get()); +} diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index 7ad154796f649..1c43bfe0ed4a9 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -68,6 +68,7 @@ #![feature(pointer_is_aligned_to)] #![feature(portable_simd)] #![feature(ptr_metadata)] +#![feature(select_unpredictable)] #![feature(slice_from_ptr_range)] #![feature(slice_internals)] #![feature(slice_partition_dedup)] @@ -147,6 +148,7 @@ mod ffi; mod fmt; mod future; mod hash; +mod hint; mod intrinsics; mod io; mod iter; From cecf16785f193c247c47e42524322aeccc96c8a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Thu, 17 Apr 2025 17:38:15 +0200 Subject: [PATCH 232/266] Add a note about the test dashboard to the post-merge report --- src/ci/citool/src/main.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/ci/citool/src/main.rs b/src/ci/citool/src/main.rs index a7a289fc3d4b1..f4e671b609fa6 100644 --- a/src/ci/citool/src/main.rs +++ b/src/ci/citool/src/main.rs @@ -24,7 +24,7 @@ use crate::github::JobInfoResolver; use crate::jobs::RunType; use crate::metrics::{JobMetrics, download_auto_job_metrics, download_job_metrics, load_metrics}; use crate::test_dashboard::generate_test_dashboard; -use crate::utils::load_env_var; +use crate::utils::{load_env_var, output_details}; const CI_DIRECTORY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/.."); const DOCKER_DIRECTORY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../docker"); @@ -188,6 +188,20 @@ fn post_merge_report(db: JobDatabase, current: String, parent: String) -> anyhow let mut job_info_resolver = JobInfoResolver::new(); output_test_diffs(&metrics, &mut job_info_resolver); + + output_details("Test dashboard", || { + println!( + r#"\nRun + +```bash +cargo run --manifest-path src/ci/citool/Cargo.toml -- \ + test-dashboard {current} --output-dir test-dashboard +``` +And then open `test-dashboard/index.html` in your browser to see an overview of all executed tests. +"# + ); + }); + output_largest_duration_changes(&metrics, &mut job_info_resolver); Ok(()) From 7d6f41b08e730572b196d6c588364973bb3cb12b Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Wed, 16 Apr 2025 18:27:58 +0000 Subject: [PATCH 233/266] Update `compiler-builtins` to 0.1.155 Includes the following changes: * Replace `#[naked]` with `#[unsafe(naked)]` [1] [2] * Replace `bl!` with `asm_sym` [3] [1]: https://github.com/rust-lang/compiler-builtins/pull/817 [2]: https://github.com/rust-lang/compiler-builtins/pull/821 [3]: https://github.com/rust-lang/compiler-builtins/pull/820 --- library/Cargo.lock | 4 ++-- library/alloc/Cargo.toml | 2 +- library/std/Cargo.toml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/library/Cargo.lock b/library/Cargo.lock index 29e0e134da7f8..e4f1c4ec96a3a 100644 --- a/library/Cargo.lock +++ b/library/Cargo.lock @@ -67,9 +67,9 @@ dependencies = [ [[package]] name = "compiler_builtins" -version = "0.1.153" +version = "0.1.155" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "926ef6a360c15a911023352fd6969c51605d70495406f735beb1ca0257448e59" +checksum = "341e0830ca6170a4fcf02e92e57daf4b6f10142d48da32a547023867a6c8b35e" dependencies = [ "cc", "rustc-std-workspace-core", diff --git a/library/alloc/Cargo.toml b/library/alloc/Cargo.toml index ee8cb9d25a393..cedbd330cbde8 100644 --- a/library/alloc/Cargo.toml +++ b/library/alloc/Cargo.toml @@ -16,7 +16,7 @@ bench = false [dependencies] core = { path = "../core", public = true } -compiler_builtins = { version = "=0.1.153", features = ['rustc-dep-of-std'] } +compiler_builtins = { version = "=0.1.155", features = ['rustc-dep-of-std'] } [features] compiler-builtins-mem = ['compiler_builtins/mem'] diff --git a/library/std/Cargo.toml b/library/std/Cargo.toml index 6b70ff764d7a4..917a470842ca9 100644 --- a/library/std/Cargo.toml +++ b/library/std/Cargo.toml @@ -18,7 +18,7 @@ cfg-if = { version = "1.0", features = ['rustc-dep-of-std'] } panic_unwind = { path = "../panic_unwind", optional = true } panic_abort = { path = "../panic_abort" } core = { path = "../core", public = true } -compiler_builtins = { version = "=0.1.153" } +compiler_builtins = { version = "=0.1.155" } unwind = { path = "../unwind" } hashbrown = { version = "0.15", default-features = false, features = [ 'rustc-dep-of-std', From d3b167493efcfa154640ece0da1b3a9b869d743e Mon Sep 17 00:00:00 2001 From: Augie Fackler Date: Thu, 17 Apr 2025 15:11:21 -0400 Subject: [PATCH 234/266] tests: adjust 101082 test for LLVM 21 fix Fixes #139987. --- tests/codegen/issues/issue-101082.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/tests/codegen/issues/issue-101082.rs b/tests/codegen/issues/issue-101082.rs index 96cdff64dda6b..8d15921ddb4e1 100644 --- a/tests/codegen/issues/issue-101082.rs +++ b/tests/codegen/issues/issue-101082.rs @@ -12,6 +12,7 @@ // at the time still sometimes fails, so only verify it for the power-of-two size // - https://github.com/llvm/llvm-project/issues/134735 //@[x86-64-v3] only-x86_64 +//@[x86-64-v3] min-llvm-version: 21 //@[x86-64-v3] compile-flags: -Ctarget-cpu=x86-64-v3 #![crate_type = "lib"] @@ -19,16 +20,7 @@ #[no_mangle] pub fn test() -> usize { // CHECK-LABEL: @test( - // host: ret {{i64|i32}} 165 - // x86-64: ret {{i64|i32}} 165 - - // FIXME: Now that this autovectorizes via a masked load, it doesn't actually - // const-fold for certain widths. The `test_eight` case below shows that, yes, - // what we're emitting *can* be const-folded, except that the way LLVM does it - // for certain widths doesn't today. We should be able to put this back to - // the same check after - // x86-64-v3: masked.load - + // CHECK: ret {{i64|i32}} 165 let values = [23, 16, 54, 3, 60, 9]; let mut acc = 0; for item in values { From 5523c87c41b357fe3c3047dabf603f18830eeaf8 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 17 Apr 2025 21:16:58 +0200 Subject: [PATCH 235/266] Update libcore.natvis for Pin. --- src/etc/natvis/libcore.natvis | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/etc/natvis/libcore.natvis b/src/etc/natvis/libcore.natvis index 8a441cf209356..8fe87a999895c 100644 --- a/src/etc/natvis/libcore.natvis +++ b/src/etc/natvis/libcore.natvis @@ -69,9 +69,9 @@ - Pin({(void*)__pointer}: {__pointer}) + Pin({(void*)pointer}: {pointer}) - __pointer + pointer From b8c043f07e71dbc1c8ba6b3b565f9ff211992bf9 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Thu, 17 Apr 2025 21:37:03 +0200 Subject: [PATCH 236/266] remove stray file --- diff | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 diff diff --git a/diff b/diff deleted file mode 100644 index e69de29bb2d1d..0000000000000 From e882ff4e7ebc4653cdc69e57bc656fe558a4af88 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 17 Apr 2025 19:06:46 +0000 Subject: [PATCH 237/266] Don't assemble non-env/bound candidates if projection is rigid --- .../src/solve/assembly/mod.rs | 87 ++++++++++++------- .../src/solve/effect_goals.rs | 3 +- .../src/solve/normalizes_to/mod.rs | 3 +- .../src/solve/trait_goals.rs | 4 +- tests/ui/impl-unused-tps.stderr | 34 ++++---- .../next-solver/rpitit-cycle-due-to-rigid.rs | 32 +++++++ 6 files changed, 107 insertions(+), 56 deletions(-) create mode 100644 tests/ui/traits/next-solver/rpitit-cycle-due-to-rigid.rs diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs index 83b2465d05aa7..ecb57cc0ad71b 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs @@ -288,6 +288,21 @@ where ) -> Vec>; } +/// Allows callers of `assemble_and_evaluate_candidates` to choose whether to limit +/// candidate assembly to param-env and alias-bound candidates. +/// +/// On top of being a micro-optimization, as it avoids doing unnecessary work when +/// a param-env trait bound candidate shadows impls for normalization, this is also +/// required to prevent query cycles due to RPITIT inference. See the issue at: +/// . +pub(super) enum AssembleCandidatesFrom { + All, + /// Only assemble candidates from the environment and alias bounds, ignoring + /// user-written and built-in impls. We only expect `ParamEnv` and `AliasBound` + /// candidates to be assembled. + EnvAndBounds, +} + impl EvalCtxt<'_, D> where D: SolverDelegate, @@ -296,6 +311,7 @@ where pub(super) fn assemble_and_evaluate_candidates>( &mut self, goal: Goal, + assemble_from: AssembleCandidatesFrom, ) -> Vec> { let Ok(normalized_self_ty) = self.structurally_normalize_ty(goal.param_env, goal.predicate.self_ty()) @@ -322,16 +338,18 @@ where } } - self.assemble_impl_candidates(goal, &mut candidates); - - self.assemble_builtin_impl_candidates(goal, &mut candidates); - self.assemble_alias_bound_candidates(goal, &mut candidates); - - self.assemble_object_bound_candidates(goal, &mut candidates); - self.assemble_param_env_candidates(goal, &mut candidates); + match assemble_from { + AssembleCandidatesFrom::All => { + self.assemble_impl_candidates(goal, &mut candidates); + self.assemble_builtin_impl_candidates(goal, &mut candidates); + self.assemble_object_bound_candidates(goal, &mut candidates); + } + AssembleCandidatesFrom::EnvAndBounds => {} + } + candidates } @@ -754,6 +772,9 @@ where }) } + /// Assemble and merge candidates for goals which are related to an underlying trait + /// goal. Right now, this is normalizes-to and host effect goals. + /// /// We sadly can't simply take all possible candidates for normalization goals /// and check whether they result in the same constraints. We want to make sure /// that trying to normalize an alias doesn't result in constraints which aren't @@ -782,47 +803,44 @@ where /// /// See trait-system-refactor-initiative#124 for more details. #[instrument(level = "debug", skip(self, inject_normalize_to_rigid_candidate), ret)] - pub(super) fn merge_candidates( + pub(super) fn assemble_and_merge_candidates>( &mut self, proven_via: Option, - candidates: Vec>, + goal: Goal, inject_normalize_to_rigid_candidate: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResult, ) -> QueryResult { let Some(proven_via) = proven_via else { // We don't care about overflow. If proving the trait goal overflowed, then // it's enough to report an overflow error for that, we don't also have to // overflow during normalization. - return Ok(self.make_ambiguous_response_no_constraints(MaybeCause::Ambiguity)); + // + // We use `forced_ambiguity` here over `make_ambiguous_response_no_constraints` + // because the former will also record a built-in candidate in the inspector. + return self.forced_ambiguity(MaybeCause::Ambiguity).map(|cand| cand.result); }; match proven_via { TraitGoalProvenVia::ParamEnv | TraitGoalProvenVia::AliasBound => { - let mut considered_candidates = Vec::new(); - considered_candidates.extend( - candidates - .iter() - .filter(|c| matches!(c.source, CandidateSource::ParamEnv(_))) - .map(|c| c.result), - ); - // Even when a trait bound has been proven using a where-bound, we // still need to consider alias-bounds for normalization, see - // tests/ui/next-solver/alias-bound-shadowed-by-env.rs. - // + // `tests/ui/next-solver/alias-bound-shadowed-by-env.rs`. + let candidates_from_env_and_bounds: Vec<_> = self + .assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::EnvAndBounds); + // We still need to prefer where-bounds over alias-bounds however. - // See tests/ui/winnowing/norm-where-bound-gt-alias-bound.rs. - // - // FIXME(const_trait_impl): should this behavior also be used by - // constness checking. Doing so is *at least theoretically* breaking, - // see github.com/rust-lang/rust/issues/133044#issuecomment-2500709754 - if considered_candidates.is_empty() { - considered_candidates.extend( - candidates - .iter() - .filter(|c| matches!(c.source, CandidateSource::AliasBound)) - .map(|c| c.result), - ); - } + // See `tests/ui/winnowing/norm-where-bound-gt-alias-bound.rs`. + let mut considered_candidates: Vec<_> = if candidates_from_env_and_bounds + .iter() + .any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) + { + candidates_from_env_and_bounds + .into_iter() + .filter(|c| matches!(c.source, CandidateSource::ParamEnv(_))) + .map(|c| c.result) + .collect() + } else { + candidates_from_env_and_bounds.into_iter().map(|c| c.result).collect() + }; // If the trait goal has been proven by using the environment, we want to treat // aliases as rigid if there are no applicable projection bounds in the environment. @@ -839,6 +857,9 @@ where } } TraitGoalProvenVia::Misc => { + let candidates = + self.assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::All); + // Prefer "orphaned" param-env normalization predicates, which are used // (for example, and ideally only) when proving item bounds for an impl. let candidates_from_env: Vec<_> = candidates diff --git a/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs b/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs index 0b61c368d8e8d..7752a705cd145 100644 --- a/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs @@ -399,12 +399,11 @@ where &mut self, goal: Goal>, ) -> QueryResult { - let candidates = self.assemble_and_evaluate_candidates(goal); let (_, proven_via) = self.probe(|_| ProbeKind::ShadowedEnvProbing).enter(|ecx| { let trait_goal: Goal> = goal.with(ecx.cx(), goal.predicate.trait_ref); ecx.compute_trait_goal(trait_goal) })?; - self.merge_candidates(proven_via, candidates, |_ecx| Err(NoSolution)) + self.assemble_and_merge_candidates(proven_via, goal, |_ecx| Err(NoSolution)) } } diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs index fdeb276a58e69..9466901683e21 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs @@ -32,14 +32,13 @@ where let cx = self.cx(); match goal.predicate.alias.kind(cx) { ty::AliasTermKind::ProjectionTy | ty::AliasTermKind::ProjectionConst => { - let candidates = self.assemble_and_evaluate_candidates(goal); let trait_ref = goal.predicate.alias.trait_ref(cx); let (_, proven_via) = self.probe(|_| ProbeKind::ShadowedEnvProbing).enter(|ecx| { let trait_goal: Goal> = goal.with(cx, trait_ref); ecx.compute_trait_goal(trait_goal) })?; - self.merge_candidates(proven_via, candidates, |ecx| { + self.assemble_and_merge_candidates(proven_via, goal, |ecx| { ecx.probe(|&result| ProbeKind::RigidAlias { result }).enter(|this| { this.structurally_instantiate_normalizes_to_term( goal, diff --git a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs index 409af8568d7a3..7bd1300f34ed7 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -13,7 +13,7 @@ use tracing::{instrument, trace}; use crate::delegate::SolverDelegate; use crate::solve::assembly::structural_traits::{self, AsyncCallableRelevantTypes}; -use crate::solve::assembly::{self, Candidate}; +use crate::solve::assembly::{self, AssembleCandidatesFrom, Candidate}; use crate::solve::inspect::ProbeKind; use crate::solve::{ BuiltinImplSource, CandidateSource, Certainty, EvalCtxt, Goal, GoalSource, MaybeCause, @@ -1365,7 +1365,7 @@ where &mut self, goal: Goal>, ) -> Result<(CanonicalResponse, Option), NoSolution> { - let candidates = self.assemble_and_evaluate_candidates(goal); + let candidates = self.assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::All); self.merge_trait_candidates(goal, candidates) } } diff --git a/tests/ui/impl-unused-tps.stderr b/tests/ui/impl-unused-tps.stderr index 09c3fce641cfe..eff5ffff9b6ac 100644 --- a/tests/ui/impl-unused-tps.stderr +++ b/tests/ui/impl-unused-tps.stderr @@ -7,23 +7,6 @@ LL | impl Foo for [isize; 0] { LL | impl Foo for U { | ^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `[isize; 0]` -error[E0207]: the type parameter `U` is not constrained by the impl trait, self type, or predicates - --> $DIR/impl-unused-tps.rs:32:9 - | -LL | impl Bar for T { - | ^ unconstrained type parameter - -error[E0119]: conflicting implementations of trait `Bar` - --> $DIR/impl-unused-tps.rs:40:1 - | -LL | impl Bar for T { - | -------------------- first implementation here -... -LL | / impl Bar for T -LL | | where -LL | | T: Bar, - | |____________________^ conflicting implementation - error[E0119]: conflicting implementations of trait `Foo<[isize; 0]>` for type `[isize; 0]` --> $DIR/impl-unused-tps.rs:49:1 | @@ -52,6 +35,12 @@ error[E0207]: the type parameter `U` is not constrained by the impl trait, self LL | impl Foo for [isize; 1] { | ^ unconstrained type parameter +error[E0207]: the type parameter `U` is not constrained by the impl trait, self type, or predicates + --> $DIR/impl-unused-tps.rs:32:9 + | +LL | impl Bar for T { + | ^ unconstrained type parameter + error[E0207]: the type parameter `U` is not constrained by the impl trait, self type, or predicates --> $DIR/impl-unused-tps.rs:40:9 | @@ -70,6 +59,17 @@ error[E0207]: the type parameter `V` is not constrained by the impl trait, self LL | impl Foo for T | ^ unconstrained type parameter +error[E0119]: conflicting implementations of trait `Bar` + --> $DIR/impl-unused-tps.rs:40:1 + | +LL | impl Bar for T { + | -------------------- first implementation here +... +LL | / impl Bar for T +LL | | where +LL | | T: Bar, + | |____________________^ conflicting implementation + error: aborting due to 9 previous errors Some errors have detailed explanations: E0119, E0207. diff --git a/tests/ui/traits/next-solver/rpitit-cycle-due-to-rigid.rs b/tests/ui/traits/next-solver/rpitit-cycle-due-to-rigid.rs new file mode 100644 index 0000000000000..ec3d710ef3719 --- /dev/null +++ b/tests/ui/traits/next-solver/rpitit-cycle-due-to-rigid.rs @@ -0,0 +1,32 @@ +//@ compile-flags: -Znext-solver +//@ check-pass +//@ edition: 2024 + +// Ensure we don't end up in a query cycle due to trying to assemble an impl candidate +// for an RPITIT normalizes-to goal, even though that impl candidate would *necessarily* +// be made rigid by a where clause. This query cycle is thus avoidable by not assembling +// that impl candidate which we *know* we are going to throw away anyways. + +use std::future::Future; + +pub trait ReactiveFunction: Send { + type Output; + + fn invoke(self) -> Self::Output; +} + +trait AttributeValue { + fn resolve(self) -> impl Future + Send; +} + +impl AttributeValue for F +where + F: ReactiveFunction, + V: AttributeValue, +{ + async fn resolve(self) { + self.invoke().resolve().await + } +} + +fn main() {} From 136171c8d8c81ff8de4446fb4bb339a1bd475a49 Mon Sep 17 00:00:00 2001 From: Manuel Drehwald Date: Fri, 18 Apr 2025 00:58:04 -0400 Subject: [PATCH 238/266] skip llvm-config in autodiff check builds, when its unavailable --- src/bootstrap/src/core/build_steps/compile.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index dab58fccf5e68..106a04de5d9a7 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -1194,8 +1194,7 @@ pub fn rustc_cargo( let enzyme_dir = builder.build.out.join(arch).join("enzyme").join("lib"); cargo.rustflag("-L").rustflag(enzyme_dir.to_str().expect("Invalid path")); - if !builder.config.dry_run() { - let llvm_config = builder.llvm_config(builder.config.build).unwrap(); + if let Some(llvm_config) = builder.llvm_config(builder.config.build) { let llvm_version_major = llvm::get_llvm_version_major(builder, &llvm_config); cargo.rustflag("-l").rustflag(&format!("Enzyme-{llvm_version_major}")); } From 65ce38a4c96da2f950fb6b181b2b83b0320d103d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Fri, 18 Apr 2025 12:32:19 +0200 Subject: [PATCH 239/266] Add a note that explains the counts --- src/ci/citool/templates/test_suites.askama | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/ci/citool/templates/test_suites.askama b/src/ci/citool/templates/test_suites.askama index d36e85228e2b0..4997f6a3f1c9a 100644 --- a/src/ci/citool/templates/test_suites.askama +++ b/src/ci/citool/templates/test_suites.askama @@ -2,6 +2,10 @@ {% block content %}

      Rust CI test dashboard

      +
      +Here's how to interpret the "passed" and "ignored" counts: +the count includes all combinations of "stage" x "target" x "CI job where the test was executed or ignored". +
      From b18e37305304780530224736ad55145063c7e8a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Fri, 18 Apr 2025 12:44:39 +0200 Subject: [PATCH 240/266] Reduce duplicated test prefixes in nested subdirectories `assembly/asm` contained a test named `asm/aarch64-el2vmsa.rs`, while it should have been only `arch64-el2vmsa.rs`. --- src/ci/citool/src/test_dashboard.rs | 36 +++++++++-------------- src/ci/citool/templates/test_group.askama | 6 ++-- 2 files changed, 17 insertions(+), 25 deletions(-) diff --git a/src/ci/citool/src/test_dashboard.rs b/src/ci/citool/src/test_dashboard.rs index c16385baa3ba4..8fbd0d3f200d4 100644 --- a/src/ci/citool/src/test_dashboard.rs +++ b/src/ci/citool/src/test_dashboard.rs @@ -64,9 +64,10 @@ fn gather_test_suites(job_metrics: &HashMap) -> TestSuites Some((name, variant)) => (name.to_string(), variant.to_string()), None => (test_name, "".to_string()), }; - let test_entry = suite_entry.tests.entry(test_name.clone()).or_insert_with(|| { - Test { name: test_name.clone(), revisions: Default::default() } - }); + let test_entry = suite_entry + .tests + .entry(test_name.clone()) + .or_insert_with(|| Test { revisions: Default::default() }); let variant_entry = test_entry .revisions .entry(variant_name) @@ -91,16 +92,12 @@ fn gather_test_suites(job_metrics: &HashMap) -> TestSuites let mut suites = suites.into_iter().collect::>(); suites.sort_by(|a, b| a.0.cmp(&b.0)); - let mut target_suites = vec![]; - for (suite_name, suite) in suites { - let suite = TestSuite { - name: suite_name.clone(), - group: build_test_group(&suite_name, suite.tests), - }; - target_suites.push(suite); - } + let suites = suites + .into_iter() + .map(|(suite_name, suite)| TestSuite { group: build_test_group(&suite_name, suite.tests) }) + .collect(); - TestSuites { suites: target_suites } + TestSuites { suites } } /// Recursively expand a test group based on filesystem hierarchy. @@ -115,7 +112,7 @@ fn build_test_group<'a>(name: &str, tests: BTreeMap>) -> TestGr if components.peek().is_none() { // This is a root test - root_tests.push(test); + root_tests.push((name, test)); } else { // This is a test in a nested directory let subdir_tests = @@ -148,7 +145,6 @@ fn normalize_test_name(name: &str, suite_name: &str) -> String { name.trim_start_matches("/").to_string() } -#[derive(serde::Serialize)] struct TestSuites<'a> { suites: Vec>, } @@ -159,21 +155,16 @@ impl<'a> TestSuites<'a> { } } -#[derive(serde::Serialize)] struct TestSuite<'a> { - name: String, group: TestGroup<'a>, } -#[derive(Debug, serde::Serialize)] struct TestResults<'a> { passed: Vec>, ignored: Vec>, } -#[derive(Debug, serde::Serialize)] struct Test<'a> { - name: String, revisions: BTreeMap>, } @@ -189,7 +180,8 @@ impl<'a> Test<'a> { } } -#[derive(Clone, Copy, Debug, serde::Serialize)] +#[derive(Clone, Copy)] +#[allow(dead_code)] struct TestMetadata<'a> { job: &'a str, stage: u32, @@ -198,13 +190,13 @@ struct TestMetadata<'a> { // We have to use a template for the TestGroup instead of a macro, because // macros cannot be recursive in askama at the moment. -#[derive(Template, serde::Serialize)] +#[derive(Template)] #[template(path = "test_group.askama")] /// Represents a group of tests struct TestGroup<'a> { name: String, /// Tests located directly in this directory - root_tests: Vec>, + root_tests: Vec<(String, Test<'a>)>, /// Nested directories with additional tests groups: Vec<(String, TestGroup<'a>)>, } diff --git a/src/ci/citool/templates/test_group.askama b/src/ci/citool/templates/test_group.askama index bdf32d00f4a19..95731103f3b9d 100644 --- a/src/ci/citool/templates/test_group.askama +++ b/src/ci/citool/templates/test_group.askama @@ -21,12 +21,12 @@ passed: {{ r.passed.len() }}, ignored: {{ r.ignored.len() }} {% if !root_tests.is_empty() %}
        - {% for test in root_tests %} + {% for (name, test) in root_tests %}
      • {% if let Some(result) = test.single_test() %} - {{ test.name }} ({% call test_result(result) %}) + {{ name }} ({% call test_result(result) %}) {% else %} - {{ test.name }} ({{ test.revisions.len() }} revision{{ test.revisions.len() | pluralize }}) + {{ name }} ({{ test.revisions.len() }} revision{{ test.revisions.len() | pluralize }})
          {% for (revision, result) in test.revisions %}
        • #{{ revision }} ({% call test_result(result) %})
        • From 1b393025718ca9c75d67e82b55a390e3506e536c Mon Sep 17 00:00:00 2001 From: roblabla Date: Fri, 18 Apr 2025 13:30:26 +0200 Subject: [PATCH 241/266] Disable has_thread_local on i686-win7-windows-msvc On Windows 7 32-bit, the alignment characteristic of the TLS Directory don't appear to be respected by the PE Loader, leading to crashes. As a result, let's disable has_thread_local to make sure TLS goes through the emulation layer. --- .../rustc_target/src/spec/targets/i686_win7_windows_msvc.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs index 233a1c4fd7a54..91ab311109787 100644 --- a/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs @@ -7,6 +7,12 @@ pub(crate) fn target() -> Target { base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.supported_sanitizers = SanitizerSet::ADDRESS; + // On Windows 7 32-bit, the alignment characteristic of the TLS Directory + // don't appear to be respected by the PE Loader, leading to crashes. As + // a result, let's disable has_thread_local to make sure TLS goes through + // the emulation layer. + // See https://github.com/rust-lang/rust/issues/138903 + base.has_thread_local = false; base.add_pre_link_args( LinkerFlavor::Msvc(Lld::No), From 8f6ef1f1f6a4fcec0325e4ff6fa50b8f42f853aa Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 18 Apr 2025 13:35:49 +0200 Subject: [PATCH 242/266] Improve `clean_maybe_renamed_item` function code a bit --- src/librustdoc/clean/mod.rs | 47 ++++++++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index fe9dc9a9e2145..a693d9f8564e9 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2797,10 +2797,35 @@ fn clean_maybe_renamed_item<'tcx>( ) -> Vec { use hir::ItemKind; - let def_id = item.owner_id.to_def_id(); - let mut name = if renamed.is_some() { renamed } else { cx.tcx.hir_opt_name(item.hir_id()) }; + fn get_name( + cx: &DocContext<'_>, + item: &hir::Item<'_>, + renamed: Option, + ) -> Option { + renamed.or_else(|| cx.tcx.hir_opt_name(item.hir_id())) + } + let def_id = item.owner_id.to_def_id(); cx.with_param_env(def_id, |cx| { + // These kinds of item either don't need a `name` or accept a `None` one so we handle them + // before. + match item.kind { + ItemKind::Impl(impl_) => return clean_impl(impl_, item.owner_id.def_id, cx), + ItemKind::Use(path, kind) => { + return clean_use_statement( + item, + get_name(cx, item, renamed), + path, + kind, + cx, + &mut FxHashSet::default(), + ); + } + _ => {} + } + + let mut name = get_name(cx, item, renamed).unwrap(); + let kind = match item.kind { ItemKind::Static(_, ty, mutability, body_id) => StaticItem(Static { type_: Box::new(clean_ty(ty, cx)), @@ -2839,7 +2864,7 @@ fn clean_maybe_renamed_item<'tcx>( item_type: Some(type_), })), item.owner_id.def_id.to_def_id(), - name.unwrap(), + name, import_id, renamed, )); @@ -2862,17 +2887,14 @@ fn clean_maybe_renamed_item<'tcx>( generics: clean_generics(generics, cx), fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(), }), - ItemKind::Impl(impl_) => return clean_impl(impl_, item.owner_id.def_id, cx), ItemKind::Macro(_, macro_def, MacroKind::Bang) => MacroItem(Macro { - source: display_macro_source(cx, name.unwrap(), macro_def), + source: display_macro_source(cx, name, macro_def), macro_rules: macro_def.macro_rules, }), - ItemKind::Macro(_, _, macro_kind) => { - clean_proc_macro(item, name.as_mut().unwrap(), macro_kind, cx) - } + ItemKind::Macro(_, _, macro_kind) => clean_proc_macro(item, &mut name, macro_kind, cx), // proc macros can have a name set by attributes ItemKind::Fn { ref sig, generics, body: body_id, .. } => { - clean_fn_or_proc_macro(item, sig, generics, body_id, name.as_mut().unwrap(), cx) + clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx) } ItemKind::Trait(_, _, _, generics, bounds, item_ids) => { let items = item_ids @@ -2888,10 +2910,7 @@ fn clean_maybe_renamed_item<'tcx>( })) } ItemKind::ExternCrate(orig_name, _) => { - return clean_extern_crate(item, name.unwrap(), orig_name, cx); - } - ItemKind::Use(path, kind) => { - return clean_use_statement(item, name, path, kind, cx, &mut FxHashSet::default()); + return clean_extern_crate(item, name, orig_name, cx); } _ => span_bug!(item.span, "not yet converted"), }; @@ -2900,7 +2919,7 @@ fn clean_maybe_renamed_item<'tcx>( cx, kind, item.owner_id.def_id.to_def_id(), - name.unwrap(), + name, import_id, renamed, )] From ac7d1be031ac08cc0910efa3ec2f4186d7943792 Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Wed, 16 Apr 2025 20:54:15 +0300 Subject: [PATCH 243/266] add coverage on config include logic Signed-off-by: onur-ozkan --- src/bootstrap/src/core/config/tests.rs | 211 ++++++++++++++++++++++++- 1 file changed, 209 insertions(+), 2 deletions(-) diff --git a/src/bootstrap/src/core/config/tests.rs b/src/bootstrap/src/core/config/tests.rs index d8002ba8467bd..c8a12c9072c91 100644 --- a/src/bootstrap/src/core/config/tests.rs +++ b/src/bootstrap/src/core/config/tests.rs @@ -1,8 +1,8 @@ use std::collections::BTreeSet; -use std::env; use std::fs::{File, remove_file}; use std::io::Write; -use std::path::Path; +use std::path::{Path, PathBuf}; +use std::{env, fs}; use build_helper::ci::CiEnv; use clap::CommandFactory; @@ -23,6 +23,27 @@ pub(crate) fn parse(config: &str) -> Config { ) } +fn get_toml(file: &Path) -> Result { + let contents = std::fs::read_to_string(file).unwrap(); + toml::from_str(&contents).and_then(|table: toml::Value| TomlConfig::deserialize(table)) +} + +/// Helps with debugging by using consistent test-specific directories instead of +/// random temporary directories. +fn prepare_test_specific_dir() -> PathBuf { + let current = std::thread::current(); + // Replace "::" with "_" to make it safe for directory names on Windows systems + let test_path = current.name().unwrap().replace("::", "_"); + + let testdir = parse("").tempdir().join(test_path); + + // clean up any old test files + let _ = fs::remove_dir_all(&testdir); + let _ = fs::create_dir_all(&testdir); + + testdir +} + #[test] fn download_ci_llvm() { let config = parse("llvm.download-ci-llvm = false"); @@ -539,3 +560,189 @@ fn test_ci_flag() { let config = Config::parse_inner(Flags::parse(&["check".into()]), |&_| toml::from_str("")); assert_eq!(config.is_running_on_ci, CiEnv::is_ci()); } + +#[test] +fn test_precedence_of_includes() { + let testdir = prepare_test_specific_dir(); + + let root_config = testdir.join("config.toml"); + let root_config_content = br#" + include = ["./extension.toml"] + + [llvm] + link-jobs = 2 + "#; + File::create(&root_config).unwrap().write_all(root_config_content).unwrap(); + + let extension = testdir.join("extension.toml"); + let extension_content = br#" + change-id=543 + include = ["./extension2.toml"] + "#; + File::create(extension).unwrap().write_all(extension_content).unwrap(); + + let extension = testdir.join("extension2.toml"); + let extension_content = br#" + change-id=742 + + [llvm] + link-jobs = 10 + + [build] + description = "Some creative description" + "#; + File::create(extension).unwrap().write_all(extension_content).unwrap(); + + let config = Config::parse_inner( + Flags::parse(&["check".to_owned(), format!("--config={}", root_config.to_str().unwrap())]), + get_toml, + ); + + assert_eq!(config.change_id.unwrap(), ChangeId::Id(543)); + assert_eq!(config.llvm_link_jobs.unwrap(), 2); + assert_eq!(config.description.unwrap(), "Some creative description"); +} + +#[test] +#[should_panic(expected = "Cyclic inclusion detected")] +fn test_cyclic_include_direct() { + let testdir = prepare_test_specific_dir(); + + let root_config = testdir.join("config.toml"); + let root_config_content = br#" + include = ["./extension.toml"] + "#; + File::create(&root_config).unwrap().write_all(root_config_content).unwrap(); + + let extension = testdir.join("extension.toml"); + let extension_content = br#" + include = ["./config.toml"] + "#; + File::create(extension).unwrap().write_all(extension_content).unwrap(); + + let config = Config::parse_inner( + Flags::parse(&["check".to_owned(), format!("--config={}", root_config.to_str().unwrap())]), + get_toml, + ); +} + +#[test] +#[should_panic(expected = "Cyclic inclusion detected")] +fn test_cyclic_include_indirect() { + let testdir = prepare_test_specific_dir(); + + let root_config = testdir.join("config.toml"); + let root_config_content = br#" + include = ["./extension.toml"] + "#; + File::create(&root_config).unwrap().write_all(root_config_content).unwrap(); + + let extension = testdir.join("extension.toml"); + let extension_content = br#" + include = ["./extension2.toml"] + "#; + File::create(extension).unwrap().write_all(extension_content).unwrap(); + + let extension = testdir.join("extension2.toml"); + let extension_content = br#" + include = ["./extension3.toml"] + "#; + File::create(extension).unwrap().write_all(extension_content).unwrap(); + + let extension = testdir.join("extension3.toml"); + let extension_content = br#" + include = ["./extension.toml"] + "#; + File::create(extension).unwrap().write_all(extension_content).unwrap(); + + let config = Config::parse_inner( + Flags::parse(&["check".to_owned(), format!("--config={}", root_config.to_str().unwrap())]), + get_toml, + ); +} + +#[test] +fn test_include_absolute_paths() { + let testdir = prepare_test_specific_dir(); + + let extension = testdir.join("extension.toml"); + File::create(&extension).unwrap().write_all(&[]).unwrap(); + + let root_config = testdir.join("config.toml"); + let extension_absolute_path = + extension.canonicalize().unwrap().to_str().unwrap().replace('\\', r"\\"); + let root_config_content = format!(r#"include = ["{}"]"#, extension_absolute_path); + File::create(&root_config).unwrap().write_all(root_config_content.as_bytes()).unwrap(); + + let config = Config::parse_inner( + Flags::parse(&["check".to_owned(), format!("--config={}", root_config.to_str().unwrap())]), + get_toml, + ); +} + +#[test] +fn test_include_relative_paths() { + let testdir = prepare_test_specific_dir(); + + let _ = fs::create_dir_all(&testdir.join("subdir/another_subdir")); + + let root_config = testdir.join("config.toml"); + let root_config_content = br#" + include = ["./subdir/extension.toml"] + "#; + File::create(&root_config).unwrap().write_all(root_config_content).unwrap(); + + let extension = testdir.join("subdir/extension.toml"); + let extension_content = br#" + include = ["../extension2.toml"] + "#; + File::create(extension).unwrap().write_all(extension_content).unwrap(); + + let extension = testdir.join("extension2.toml"); + let extension_content = br#" + include = ["./subdir/another_subdir/extension3.toml"] + "#; + File::create(extension).unwrap().write_all(extension_content).unwrap(); + + let extension = testdir.join("subdir/another_subdir/extension3.toml"); + let extension_content = br#" + include = ["../../extension4.toml"] + "#; + File::create(extension).unwrap().write_all(extension_content).unwrap(); + + let extension = testdir.join("extension4.toml"); + File::create(extension).unwrap().write_all(&[]).unwrap(); + + let config = Config::parse_inner( + Flags::parse(&["check".to_owned(), format!("--config={}", root_config.to_str().unwrap())]), + get_toml, + ); +} + +#[test] +fn test_include_precedence_over_profile() { + let testdir = prepare_test_specific_dir(); + + let root_config = testdir.join("config.toml"); + let root_config_content = br#" + profile = "dist" + include = ["./extension.toml"] + "#; + File::create(&root_config).unwrap().write_all(root_config_content).unwrap(); + + let extension = testdir.join("extension.toml"); + let extension_content = br#" + [rust] + channel = "dev" + "#; + File::create(extension).unwrap().write_all(extension_content).unwrap(); + + let config = Config::parse_inner( + Flags::parse(&["check".to_owned(), format!("--config={}", root_config.to_str().unwrap())]), + get_toml, + ); + + // "dist" profile would normally set the channel to "auto-detect", but includes should + // override profile settings, so we expect this to be "dev" here. + assert_eq!(config.channel, "dev"); +} From 65b87aae21096c0f22d141ceaf7030ebdf6edbe4 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 17 Apr 2025 15:05:06 -0400 Subject: [PATCH 244/266] Support new target builtins --- src/intrinsic/llvm.rs | 245 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 244 insertions(+), 1 deletion(-) diff --git a/src/intrinsic/llvm.rs b/src/intrinsic/llvm.rs index 2b172cdfed3ad..e030e3b4ff280 100644 --- a/src/intrinsic/llvm.rs +++ b/src/intrinsic/llvm.rs @@ -1,11 +1,86 @@ use std::borrow::Cow; -use gccjit::{CType, Context, Function, FunctionPtrType, RValue, ToRValue}; +use gccjit::{CType, Context, Field, Function, FunctionPtrType, RValue, ToRValue, Type}; use rustc_codegen_ssa::traits::BuilderMethods; use crate::builder::Builder; use crate::context::CodegenCx; +fn encode_key_128_type<'a, 'gcc, 'tcx>( + builder: &Builder<'a, 'gcc, 'tcx>, +) -> (Type<'gcc>, Field<'gcc>, Field<'gcc>) { + let m128i = builder.context.new_vector_type(builder.i64_type, 2); + let field1 = builder.context.new_field(None, builder.u32_type, "field1"); + let field2 = builder.context.new_field(None, m128i, "field2"); + let field3 = builder.context.new_field(None, m128i, "field3"); + let field4 = builder.context.new_field(None, m128i, "field4"); + let field5 = builder.context.new_field(None, m128i, "field5"); + let field6 = builder.context.new_field(None, m128i, "field6"); + let field7 = builder.context.new_field(None, m128i, "field7"); + let encode_type = builder.context.new_struct_type( + None, + "EncodeKey128Output", + &[field1, field2, field3, field4, field5, field6, field7], + ); + encode_type.as_type().set_packed(); + (encode_type.as_type(), field1, field2) +} + +fn encode_key_256_type<'a, 'gcc, 'tcx>( + builder: &Builder<'a, 'gcc, 'tcx>, +) -> (Type<'gcc>, Field<'gcc>, Field<'gcc>) { + let m128i = builder.context.new_vector_type(builder.i64_type, 2); + let field1 = builder.context.new_field(None, builder.u32_type, "field1"); + let field2 = builder.context.new_field(None, m128i, "field2"); + let field3 = builder.context.new_field(None, m128i, "field3"); + let field4 = builder.context.new_field(None, m128i, "field4"); + let field5 = builder.context.new_field(None, m128i, "field5"); + let field6 = builder.context.new_field(None, m128i, "field6"); + let field7 = builder.context.new_field(None, m128i, "field7"); + let field8 = builder.context.new_field(None, m128i, "field8"); + let encode_type = builder.context.new_struct_type( + None, + "EncodeKey256Output", + &[field1, field2, field3, field4, field5, field6, field7, field8], + ); + encode_type.as_type().set_packed(); + (encode_type.as_type(), field1, field2) +} + +fn aes_output_type<'a, 'gcc, 'tcx>( + builder: &Builder<'a, 'gcc, 'tcx>, +) -> (Type<'gcc>, Field<'gcc>, Field<'gcc>) { + let m128i = builder.context.new_vector_type(builder.i64_type, 2); + let field1 = builder.context.new_field(None, builder.u8_type, "field1"); + let field2 = builder.context.new_field(None, m128i, "field2"); + let aes_output_type = builder.context.new_struct_type(None, "AesOutput", &[field1, field2]); + let typ = aes_output_type.as_type(); + typ.set_packed(); + (typ, field1, field2) +} + +fn wide_aes_output_type<'a, 'gcc, 'tcx>( + builder: &Builder<'a, 'gcc, 'tcx>, +) -> (Type<'gcc>, Field<'gcc>, Field<'gcc>) { + let m128i = builder.context.new_vector_type(builder.i64_type, 2); + let field1 = builder.context.new_field(None, builder.u8_type, "field1"); + let field2 = builder.context.new_field(None, m128i, "field2"); + let field3 = builder.context.new_field(None, m128i, "field3"); + let field4 = builder.context.new_field(None, m128i, "field4"); + let field5 = builder.context.new_field(None, m128i, "field5"); + let field6 = builder.context.new_field(None, m128i, "field6"); + let field7 = builder.context.new_field(None, m128i, "field7"); + let field8 = builder.context.new_field(None, m128i, "field8"); + let field9 = builder.context.new_field(None, m128i, "field9"); + let aes_output_type = builder.context.new_struct_type( + None, + "WideAesOutput", + &[field1, field2, field3, field4, field5, field6, field7, field8, field9], + ); + aes_output_type.as_type().set_packed(); + (aes_output_type.as_type(), field1, field2) +} + #[cfg_attr(not(feature = "master"), allow(unused_variables))] pub fn adjust_function<'gcc>( context: &'gcc Context<'gcc>, @@ -503,6 +578,74 @@ pub fn adjust_intrinsic_arguments<'a, 'b, 'gcc, 'tcx>( let arg4 = builder.context.new_rvalue_from_int(arg4_type, -1); args = vec![a, b, c, arg4, new_args[3]].into(); } + "__builtin_ia32_encodekey128_u32" => { + let mut new_args = args.to_vec(); + let m128i = builder.context.new_vector_type(builder.i64_type, 2); + let array_type = builder.context.new_array_type(None, m128i, 6); + let result = builder.current_func().new_local(None, array_type, "result"); + new_args.push(result.get_address(None)); + args = new_args.into(); + } + "__builtin_ia32_encodekey256_u32" => { + let mut new_args = args.to_vec(); + let m128i = builder.context.new_vector_type(builder.i64_type, 2); + let array_type = builder.context.new_array_type(None, m128i, 7); + let result = builder.current_func().new_local(None, array_type, "result"); + new_args.push(result.get_address(None)); + args = new_args.into(); + } + "__builtin_ia32_aesenc128kl_u8" + | "__builtin_ia32_aesdec128kl_u8" + | "__builtin_ia32_aesenc256kl_u8" + | "__builtin_ia32_aesdec256kl_u8" => { + let mut new_args = vec![]; + // TODO: directly create a variable of type m128i instead of the whole struct? + let (aes_output_type, _, field2) = aes_output_type(builder); + let result = builder.current_func().new_local(None, aes_output_type, "result"); + let field2 = result.access_field(None, field2); + new_args.push(field2.get_address(None)); + new_args.extend(args.to_vec()); + args = new_args.into(); + } + "__builtin_ia32_aesencwide128kl_u8" + | "__builtin_ia32_aesdecwide128kl_u8" + | "__builtin_ia32_aesencwide256kl_u8" + | "__builtin_ia32_aesdecwide256kl_u8" => { + let mut new_args = vec![]; + + let mut old_args = args.to_vec(); + let handle = old_args.swap_remove(0); // Called __P in GCC. + let first_value = old_args.swap_remove(0); + + let element_type = first_value.get_type(); + let array_type = builder.context.new_array_type(None, element_type, 8); + let result = builder.current_func().new_local(None, array_type, "result"); + new_args.push(result.get_address(None)); + + let array = builder.current_func().new_local(None, array_type, "array"); + let input = builder.context.new_array_constructor( + None, + array_type, + &[ + first_value, + old_args.swap_remove(0), + old_args.swap_remove(0), + old_args.swap_remove(0), + old_args.swap_remove(0), + old_args.swap_remove(0), + old_args.swap_remove(0), + old_args.swap_remove(0), + ], + ); + builder.llbb().add_assignment(None, array, input); + let input_ptr = array.get_address(None); + let arg2_type = gcc_func.get_param_type(1); + let input_ptr = builder.context.new_cast(None, input_ptr, arg2_type); + new_args.push(input_ptr); + + new_args.push(handle); + args = new_args.into(); + } _ => (), } } else { @@ -700,6 +843,96 @@ pub fn adjust_intrinsic_return_value<'a, 'gcc, 'tcx>( let f16_type = builder.context.new_c_type(CType::Float16); return_value = builder.context.new_cast(None, return_value, f16_type); } + "__builtin_ia32_encodekey128_u32" => { + // The builtin __builtin_ia32_encodekey128_u32 writes the result in its pointer argument while + // llvm.x86.encodekey128 returns a value. + // We added a result pointer argument and now need to assign its value to the return_value expected by + // the LLVM intrinsic. + let (encode_type, field1, field2) = encode_key_128_type(builder); + let result = builder.current_func().new_local(None, encode_type, "result"); + let field1 = result.access_field(None, field1); + builder.llbb().add_assignment(None, field1, return_value); + let field2 = result.access_field(None, field2); + let field2_type = field2.to_rvalue().get_type(); + let array_type = builder.context.new_array_type(None, field2_type, 6); + let ptr = builder.context.new_cast(None, args[2], array_type.make_pointer()); + let field2_ptr = + builder.context.new_cast(None, field2.get_address(None), array_type.make_pointer()); + builder.llbb().add_assignment( + None, + field2_ptr.dereference(None), + ptr.dereference(None), + ); + return_value = result.to_rvalue(); + } + "__builtin_ia32_encodekey256_u32" => { + // The builtin __builtin_ia32_encodekey256_u32 writes the result in its pointer argument while + // llvm.x86.encodekey256 returns a value. + // We added a result pointer argument and now need to assign its value to the return_value expected by + // the LLVM intrinsic. + let (encode_type, field1, field2) = encode_key_256_type(builder); + let result = builder.current_func().new_local(None, encode_type, "result"); + let field1 = result.access_field(None, field1); + builder.llbb().add_assignment(None, field1, return_value); + let field2 = result.access_field(None, field2); + let field2_type = field2.to_rvalue().get_type(); + let array_type = builder.context.new_array_type(None, field2_type, 7); + let ptr = builder.context.new_cast(None, args[3], array_type.make_pointer()); + let field2_ptr = + builder.context.new_cast(None, field2.get_address(None), array_type.make_pointer()); + builder.llbb().add_assignment( + None, + field2_ptr.dereference(None), + ptr.dereference(None), + ); + return_value = result.to_rvalue(); + } + "__builtin_ia32_aesdec128kl_u8" + | "__builtin_ia32_aesenc128kl_u8" + | "__builtin_ia32_aesdec256kl_u8" + | "__builtin_ia32_aesenc256kl_u8" => { + // The builtin for aesdec/aesenc writes the result in its pointer argument while + // llvm.x86.aesdec128kl returns a value. + // We added a result pointer argument and now need to assign its value to the return_value expected by + // the LLVM intrinsic. + let (aes_output_type, field1, field2) = aes_output_type(builder); + let result = builder.current_func().new_local(None, aes_output_type, "result"); + let field1 = result.access_field(None, field1); + builder.llbb().add_assignment(None, field1, return_value); + let field2 = result.access_field(None, field2); + let ptr = builder.context.new_cast( + None, + args[0], + field2.to_rvalue().get_type().make_pointer(), + ); + builder.llbb().add_assignment(None, field2, ptr.dereference(None)); + return_value = result.to_rvalue(); + } + "__builtin_ia32_aesencwide128kl_u8" + | "__builtin_ia32_aesdecwide128kl_u8" + | "__builtin_ia32_aesencwide256kl_u8" + | "__builtin_ia32_aesdecwide256kl_u8" => { + // The builtin for aesdecwide/aesencwide writes the result in its pointer argument while + // llvm.x86.aesencwide128kl returns a value. + // We added a result pointer argument and now need to assign its value to the return_value expected by + // the LLVM intrinsic. + let (aes_output_type, field1, field2) = wide_aes_output_type(builder); + let result = builder.current_func().new_local(None, aes_output_type, "result"); + let field1 = result.access_field(None, field1); + builder.llbb().add_assignment(None, field1, return_value); + let field2 = result.access_field(None, field2); + let field2_type = field2.to_rvalue().get_type(); + let array_type = builder.context.new_array_type(None, field2_type, 8); + let ptr = builder.context.new_cast(None, args[0], array_type.make_pointer()); + let field2_ptr = + builder.context.new_cast(None, field2.get_address(None), array_type.make_pointer()); + builder.llbb().add_assignment( + None, + field2_ptr.dereference(None), + ptr.dereference(None), + ); + return_value = result.to_rvalue(); + } _ => (), } @@ -1284,6 +1517,16 @@ pub fn intrinsic<'gcc, 'tcx>(name: &str, cx: &CodegenCx<'gcc, 'tcx>) -> Function "llvm.x86.avx512fp16.mask.vfmadd.cph.256" => "__builtin_ia32_vfmaddcph256_mask3", "llvm.x86.avx512fp16.mask.vfcmadd.cph.128" => "__builtin_ia32_vfcmaddcph128_mask3", "llvm.x86.avx512fp16.mask.vfmadd.cph.128" => "__builtin_ia32_vfmaddcph128_mask3", + "llvm.x86.encodekey128" => "__builtin_ia32_encodekey128_u32", + "llvm.x86.encodekey256" => "__builtin_ia32_encodekey256_u32", + "llvm.x86.aesenc128kl" => "__builtin_ia32_aesenc128kl_u8", + "llvm.x86.aesdec128kl" => "__builtin_ia32_aesdec128kl_u8", + "llvm.x86.aesenc256kl" => "__builtin_ia32_aesenc256kl_u8", + "llvm.x86.aesdec256kl" => "__builtin_ia32_aesdec256kl_u8", + "llvm.x86.aesencwide128kl" => "__builtin_ia32_aesencwide128kl_u8", + "llvm.x86.aesdecwide128kl" => "__builtin_ia32_aesdecwide128kl_u8", + "llvm.x86.aesencwide256kl" => "__builtin_ia32_aesencwide256kl_u8", + "llvm.x86.aesdecwide256kl" => "__builtin_ia32_aesdecwide256kl_u8", // TODO: support the tile builtins: "llvm.x86.ldtilecfg" => "__builtin_trap", From 98dd5a30b32c1311d5a44ebb2c0667a8ff0ef76a Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Fri, 18 Apr 2025 11:45:30 -0400 Subject: [PATCH 245/266] Fix for libgccjit 12 --- src/intrinsic/llvm.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/intrinsic/llvm.rs b/src/intrinsic/llvm.rs index e030e3b4ff280..befb2e17960c5 100644 --- a/src/intrinsic/llvm.rs +++ b/src/intrinsic/llvm.rs @@ -22,6 +22,7 @@ fn encode_key_128_type<'a, 'gcc, 'tcx>( "EncodeKey128Output", &[field1, field2, field3, field4, field5, field6, field7], ); + #[cfg(feature = "master")] encode_type.as_type().set_packed(); (encode_type.as_type(), field1, field2) } @@ -43,6 +44,7 @@ fn encode_key_256_type<'a, 'gcc, 'tcx>( "EncodeKey256Output", &[field1, field2, field3, field4, field5, field6, field7, field8], ); + #[cfg(feature = "master")] encode_type.as_type().set_packed(); (encode_type.as_type(), field1, field2) } @@ -55,6 +57,7 @@ fn aes_output_type<'a, 'gcc, 'tcx>( let field2 = builder.context.new_field(None, m128i, "field2"); let aes_output_type = builder.context.new_struct_type(None, "AesOutput", &[field1, field2]); let typ = aes_output_type.as_type(); + #[cfg(feature = "master")] typ.set_packed(); (typ, field1, field2) } @@ -77,6 +80,7 @@ fn wide_aes_output_type<'a, 'gcc, 'tcx>( "WideAesOutput", &[field1, field2, field3, field4, field5, field6, field7, field8, field9], ); + #[cfg(feature = "master")] aes_output_type.as_type().set_packed(); (aes_output_type.as_type(), field1, field2) } From 52b06872fe92811e5ae5d87bbb3508924525723b Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Fri, 18 Apr 2025 12:07:10 -0400 Subject: [PATCH 246/266] Simplify handling of some SIMD intrinsics --- src/intrinsic/llvm.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/intrinsic/llvm.rs b/src/intrinsic/llvm.rs index befb2e17960c5..0eebd21001a90 100644 --- a/src/intrinsic/llvm.rs +++ b/src/intrinsic/llvm.rs @@ -603,11 +603,9 @@ pub fn adjust_intrinsic_arguments<'a, 'b, 'gcc, 'tcx>( | "__builtin_ia32_aesenc256kl_u8" | "__builtin_ia32_aesdec256kl_u8" => { let mut new_args = vec![]; - // TODO: directly create a variable of type m128i instead of the whole struct? - let (aes_output_type, _, field2) = aes_output_type(builder); - let result = builder.current_func().new_local(None, aes_output_type, "result"); - let field2 = result.access_field(None, field2); - new_args.push(field2.get_address(None)); + let m128i = builder.context.new_vector_type(builder.i64_type, 2); + let result = builder.current_func().new_local(None, m128i, "result"); + new_args.push(result.get_address(None)); new_args.extend(args.to_vec()); args = new_args.into(); } From 59477a8ab21480a5c3da0313ef5a235091d8cbee Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Wed, 16 Apr 2025 15:12:05 +0200 Subject: [PATCH 247/266] Make rustdoc JSON Span column 1-based, just like line numbers --- src/librustdoc/json/conversions.rs | 4 ++-- src/rustdoc-json-types/lib.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index dab23f8e42a3d..f446c9fbbd8b3 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -84,8 +84,8 @@ impl JsonRenderer<'_> { let lo = span.lo(self.sess()); Some(Span { filename: local_path, - begin: (lo.line, lo.col.to_usize()), - end: (hi.line, hi.col.to_usize()), + begin: (lo.line, lo.col.to_usize() + 1), + end: (hi.line, hi.col.to_usize() + 1), }) } else { None diff --git a/src/rustdoc-json-types/lib.rs b/src/rustdoc-json-types/lib.rs index 7247950545ad5..875857f965110 100644 --- a/src/rustdoc-json-types/lib.rs +++ b/src/rustdoc-json-types/lib.rs @@ -205,9 +205,9 @@ pub struct Item { pub struct Span { /// The path to the source file for this span relative to the path `rustdoc` was invoked with. pub filename: PathBuf, - /// Zero indexed Line and Column of the first character of the `Span` + /// One indexed Line and Column of the first character of the `Span`. pub begin: (usize, usize), - /// Zero indexed Line and Column of the last character of the `Span` + /// One indexed Line and Column of the last character of the `Span`. pub end: (usize, usize), } From ba9a008d90ad7b9c11379a00766f9e4ebbcdc126 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Wed, 16 Apr 2025 15:28:28 +0200 Subject: [PATCH 248/266] Add regression test for span 1-indexed check --- tests/rustdoc-json/impls/auto.rs | 4 ++-- tests/rustdoc-json/span.rs | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 tests/rustdoc-json/span.rs diff --git a/tests/rustdoc-json/impls/auto.rs b/tests/rustdoc-json/impls/auto.rs index f94f7338480bb..ce47d1be690f7 100644 --- a/tests/rustdoc-json/impls/auto.rs +++ b/tests/rustdoc-json/impls/auto.rs @@ -15,8 +15,8 @@ impl Foo { } // Testing spans, so all tests below code -//@ is "$.index[?(@.docs=='has span')].span.begin" "[13, 0]" -//@ is "$.index[?(@.docs=='has span')].span.end" "[15, 1]" +//@ is "$.index[?(@.docs=='has span')].span.begin" "[13, 1]" +//@ is "$.index[?(@.docs=='has span')].span.end" "[15, 2]" // FIXME: this doesn't work due to https://github.com/freestrings/jsonpath/issues/91 // is "$.index[?(@.inner.impl.is_synthetic==true)].span" null pub struct Foo; diff --git a/tests/rustdoc-json/span.rs b/tests/rustdoc-json/span.rs new file mode 100644 index 0000000000000..c96879d0e684a --- /dev/null +++ b/tests/rustdoc-json/span.rs @@ -0,0 +1,4 @@ +pub mod bar {} +// This test ensures that spans are 1-indexed. +//@ is "$.index[?(@.name=='span')].span.begin" "[1, 1]" +//@ is "$.index[?(@.name=='bar')].span.begin" "[1, 1]" From 076016d55afdf760c7e30e23c5df8f0c079cd85b Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 18 Apr 2025 20:34:56 +0200 Subject: [PATCH 249/266] Update rustdoc-json-types `FORMAT_VERSION` to 45 --- src/rustdoc-json-types/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rustdoc-json-types/lib.rs b/src/rustdoc-json-types/lib.rs index 875857f965110..64223b5b75896 100644 --- a/src/rustdoc-json-types/lib.rs +++ b/src/rustdoc-json-types/lib.rs @@ -30,7 +30,7 @@ pub type FxHashMap = HashMap; // re-export for use in src/librustdoc /// This integer is incremented with every breaking change to the API, /// and is returned along with the JSON blob as [`Crate::format_version`]. /// Consuming code should assert that this value matches the format version(s) that it supports. -pub const FORMAT_VERSION: u32 = 44; +pub const FORMAT_VERSION: u32 = 45; /// The root of the emitted JSON blob. /// From c123dc63ea5f765488e4d56aa55bf4467fce7d27 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 18 Apr 2025 21:21:15 +0200 Subject: [PATCH 250/266] Fix `rustc_codegen_gcc/tests/run/return-tuple.rs` test --- compiler/rustc_codegen_gcc/tests/run/return-tuple.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/compiler/rustc_codegen_gcc/tests/run/return-tuple.rs b/compiler/rustc_codegen_gcc/tests/run/return-tuple.rs index c6e1ba7ce3949..c1254c51ce91d 100644 --- a/compiler/rustc_codegen_gcc/tests/run/return-tuple.rs +++ b/compiler/rustc_codegen_gcc/tests/run/return-tuple.rs @@ -6,13 +6,7 @@ // 10 // 42 -<<<<<<< HEAD -#![feature(auto_traits, lang_items, no_core, intrinsics)] -#![allow(internal_features)] - -======= #![feature(no_core)] ->>>>>>> db1a31c243a649e1fe20f5466ba181da5be35c14 #![no_std] #![no_core] #![no_main] From fb3cae08ab3fad5b915e04adc60b164ddd1612c4 Mon Sep 17 00:00:00 2001 From: Patrick Mooney Date: Thu, 17 Apr 2025 20:31:58 -0500 Subject: [PATCH 251/266] std: Use fstatat() on illumos --- library/std/src/sys/fs/unix.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/library/std/src/sys/fs/unix.rs b/library/std/src/sys/fs/unix.rs index 687fc322e598d..bc8817bac7044 100644 --- a/library/std/src/sys/fs/unix.rs +++ b/library/std/src/sys/fs/unix.rs @@ -12,10 +12,11 @@ use libc::c_char; all(target_os = "linux", not(target_env = "musl")), target_os = "android", target_os = "fuchsia", - target_os = "hurd" + target_os = "hurd", + target_os = "illumos", ))] use libc::dirfd; -#[cfg(target_os = "fuchsia")] +#[cfg(any(target_os = "fuchsia", target_os = "illumos"))] use libc::fstatat as fstatat64; #[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "hurd"))] use libc::fstatat64; @@ -892,7 +893,8 @@ impl DirEntry { all(target_os = "linux", not(target_env = "musl")), target_os = "android", target_os = "fuchsia", - target_os = "hurd" + target_os = "hurd", + target_os = "illumos", ), not(miri) // no dirfd on Miri ))] @@ -922,6 +924,7 @@ impl DirEntry { target_os = "android", target_os = "fuchsia", target_os = "hurd", + target_os = "illumos", )), miri ))] From 84f582665ef64467e2ca8f65448f75f14b12edf5 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 18 Apr 2025 22:46:43 +0200 Subject: [PATCH 252/266] Fix compilation error in GCC backend --- compiler/rustc_codegen_gcc/src/int.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_codegen_gcc/src/int.rs b/compiler/rustc_codegen_gcc/src/int.rs index 906d7eaceb6be..9b5b0fde6e2f1 100644 --- a/compiler/rustc_codegen_gcc/src/int.rs +++ b/compiler/rustc_codegen_gcc/src/int.rs @@ -404,7 +404,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let ret_indirect = matches!(fn_abi.ret.mode, PassMode::Indirect { .. }); - let result = if ret_indirect { + let call = if ret_indirect { let res_value = self.current_func().new_local(self.location, res_type, "result_value"); let res_addr = res_value.get_address(self.location); let res_param_type = res_type.make_pointer(); From 41ddf8672231c1f8cfa0fc754c1653f151030b19 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Sat, 29 Mar 2025 17:30:11 +0100 Subject: [PATCH 253/266] Make `#[naked]` an unsafe attribute --- compiler/rustc_builtin_macros/messages.ftl | 4 +- .../example/mini_core_hello_world.rs | 6 +- .../src/error_codes/E0736.md | 2 +- .../src/error_codes/E0787.md | 2 +- compiler/rustc_feature/src/builtin_attrs.rs | 2 +- .../rustc_mir_build/src/check_unsafety.rs | 8 ++- compiler/rustc_parse/src/validate_attr.rs | 6 -- compiler/rustc_passes/messages.ftl | 8 +-- .../src/compiler-flags/sanitizer.md | 37 +++++------ .../aarch64-naked-fn-no-bti-prolog.rs | 4 +- tests/assembly/naked-functions/aix.rs | 4 +- tests/assembly/naked-functions/wasm32.rs | 60 +++++++++--------- .../x86_64-naked-fn-no-cet-prolog.rs | 4 +- tests/codegen/cffi/c-variadic-naked.rs | 6 +- tests/codegen/naked-asan.rs | 4 +- tests/codegen/naked-fn/aligned.rs | 6 +- tests/codegen/naked-fn/generics.rs | 46 +++++++------- tests/codegen/naked-fn/instruction-set.rs | 12 ++-- .../naked-fn/min-function-alignment.rs | 16 ++--- tests/codegen/naked-fn/naked-functions.rs | 16 ++--- .../naked-symbol-visibility/a_rust_dylib.rs | 20 +++--- tests/ui/asm/naked-asm-outside-naked-fn.rs | 16 ++--- .../ui/asm/naked-asm-outside-naked-fn.stderr | 24 +++---- tests/ui/asm/naked-functions-ffi.rs | 6 +- tests/ui/asm/naked-functions-inline.rs | 20 +++--- tests/ui/asm/naked-functions-inline.stderr | 32 +++++----- .../ui/asm/naked-functions-instruction-set.rs | 8 +-- tests/ui/asm/naked-functions-rustic-abi.rs | 12 ++-- .../ui/asm/naked-functions-target-feature.rs | 12 ++-- tests/ui/asm/naked-functions-testattrs.rs | 16 ++--- tests/ui/asm/naked-functions-testattrs.stderr | 24 +++---- tests/ui/asm/naked-functions-unused.rs | 30 +++------ tests/ui/asm/naked-functions.rs | 62 +++++++++---------- tests/ui/asm/naked-functions.stderr | 50 +++++++-------- tests/ui/asm/naked-invalid-attr.rs | 28 ++++----- tests/ui/asm/naked-invalid-attr.stderr | 20 +++--- tests/ui/asm/naked-with-invalid-repr-attr.rs | 20 +++--- .../asm/naked-with-invalid-repr-attr.stderr | 12 ++-- tests/ui/asm/named-asm-labels.rs | 16 ++--- tests/ui/asm/named-asm-labels.stderr | 18 +++--- .../feature-gate-naked_functions.rs | 6 +- .../feature-gate-naked_functions.stderr | 45 ++++++++------ ...feature-gate-naked_functions_rustic_abi.rs | 6 +- ...ure-gate-naked_functions_target_feature.rs | 2 +- .../rfc-2091-track-caller/error-with-naked.rs | 4 +- .../error-with-naked.stderr | 16 ++--- 46 files changed, 375 insertions(+), 403 deletions(-) diff --git a/compiler/rustc_builtin_macros/messages.ftl b/compiler/rustc_builtin_macros/messages.ftl index 5316e90847ac5..73be954cefd76 100644 --- a/compiler/rustc_builtin_macros/messages.ftl +++ b/compiler/rustc_builtin_macros/messages.ftl @@ -247,9 +247,9 @@ builtin_macros_multiple_defaults = multiple declared defaults .suggestion = make `{$ident}` default builtin_macros_naked_functions_testing_attribute = - cannot use `#[naked]` with testing attributes + cannot use `#[unsafe(naked)]` with testing attributes .label = function marked with testing attribute here - .naked_attribute = `#[naked]` is incompatible with testing attributes + .naked_attribute = `#[unsafe(naked)]` is incompatible with testing attributes builtin_macros_no_default_variant = `#[derive(Default)]` on enum with no `#[default]` .label = this enum needs a unit variant marked with `#[default]` diff --git a/compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs b/compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs index 09d5b73fd3d9d..0b3a7281d5a06 100644 --- a/compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs +++ b/compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs @@ -387,11 +387,9 @@ global_asm! { } #[cfg(all(not(jit), target_arch = "x86_64"))] -#[naked] +#[unsafe(naked)] extern "C" fn naked_test() { - unsafe { - naked_asm!("ret"); - } + naked_asm!("ret") } #[repr(C)] diff --git a/compiler/rustc_error_codes/src/error_codes/E0736.md b/compiler/rustc_error_codes/src/error_codes/E0736.md index cb7633b7068a3..66d5fbb80cf29 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0736.md +++ b/compiler/rustc_error_codes/src/error_codes/E0736.md @@ -11,7 +11,7 @@ Erroneous code example: ```compile_fail,E0736 #[inline] -#[naked] +#[unsafe(naked)] fn foo() {} ``` diff --git a/compiler/rustc_error_codes/src/error_codes/E0787.md b/compiler/rustc_error_codes/src/error_codes/E0787.md index f5c5faa066b6b..47b56ac17f4f5 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0787.md +++ b/compiler/rustc_error_codes/src/error_codes/E0787.md @@ -5,7 +5,7 @@ Erroneous code example: ```compile_fail,E0787 #![feature(naked_functions)] -#[naked] +#[unsafe(naked)] pub extern "C" fn f() -> u32 { 42 } diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 3b441729d7552..713e460e507f4 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -517,7 +517,7 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ // Linking: gated!( - naked, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No, + unsafe naked, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No, naked_functions, experimental!(naked) ), diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index b6a856a6eb4d1..adfce99a9b537 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -564,13 +564,17 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { } } ExprKind::InlineAsm(box InlineAsmExpr { - asm_macro: AsmMacro::Asm | AsmMacro::NakedAsm, + asm_macro: asm_macro @ (AsmMacro::Asm | AsmMacro::NakedAsm), ref operands, template: _, options: _, line_spans: _, }) => { - self.requires_unsafe(expr.span, UseOfInlineAssembly); + // The `naked` attribute and the `naked_asm!` block form one atomic unit of + // unsafety, and `naked_asm!` does not itself need to be wrapped in an unsafe block. + if let AsmMacro::Asm = asm_macro { + self.requires_unsafe(expr.span, UseOfInlineAssembly); + } // For inline asm, do not use `walk_expr`, since we want to handle the label block // specially. diff --git a/compiler/rustc_parse/src/validate_attr.rs b/compiler/rustc_parse/src/validate_attr.rs index b518fca7a6583..6a1c2af48ed50 100644 --- a/compiler/rustc_parse/src/validate_attr.rs +++ b/compiler/rustc_parse/src/validate_attr.rs @@ -194,12 +194,6 @@ pub fn check_attribute_safety(psess: &ParseSess, safety: AttributeSafety, attr: } } } else if let Safety::Unsafe(unsafe_span) = attr_item.unsafety { - // Allow (but don't require) `#[unsafe(naked)]` so that compiler-builtins can upgrade to it. - // FIXME(#139797): remove this special case when compiler-builtins has upgraded. - if attr.has_name(sym::naked) { - return; - } - psess.dcx().emit_err(errors::InvalidAttrUnsafe { span: unsafe_span, name: attr_item.path.clone(), diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index 99789b74488c9..413726ddd82d3 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -508,7 +508,7 @@ passes_must_use_no_effect = `#[must_use]` has no effect when applied to {$article} {$target} passes_naked_asm_outside_naked_fn = - the `naked_asm!` macro can only be used in functions marked with `#[naked]` + the `naked_asm!` macro can only be used in functions marked with `#[unsafe(naked)]` passes_naked_functions_asm_block = naked functions must contain a single `naked_asm!` invocation @@ -516,9 +516,9 @@ passes_naked_functions_asm_block = .label_non_asm = not allowed in naked functions passes_naked_functions_incompatible_attribute = - attribute incompatible with `#[naked]` - .label = the `{$attr}` attribute is incompatible with `#[naked]` - .naked_attribute = function marked with `#[naked]` here + attribute incompatible with `#[unsafe(naked)]` + .label = the `{$attr}` attribute is incompatible with `#[unsafe(naked)]` + .naked_attribute = function marked with `#[unsafe(naked)]` here passes_naked_functions_must_naked_asm = the `asm!` macro is not allowed in naked functions diff --git a/src/doc/unstable-book/src/compiler-flags/sanitizer.md b/src/doc/unstable-book/src/compiler-flags/sanitizer.md index 4679acf0a6a15..f2e1bb80cb263 100644 --- a/src/doc/unstable-book/src/compiler-flags/sanitizer.md +++ b/src/doc/unstable-book/src/compiler-flags/sanitizer.md @@ -247,34 +247,31 @@ See the [Clang ControlFlowIntegrity documentation][clang-cfi] for more details. ```rust,ignore (making doc tests pass cross-platform is hard) #![feature(naked_functions)] -use std::arch::asm; +use std::arch::naked_asm; use std::mem; fn add_one(x: i32) -> i32 { x + 1 } -#[naked] +#[unsafe(naked)] pub extern "C" fn add_two(x: i32) { // x + 2 preceded by a landing pad/nop block - unsafe { - asm!( - " - nop - nop - nop - nop - nop - nop - nop - nop - nop - lea eax, [rdi+2] - ret - ", - options(noreturn) - ); - } + naked_asm!( + " + nop + nop + nop + nop + nop + nop + nop + nop + nop + lea eax, [rdi+2] + ret + " + ); } fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { diff --git a/tests/assembly/naked-functions/aarch64-naked-fn-no-bti-prolog.rs b/tests/assembly/naked-functions/aarch64-naked-fn-no-bti-prolog.rs index 46e627eaa00bd..46acf7c6501a9 100644 --- a/tests/assembly/naked-functions/aarch64-naked-fn-no-bti-prolog.rs +++ b/tests/assembly/naked-functions/aarch64-naked-fn-no-bti-prolog.rs @@ -13,8 +13,8 @@ use std::arch::naked_asm; // LLVM implements this via making sure of that, even for functions with the naked attribute. // So, we must emit an appropriate instruction instead! #[no_mangle] -#[naked] -pub unsafe extern "C" fn _hlt() -> ! { +#[unsafe(naked)] +pub extern "C" fn _hlt() -> ! { // CHECK-NOT: hint #34 // CHECK: hlt #0x1 naked_asm!("hlt #1") diff --git a/tests/assembly/naked-functions/aix.rs b/tests/assembly/naked-functions/aix.rs index cc0825b37387c..9aa9edc39e78b 100644 --- a/tests/assembly/naked-functions/aix.rs +++ b/tests/assembly/naked-functions/aix.rs @@ -29,7 +29,7 @@ use minicore::*; // CHECK-LABEL: blr: // CHECK: blr #[no_mangle] -#[naked] -unsafe extern "C" fn blr() { +#[unsafe(naked)] +extern "C" fn blr() { naked_asm!("blr") } diff --git a/tests/assembly/naked-functions/wasm32.rs b/tests/assembly/naked-functions/wasm32.rs index 4911a6bd08f68..c114cb385be17 100644 --- a/tests/assembly/naked-functions/wasm32.rs +++ b/tests/assembly/naked-functions/wasm32.rs @@ -22,8 +22,8 @@ use minicore::*; // CHECK-NOT: .size // CHECK: end_function #[no_mangle] -#[naked] -unsafe extern "C" fn nop() { +#[unsafe(naked)] +extern "C" fn nop() { naked_asm!("nop") } @@ -34,11 +34,11 @@ unsafe extern "C" fn nop() { // CHECK-NOT: .size // CHECK: end_function #[no_mangle] -#[naked] +#[unsafe(naked)] #[linkage = "weak"] // wasm functions cannot be aligned, so this has no effect #[repr(align(32))] -unsafe extern "C" fn weak_aligned_nop() { +extern "C" fn weak_aligned_nop() { naked_asm!("nop") } @@ -51,48 +51,48 @@ unsafe extern "C" fn weak_aligned_nop() { // // CHECK-NEXT: end_function #[no_mangle] -#[naked] -unsafe extern "C" fn fn_i8_i8(num: i8) -> i8 { +#[unsafe(naked)] +extern "C" fn fn_i8_i8(num: i8) -> i8 { naked_asm!("local.get 0", "local.get 0", "i32.mul") } // CHECK-LABEL: fn_i8_i8_i8: // CHECK: .functype fn_i8_i8_i8 (i32, i32) -> (i32) #[no_mangle] -#[naked] -unsafe extern "C" fn fn_i8_i8_i8(a: i8, b: i8) -> i8 { +#[unsafe(naked)] +extern "C" fn fn_i8_i8_i8(a: i8, b: i8) -> i8 { naked_asm!("local.get 1", "local.get 0", "i32.mul") } // CHECK-LABEL: fn_unit_i8: // CHECK: .functype fn_unit_i8 () -> (i32) #[no_mangle] -#[naked] -unsafe extern "C" fn fn_unit_i8() -> i8 { +#[unsafe(naked)] +extern "C" fn fn_unit_i8() -> i8 { naked_asm!("i32.const 42") } // CHECK-LABEL: fn_i8_unit: // CHECK: .functype fn_i8_unit (i32) -> () #[no_mangle] -#[naked] -unsafe extern "C" fn fn_i8_unit(_: i8) { +#[unsafe(naked)] +extern "C" fn fn_i8_unit(_: i8) { naked_asm!("nop") } // CHECK-LABEL: fn_i32_i32: // CHECK: .functype fn_i32_i32 (i32) -> (i32) #[no_mangle] -#[naked] -unsafe extern "C" fn fn_i32_i32(num: i32) -> i32 { +#[unsafe(naked)] +extern "C" fn fn_i32_i32(num: i32) -> i32 { naked_asm!("local.get 0", "local.get 0", "i32.mul") } // CHECK-LABEL: fn_i64_i64: // CHECK: .functype fn_i64_i64 (i64) -> (i64) #[no_mangle] -#[naked] -unsafe extern "C" fn fn_i64_i64(num: i64) -> i64 { +#[unsafe(naked)] +extern "C" fn fn_i64_i64(num: i64) -> i64 { naked_asm!("local.get 0", "local.get 0", "i64.mul") } @@ -101,8 +101,8 @@ unsafe extern "C" fn fn_i64_i64(num: i64) -> i64 { // wasm64-unknown: .functype fn_i128_i128 (i64, i64, i64) -> () #[allow(improper_ctypes_definitions)] #[no_mangle] -#[naked] -unsafe extern "C" fn fn_i128_i128(num: i128) -> i128 { +#[unsafe(naked)] +extern "C" fn fn_i128_i128(num: i128) -> i128 { naked_asm!( "local.get 0", "local.get 2", @@ -117,8 +117,8 @@ unsafe extern "C" fn fn_i128_i128(num: i128) -> i128 { // wasm32-wasip1: .functype fn_f128_f128 (i32, i64, i64) -> () // wasm64-unknown: .functype fn_f128_f128 (i64, i64, i64) -> () #[no_mangle] -#[naked] -unsafe extern "C" fn fn_f128_f128(num: f128) -> f128 { +#[unsafe(naked)] +extern "C" fn fn_f128_f128(num: f128) -> f128 { naked_asm!( "local.get 0", "local.get 2", @@ -139,8 +139,8 @@ struct Compound { // wasm32-wasip1: .functype fn_compound_compound (i32, i32) -> () // wasm64-unknown: .functype fn_compound_compound (i64, i64) -> () #[no_mangle] -#[naked] -unsafe extern "C" fn fn_compound_compound(_: Compound) -> Compound { +#[unsafe(naked)] +extern "C" fn fn_compound_compound(_: Compound) -> Compound { // this is the wasm32-wasip1 assembly naked_asm!( "local.get 0", @@ -160,8 +160,8 @@ struct WrapperI32(i32); // CHECK-LABEL: fn_wrapperi32_wrapperi32: // CHECK: .functype fn_wrapperi32_wrapperi32 (i32) -> (i32) #[no_mangle] -#[naked] -unsafe extern "C" fn fn_wrapperi32_wrapperi32(_: WrapperI32) -> WrapperI32 { +#[unsafe(naked)] +extern "C" fn fn_wrapperi32_wrapperi32(_: WrapperI32) -> WrapperI32 { naked_asm!("local.get 0") } @@ -171,8 +171,8 @@ struct WrapperI64(i64); // CHECK-LABEL: fn_wrapperi64_wrapperi64: // CHECK: .functype fn_wrapperi64_wrapperi64 (i64) -> (i64) #[no_mangle] -#[naked] -unsafe extern "C" fn fn_wrapperi64_wrapperi64(_: WrapperI64) -> WrapperI64 { +#[unsafe(naked)] +extern "C" fn fn_wrapperi64_wrapperi64(_: WrapperI64) -> WrapperI64 { naked_asm!("local.get 0") } @@ -182,8 +182,8 @@ struct WrapperF32(f32); // CHECK-LABEL: fn_wrapperf32_wrapperf32: // CHECK: .functype fn_wrapperf32_wrapperf32 (f32) -> (f32) #[no_mangle] -#[naked] -unsafe extern "C" fn fn_wrapperf32_wrapperf32(_: WrapperF32) -> WrapperF32 { +#[unsafe(naked)] +extern "C" fn fn_wrapperf32_wrapperf32(_: WrapperF32) -> WrapperF32 { naked_asm!("local.get 0") } @@ -193,7 +193,7 @@ struct WrapperF64(f64); // CHECK-LABEL: fn_wrapperf64_wrapperf64: // CHECK: .functype fn_wrapperf64_wrapperf64 (f64) -> (f64) #[no_mangle] -#[naked] -unsafe extern "C" fn fn_wrapperf64_wrapperf64(_: WrapperF64) -> WrapperF64 { +#[unsafe(naked)] +extern "C" fn fn_wrapperf64_wrapperf64(_: WrapperF64) -> WrapperF64 { naked_asm!("local.get 0") } diff --git a/tests/assembly/naked-functions/x86_64-naked-fn-no-cet-prolog.rs b/tests/assembly/naked-functions/x86_64-naked-fn-no-cet-prolog.rs index 54e1d93c68bd6..df6a2e91c51ea 100644 --- a/tests/assembly/naked-functions/x86_64-naked-fn-no-cet-prolog.rs +++ b/tests/assembly/naked-functions/x86_64-naked-fn-no-cet-prolog.rs @@ -13,8 +13,8 @@ use std::arch::naked_asm; // works by using an instruction for each possible landing site, // and LLVM implements this via making sure of that. #[no_mangle] -#[naked] -pub unsafe extern "sysv64" fn will_halt() -> ! { +#[unsafe(naked)] +pub extern "sysv64" fn will_halt() -> ! { // CHECK-NOT: endbr{{32|64}} // CHECK: hlt naked_asm!("hlt") diff --git a/tests/codegen/cffi/c-variadic-naked.rs b/tests/codegen/cffi/c-variadic-naked.rs index 24b69c5f59e21..05d48e52dc006 100644 --- a/tests/codegen/cffi/c-variadic-naked.rs +++ b/tests/codegen/cffi/c-variadic-naked.rs @@ -8,11 +8,9 @@ #![feature(naked_functions)] #![no_std] -#[naked] +#[unsafe(naked)] pub unsafe extern "C" fn c_variadic(_: usize, _: ...) { // CHECK-NOT: va_start // CHECK-NOT: alloca - core::arch::naked_asm! { - "ret", - } + core::arch::naked_asm!("ret") } diff --git a/tests/codegen/naked-asan.rs b/tests/codegen/naked-asan.rs index 8efedab6ea55d..52b3e709cd35c 100644 --- a/tests/codegen/naked-asan.rs +++ b/tests/codegen/naked-asan.rs @@ -13,10 +13,10 @@ pub fn caller() { } // CHECK: declare x86_intrcc void @page_fault_handler(ptr {{.*}}, i64{{.*}}){{.*}}#[[ATTRS:[0-9]+]] -#[naked] +#[unsafe(naked)] #[no_mangle] pub extern "x86-interrupt" fn page_fault_handler(_: u64, _: u64) { - unsafe { core::arch::naked_asm!("ud2") }; + core::arch::naked_asm!("ud2") } // CHECK: #[[ATTRS]] = diff --git a/tests/codegen/naked-fn/aligned.rs b/tests/codegen/naked-fn/aligned.rs index d9dcd7f6c3ef7..6183461fedaec 100644 --- a/tests/codegen/naked-fn/aligned.rs +++ b/tests/codegen/naked-fn/aligned.rs @@ -10,8 +10,8 @@ use std::arch::naked_asm; // CHECK-LABEL: naked_empty: #[repr(align(16))] #[no_mangle] -#[naked] -pub unsafe extern "C" fn naked_empty() { +#[unsafe(naked)] +pub extern "C" fn naked_empty() { // CHECK: ret - naked_asm!("ret"); + naked_asm!("ret") } diff --git a/tests/codegen/naked-fn/generics.rs b/tests/codegen/naked-fn/generics.rs index 64998df64ddb6..4427586777168 100644 --- a/tests/codegen/naked-fn/generics.rs +++ b/tests/codegen/naked-fn/generics.rs @@ -28,21 +28,19 @@ fn test(x: u64) { // CHECK: add rax, 1 // CHECK: add rax, 42 -#[naked] +#[unsafe(naked)] pub extern "C" fn using_const_generics(x: u64) -> u64 { const M: u64 = 42; - unsafe { - naked_asm!( - "xor rax, rax", - "add rax, rdi", - "add rax, {}", - "add rax, {}", - "ret", - const N, - const M, - ) - } + naked_asm!( + "xor rax, rax", + "add rax, rdi", + "add rax, {}", + "add rax, {}", + "ret", + const N, + const M, + ) } trait Invert { @@ -60,16 +58,14 @@ impl Invert for i64 { // CHECK: call // CHECK: ret -#[naked] +#[unsafe(naked)] #[no_mangle] pub extern "C" fn generic_function(x: i64) -> i64 { - unsafe { - naked_asm!( - "call {}", - "ret", - sym ::invert, - ) - } + naked_asm!( + "call {}", + "ret", + sym ::invert, + ) } #[derive(Copy, Clone)] @@ -81,10 +77,10 @@ struct Foo(u64); // CHECK: mov rax, rdi impl Foo { - #[naked] + #[unsafe(naked)] #[no_mangle] extern "C" fn method(self) -> u64 { - unsafe { naked_asm!("mov rax, rdi", "ret") } + naked_asm!("mov rax, rdi", "ret") } } @@ -97,10 +93,10 @@ trait Bar { } impl Bar for Foo { - #[naked] + #[unsafe(naked)] #[no_mangle] extern "C" fn trait_method(self) -> u64 { - unsafe { naked_asm!("mov rax, rdi", "ret") } + naked_asm!("mov rax, rdi", "ret") } } @@ -109,7 +105,7 @@ impl Bar for Foo { // CHECK: lea rax, [rdi + rsi] // this previously ICE'd, see https://github.com/rust-lang/rust/issues/124375 -#[naked] +#[unsafe(naked)] #[no_mangle] pub unsafe extern "C" fn naked_with_args_and_return(a: isize, b: isize) -> isize { naked_asm!("lea rax, [rdi + rsi]", "ret"); diff --git a/tests/codegen/naked-fn/instruction-set.rs b/tests/codegen/naked-fn/instruction-set.rs index a7b4c22a59bfd..2ccd47d645858 100644 --- a/tests/codegen/naked-fn/instruction-set.rs +++ b/tests/codegen/naked-fn/instruction-set.rs @@ -20,8 +20,8 @@ use minicore::*; // arm-mode: .arm // thumb-mode: .thumb #[no_mangle] -#[naked] -unsafe extern "C" fn test_unspecified() { +#[unsafe(naked)] +extern "C" fn test_unspecified() { naked_asm!("bx lr"); } @@ -33,9 +33,9 @@ unsafe extern "C" fn test_unspecified() { // arm-mode: .arm // thumb-mode: .thumb #[no_mangle] -#[naked] +#[unsafe(naked)] #[instruction_set(arm::t32)] -unsafe extern "C" fn test_thumb() { +extern "C" fn test_thumb() { naked_asm!("bx lr"); } @@ -46,8 +46,8 @@ unsafe extern "C" fn test_thumb() { // arm-mode: .arm // thumb-mode: .thumb #[no_mangle] -#[naked] +#[unsafe(naked)] #[instruction_set(arm::a32)] -unsafe extern "C" fn test_arm() { +extern "C" fn test_arm() { naked_asm!("bx lr"); } diff --git a/tests/codegen/naked-fn/min-function-alignment.rs b/tests/codegen/naked-fn/min-function-alignment.rs index 1330d796d397f..4a9142288248b 100644 --- a/tests/codegen/naked-fn/min-function-alignment.rs +++ b/tests/codegen/naked-fn/min-function-alignment.rs @@ -9,24 +9,24 @@ // // CHECK: .balign 16 #[no_mangle] -#[naked] -pub unsafe extern "C" fn naked_no_explicit_align() { +#[unsafe(naked)] +pub extern "C" fn naked_no_explicit_align() { core::arch::naked_asm!("ret") } // CHECK: .balign 16 #[no_mangle] #[repr(align(8))] -#[naked] -pub unsafe extern "C" fn naked_lower_align() { +#[unsafe(naked)] +pub extern "C" fn naked_lower_align() { core::arch::naked_asm!("ret") } // CHECK: .balign 32 #[no_mangle] #[repr(align(32))] -#[naked] -pub unsafe extern "C" fn naked_higher_align() { +#[unsafe(naked)] +pub extern "C" fn naked_higher_align() { core::arch::naked_asm!("ret") } @@ -38,7 +38,7 @@ pub unsafe extern "C" fn naked_higher_align() { // CHECK: .balign 16 #[no_mangle] #[cold] -#[naked] -pub unsafe extern "C" fn no_explicit_align_cold() { +#[unsafe(naked)] +pub extern "C" fn no_explicit_align_cold() { core::arch::naked_asm!("ret") } diff --git a/tests/codegen/naked-fn/naked-functions.rs b/tests/codegen/naked-fn/naked-functions.rs index 3fe795178b702..1bcdd6de373e5 100644 --- a/tests/codegen/naked-fn/naked-functions.rs +++ b/tests/codegen/naked-fn/naked-functions.rs @@ -60,8 +60,8 @@ use minicore::*; // linux,win: .att_syntax #[no_mangle] -#[naked] -pub unsafe extern "C" fn naked_empty() { +#[unsafe(naked)] +pub extern "C" fn naked_empty() { #[cfg(not(all(target_arch = "arm", target_feature = "thumb-mode")))] naked_asm!("ret"); @@ -114,8 +114,8 @@ pub unsafe extern "C" fn naked_empty() { // linux,win: .att_syntax #[no_mangle] -#[naked] -pub unsafe extern "C" fn naked_with_args_and_return(a: isize, b: isize) -> isize { +#[unsafe(naked)] +pub extern "C" fn naked_with_args_and_return(a: isize, b: isize) -> isize { #[cfg(any(target_os = "windows", target_os = "linux"))] { naked_asm!("lea rax, [rdi + rsi]", "ret") @@ -138,9 +138,9 @@ pub unsafe extern "C" fn naked_with_args_and_return(a: isize, b: isize) -> isize // thumb: .pushsection .text.some_different_name,\22ax\22, %progbits // CHECK-LABEL: test_link_section: #[no_mangle] -#[naked] +#[unsafe(naked)] #[link_section = ".text.some_different_name"] -pub unsafe extern "C" fn test_link_section() { +pub extern "C" fn test_link_section() { #[cfg(not(all(target_arch = "arm", target_feature = "thumb-mode")))] naked_asm!("ret"); @@ -159,7 +159,7 @@ pub unsafe extern "C" fn test_link_section() { // win_i686-LABEL: @fastcall_cc@4: #[cfg(target_os = "windows")] #[no_mangle] -#[naked] -pub unsafe extern "fastcall" fn fastcall_cc(x: i32) -> i32 { +#[unsafe(naked)] +pub extern "fastcall" fn fastcall_cc(x: i32) -> i32 { naked_asm!("ret"); } diff --git a/tests/run-make/naked-symbol-visibility/a_rust_dylib.rs b/tests/run-make/naked-symbol-visibility/a_rust_dylib.rs index f98a2036544c3..ae75519525363 100644 --- a/tests/run-make/naked-symbol-visibility/a_rust_dylib.rs +++ b/tests/run-make/naked-symbol-visibility/a_rust_dylib.rs @@ -26,9 +26,9 @@ extern "C" fn private_vanilla() -> u32 { 42 } -#[naked] +#[unsafe(naked)] extern "C" fn private_naked() -> u32 { - unsafe { naked_asm!("mov rax, 42", "ret") } + naked_asm!("mov rax, 42", "ret") } #[no_mangle] @@ -36,19 +36,19 @@ pub extern "C" fn public_vanilla() -> u32 { 42 } -#[naked] +#[unsafe(naked)] #[no_mangle] pub extern "C" fn public_naked_nongeneric() -> u32 { - unsafe { naked_asm!("mov rax, 42", "ret") } + naked_asm!("mov rax, 42", "ret") } pub extern "C" fn public_vanilla_generic() -> u32 { T::COUNT } -#[naked] +#[unsafe(naked)] pub extern "C" fn public_naked_generic() -> u32 { - unsafe { naked_asm!("mov rax, {}", "ret", const T::COUNT) } + naked_asm!("mov rax, {}", "ret", const T::COUNT) } #[linkage = "external"] @@ -56,10 +56,10 @@ extern "C" fn vanilla_external_linkage() -> u32 { 42 } -#[naked] +#[unsafe(naked)] #[linkage = "external"] extern "C" fn naked_external_linkage() -> u32 { - unsafe { naked_asm!("mov rax, 42", "ret") } + naked_asm!("mov rax, 42", "ret") } #[cfg(not(windows))] @@ -68,11 +68,11 @@ extern "C" fn vanilla_weak_linkage() -> u32 { 42 } -#[naked] +#[unsafe(naked)] #[cfg(not(windows))] #[linkage = "weak"] extern "C" fn naked_weak_linkage() -> u32 { - unsafe { naked_asm!("mov rax, 42", "ret") } + naked_asm!("mov rax, 42", "ret") } // functions that are declared in an `extern "C"` block are currently not exported diff --git a/tests/ui/asm/naked-asm-outside-naked-fn.rs b/tests/ui/asm/naked-asm-outside-naked-fn.rs index 1696008f3397d..a7680cc63ae03 100644 --- a/tests/ui/asm/naked-asm-outside-naked-fn.rs +++ b/tests/ui/asm/naked-asm-outside-naked-fn.rs @@ -12,24 +12,24 @@ fn main() { test1(); } -#[naked] +#[unsafe(naked)] extern "C" fn test1() { - unsafe { naked_asm!("") } + naked_asm!("") } extern "C" fn test2() { - unsafe { naked_asm!("") } - //~^ ERROR the `naked_asm!` macro can only be used in functions marked with `#[naked]` + naked_asm!("") + //~^ ERROR the `naked_asm!` macro can only be used in functions marked with `#[unsafe(naked)]` } extern "C" fn test3() { - unsafe { (|| naked_asm!(""))() } - //~^ ERROR the `naked_asm!` macro can only be used in functions marked with `#[naked]` + (|| naked_asm!(""))() + //~^ ERROR the `naked_asm!` macro can only be used in functions marked with `#[unsafe(naked)]` } fn test4() { async move { - unsafe { naked_asm!("") } ; - //~^ ERROR the `naked_asm!` macro can only be used in functions marked with `#[naked]` + naked_asm!(""); + //~^ ERROR the `naked_asm!` macro can only be used in functions marked with `#[unsafe(naked)]` }; } diff --git a/tests/ui/asm/naked-asm-outside-naked-fn.stderr b/tests/ui/asm/naked-asm-outside-naked-fn.stderr index 6e91359669ca2..85a50a49fecfc 100644 --- a/tests/ui/asm/naked-asm-outside-naked-fn.stderr +++ b/tests/ui/asm/naked-asm-outside-naked-fn.stderr @@ -1,20 +1,20 @@ -error: the `naked_asm!` macro can only be used in functions marked with `#[naked]` - --> $DIR/naked-asm-outside-naked-fn.rs:21:14 +error: the `naked_asm!` macro can only be used in functions marked with `#[unsafe(naked)]` + --> $DIR/naked-asm-outside-naked-fn.rs:21:5 | -LL | unsafe { naked_asm!("") } - | ^^^^^^^^^^^^^^ +LL | naked_asm!("") + | ^^^^^^^^^^^^^^ -error: the `naked_asm!` macro can only be used in functions marked with `#[naked]` - --> $DIR/naked-asm-outside-naked-fn.rs:26:18 +error: the `naked_asm!` macro can only be used in functions marked with `#[unsafe(naked)]` + --> $DIR/naked-asm-outside-naked-fn.rs:26:9 | -LL | unsafe { (|| naked_asm!(""))() } - | ^^^^^^^^^^^^^^ +LL | (|| naked_asm!(""))() + | ^^^^^^^^^^^^^^ -error: the `naked_asm!` macro can only be used in functions marked with `#[naked]` - --> $DIR/naked-asm-outside-naked-fn.rs:32:19 +error: the `naked_asm!` macro can only be used in functions marked with `#[unsafe(naked)]` + --> $DIR/naked-asm-outside-naked-fn.rs:32:9 | -LL | unsafe { naked_asm!("") } ; - | ^^^^^^^^^^^^^^ +LL | naked_asm!(""); + | ^^^^^^^^^^^^^^ error: aborting due to 3 previous errors diff --git a/tests/ui/asm/naked-functions-ffi.rs b/tests/ui/asm/naked-functions-ffi.rs index b78d1e6a0d1c6..8fd0da01d72a7 100644 --- a/tests/ui/asm/naked-functions-ffi.rs +++ b/tests/ui/asm/naked-functions-ffi.rs @@ -5,11 +5,9 @@ use std::arch::naked_asm; -#[naked] +#[unsafe(naked)] pub extern "C" fn naked(p: char) -> u128 { //~^ WARN uses type `char` //~| WARN uses type `u128` - unsafe { - naked_asm!(""); - } + naked_asm!("") } diff --git a/tests/ui/asm/naked-functions-inline.rs b/tests/ui/asm/naked-functions-inline.rs index 74049e8ecbc7c..261401be64517 100644 --- a/tests/ui/asm/naked-functions-inline.rs +++ b/tests/ui/asm/naked-functions-inline.rs @@ -4,35 +4,35 @@ use std::arch::naked_asm; -#[naked] -pub unsafe extern "C" fn inline_none() { +#[unsafe(naked)] +pub extern "C" fn inline_none() { naked_asm!(""); } -#[naked] +#[unsafe(naked)] #[inline] //~^ ERROR [E0736] -pub unsafe extern "C" fn inline_hint() { +pub extern "C" fn inline_hint() { naked_asm!(""); } -#[naked] +#[unsafe(naked)] #[inline(always)] //~^ ERROR [E0736] -pub unsafe extern "C" fn inline_always() { +pub extern "C" fn inline_always() { naked_asm!(""); } -#[naked] +#[unsafe(naked)] #[inline(never)] //~^ ERROR [E0736] -pub unsafe extern "C" fn inline_never() { +pub extern "C" fn inline_never() { naked_asm!(""); } -#[naked] +#[unsafe(naked)] #[cfg_attr(all(), inline(never))] //~^ ERROR [E0736] -pub unsafe extern "C" fn conditional_inline_never() { +pub extern "C" fn conditional_inline_never() { naked_asm!(""); } diff --git a/tests/ui/asm/naked-functions-inline.stderr b/tests/ui/asm/naked-functions-inline.stderr index 84a688f6f5382..6df5b08ae8534 100644 --- a/tests/ui/asm/naked-functions-inline.stderr +++ b/tests/ui/asm/naked-functions-inline.stderr @@ -1,34 +1,34 @@ -error[E0736]: attribute incompatible with `#[naked]` +error[E0736]: attribute incompatible with `#[unsafe(naked)]` --> $DIR/naked-functions-inline.rs:13:1 | -LL | #[naked] - | -------- function marked with `#[naked]` here +LL | #[unsafe(naked)] + | ---------------- function marked with `#[unsafe(naked)]` here LL | #[inline] - | ^^^^^^^^^ the `inline` attribute is incompatible with `#[naked]` + | ^^^^^^^^^ the `inline` attribute is incompatible with `#[unsafe(naked)]` -error[E0736]: attribute incompatible with `#[naked]` +error[E0736]: attribute incompatible with `#[unsafe(naked)]` --> $DIR/naked-functions-inline.rs:20:1 | -LL | #[naked] - | -------- function marked with `#[naked]` here +LL | #[unsafe(naked)] + | ---------------- function marked with `#[unsafe(naked)]` here LL | #[inline(always)] - | ^^^^^^^^^^^^^^^^^ the `inline` attribute is incompatible with `#[naked]` + | ^^^^^^^^^^^^^^^^^ the `inline` attribute is incompatible with `#[unsafe(naked)]` -error[E0736]: attribute incompatible with `#[naked]` +error[E0736]: attribute incompatible with `#[unsafe(naked)]` --> $DIR/naked-functions-inline.rs:27:1 | -LL | #[naked] - | -------- function marked with `#[naked]` here +LL | #[unsafe(naked)] + | ---------------- function marked with `#[unsafe(naked)]` here LL | #[inline(never)] - | ^^^^^^^^^^^^^^^^ the `inline` attribute is incompatible with `#[naked]` + | ^^^^^^^^^^^^^^^^ the `inline` attribute is incompatible with `#[unsafe(naked)]` -error[E0736]: attribute incompatible with `#[naked]` +error[E0736]: attribute incompatible with `#[unsafe(naked)]` --> $DIR/naked-functions-inline.rs:34:19 | -LL | #[naked] - | -------- function marked with `#[naked]` here +LL | #[unsafe(naked)] + | ---------------- function marked with `#[unsafe(naked)]` here LL | #[cfg_attr(all(), inline(never))] - | ^^^^^^^^^^^^^ the `inline` attribute is incompatible with `#[naked]` + | ^^^^^^^^^^^^^ the `inline` attribute is incompatible with `#[unsafe(naked)]` error: aborting due to 4 previous errors diff --git a/tests/ui/asm/naked-functions-instruction-set.rs b/tests/ui/asm/naked-functions-instruction-set.rs index 28241badf5f87..6fd34b035edd0 100644 --- a/tests/ui/asm/naked-functions-instruction-set.rs +++ b/tests/ui/asm/naked-functions-instruction-set.rs @@ -12,15 +12,15 @@ extern crate minicore; use minicore::*; #[no_mangle] -#[naked] +#[unsafe(naked)] #[instruction_set(arm::t32)] -unsafe extern "C" fn test_thumb() { +extern "C" fn test_thumb() { naked_asm!("bx lr"); } #[no_mangle] -#[naked] +#[unsafe(naked)] #[instruction_set(arm::a32)] -unsafe extern "C" fn test_arm() { +extern "C" fn test_arm() { naked_asm!("bx lr"); } diff --git a/tests/ui/asm/naked-functions-rustic-abi.rs b/tests/ui/asm/naked-functions-rustic-abi.rs index b654d38ccc1a6..99b8d2e19fe40 100644 --- a/tests/ui/asm/naked-functions-rustic-abi.rs +++ b/tests/ui/asm/naked-functions-rustic-abi.rs @@ -11,17 +11,17 @@ use std::arch::{asm, naked_asm}; -#[naked] -pub unsafe fn rust_implicit() { +#[unsafe(naked)] +pub fn rust_implicit() { naked_asm!("ret"); } -#[naked] -pub unsafe extern "Rust" fn rust_explicit() { +#[unsafe(naked)] +pub extern "Rust" fn rust_explicit() { naked_asm!("ret"); } -#[naked] -pub unsafe extern "rust-cold" fn rust_cold() { +#[unsafe(naked)] +pub extern "rust-cold" fn rust_cold() { naked_asm!("ret"); } diff --git a/tests/ui/asm/naked-functions-target-feature.rs b/tests/ui/asm/naked-functions-target-feature.rs index afe1a38914720..d8dc2104c76e1 100644 --- a/tests/ui/asm/naked-functions-target-feature.rs +++ b/tests/ui/asm/naked-functions-target-feature.rs @@ -8,14 +8,14 @@ use std::arch::{asm, naked_asm}; #[cfg(target_arch = "x86_64")] #[target_feature(enable = "sse2")] -#[naked] -pub unsafe extern "C" fn compatible_target_feature() { - naked_asm!(""); +#[unsafe(naked)] +pub extern "C" fn compatible_target_feature() { + naked_asm!("ret"); } #[cfg(target_arch = "aarch64")] #[target_feature(enable = "neon")] -#[naked] -pub unsafe extern "C" fn compatible_target_feature() { - naked_asm!(""); +#[unsafe(naked)] +pub extern "C" fn compatible_target_feature() { + naked_asm!("ret"); } diff --git a/tests/ui/asm/naked-functions-testattrs.rs b/tests/ui/asm/naked-functions-testattrs.rs index ad31876a77a59..c8539e8064088 100644 --- a/tests/ui/asm/naked-functions-testattrs.rs +++ b/tests/ui/asm/naked-functions-testattrs.rs @@ -8,31 +8,31 @@ use std::arch::naked_asm; #[test] -#[naked] +#[unsafe(naked)] //~^ ERROR [E0736] extern "C" fn test_naked() { - unsafe { naked_asm!("") }; + naked_asm!("") } #[should_panic] #[test] -#[naked] +#[unsafe(naked)] //~^ ERROR [E0736] extern "C" fn test_naked_should_panic() { - unsafe { naked_asm!("") }; + naked_asm!("") } #[ignore] #[test] -#[naked] +#[unsafe(naked)] //~^ ERROR [E0736] extern "C" fn test_naked_ignore() { - unsafe { naked_asm!("") }; + naked_asm!("") } #[bench] -#[naked] +#[unsafe(naked)] //~^ ERROR [E0736] extern "C" fn bench_naked() { - unsafe { naked_asm!("") }; + naked_asm!("") } diff --git a/tests/ui/asm/naked-functions-testattrs.stderr b/tests/ui/asm/naked-functions-testattrs.stderr index 0f0bb91b95413..ad2041ec118b9 100644 --- a/tests/ui/asm/naked-functions-testattrs.stderr +++ b/tests/ui/asm/naked-functions-testattrs.stderr @@ -1,34 +1,34 @@ -error[E0736]: cannot use `#[naked]` with testing attributes +error[E0736]: cannot use `#[unsafe(naked)]` with testing attributes --> $DIR/naked-functions-testattrs.rs:11:1 | LL | #[test] | ------- function marked with testing attribute here -LL | #[naked] - | ^^^^^^^^ `#[naked]` is incompatible with testing attributes +LL | #[unsafe(naked)] + | ^^^^^^^^^^^^^^^^ `#[unsafe(naked)]` is incompatible with testing attributes -error[E0736]: cannot use `#[naked]` with testing attributes +error[E0736]: cannot use `#[unsafe(naked)]` with testing attributes --> $DIR/naked-functions-testattrs.rs:19:1 | LL | #[test] | ------- function marked with testing attribute here -LL | #[naked] - | ^^^^^^^^ `#[naked]` is incompatible with testing attributes +LL | #[unsafe(naked)] + | ^^^^^^^^^^^^^^^^ `#[unsafe(naked)]` is incompatible with testing attributes -error[E0736]: cannot use `#[naked]` with testing attributes +error[E0736]: cannot use `#[unsafe(naked)]` with testing attributes --> $DIR/naked-functions-testattrs.rs:27:1 | LL | #[test] | ------- function marked with testing attribute here -LL | #[naked] - | ^^^^^^^^ `#[naked]` is incompatible with testing attributes +LL | #[unsafe(naked)] + | ^^^^^^^^^^^^^^^^ `#[unsafe(naked)]` is incompatible with testing attributes -error[E0736]: cannot use `#[naked]` with testing attributes +error[E0736]: cannot use `#[unsafe(naked)]` with testing attributes --> $DIR/naked-functions-testattrs.rs:34:1 | LL | #[bench] | -------- function marked with testing attribute here -LL | #[naked] - | ^^^^^^^^ `#[naked]` is incompatible with testing attributes +LL | #[unsafe(naked)] + | ^^^^^^^^^^^^^^^^ `#[unsafe(naked)]` is incompatible with testing attributes error: aborting due to 4 previous errors diff --git a/tests/ui/asm/naked-functions-unused.rs b/tests/ui/asm/naked-functions-unused.rs index c27037819a44f..67c05984be71c 100644 --- a/tests/ui/asm/naked-functions-unused.rs +++ b/tests/ui/asm/naked-functions-unused.rs @@ -64,44 +64,34 @@ pub mod normal { pub mod naked { use std::arch::naked_asm; - #[naked] + #[unsafe(naked)] pub extern "C" fn function(a: usize, b: usize) -> usize { - unsafe { - naked_asm!(""); - } + naked_asm!("") } pub struct Naked; impl Naked { - #[naked] + #[unsafe(naked)] pub extern "C" fn associated(a: usize, b: usize) -> usize { - unsafe { - naked_asm!(""); - } + naked_asm!("") } - #[naked] + #[unsafe(naked)] pub extern "C" fn method(&self, a: usize, b: usize) -> usize { - unsafe { - naked_asm!(""); - } + naked_asm!("") } } impl super::Trait for Naked { - #[naked] + #[unsafe(naked)] extern "C" fn trait_associated(a: usize, b: usize) -> usize { - unsafe { - naked_asm!(""); - } + naked_asm!("") } - #[naked] + #[unsafe(naked)] extern "C" fn trait_method(&self, a: usize, b: usize) -> usize { - unsafe { - naked_asm!(""); - } + naked_asm!("") } } } diff --git a/tests/ui/asm/naked-functions.rs b/tests/ui/asm/naked-functions.rs index 8ba0eecb7b5c7..b433c1b5389c4 100644 --- a/tests/ui/asm/naked-functions.rs +++ b/tests/ui/asm/naked-functions.rs @@ -9,8 +9,8 @@ use std::arch::{asm, naked_asm}; #[unsafe(naked)] -pub unsafe extern "C" fn inline_asm_macro() { - asm!("", options(raw)); +pub extern "C" fn inline_asm_macro() { + unsafe { asm!("", options(raw)) }; //~^ERROR the `asm!` macro is not allowed in naked functions } @@ -21,7 +21,7 @@ pub struct P { } #[unsafe(naked)] -pub unsafe extern "C" fn patterns( +pub extern "C" fn patterns( mut a: u32, //~^ ERROR patterns not allowed in naked function parameters &b: &i32, @@ -35,7 +35,7 @@ pub unsafe extern "C" fn patterns( } #[unsafe(naked)] -pub unsafe extern "C" fn inc(a: u32) -> u32 { +pub extern "C" fn inc(a: u32) -> u32 { //~^ ERROR naked functions must contain a single `naked_asm!` invocation a + 1 //~^ ERROR referencing function parameters is not allowed in naked functions @@ -43,19 +43,19 @@ pub unsafe extern "C" fn inc(a: u32) -> u32 { #[unsafe(naked)] #[allow(asm_sub_register)] -pub unsafe extern "C" fn inc_asm(a: u32) -> u32 { +pub extern "C" fn inc_asm(a: u32) -> u32 { naked_asm!("/* {0} */", in(reg) a) //~^ ERROR the `in` operand cannot be used with `naked_asm!` } #[unsafe(naked)] -pub unsafe extern "C" fn inc_closure(a: u32) -> u32 { +pub extern "C" fn inc_closure(a: u32) -> u32 { //~^ ERROR naked functions must contain a single `naked_asm!` invocation (|| a + 1)() } #[unsafe(naked)] -pub unsafe extern "C" fn unsupported_operands() { +pub extern "C" fn unsupported_operands() { //~^ ERROR naked functions must contain a single `naked_asm!` invocation let mut a = 0usize; let mut b = 0usize; @@ -84,11 +84,10 @@ pub extern "C" fn missing_assembly() { #[unsafe(naked)] pub extern "C" fn too_many_asm_blocks() { //~^ ERROR naked functions must contain a single `naked_asm!` invocation - unsafe { - naked_asm!("", options(noreturn)); - //~^ ERROR the `noreturn` option cannot be used with `naked_asm!` - naked_asm!(""); - } + + naked_asm!("", options(noreturn)); + //~^ ERROR the `noreturn` option cannot be used with `naked_asm!` + naked_asm!(""); } pub fn outer(x: u32) -> extern "C" fn(usize) -> usize { @@ -124,49 +123,44 @@ unsafe extern "C" fn invalid_may_unwind() { #[unsafe(naked)] pub extern "C" fn valid_a() -> T { - unsafe { - naked_asm!(""); - } + naked_asm!(""); } #[unsafe(naked)] pub extern "C" fn valid_b() { - unsafe { + { { - { - naked_asm!(""); - }; + naked_asm!(""); }; - } + }; } #[unsafe(naked)] -pub unsafe extern "C" fn valid_c() { +pub extern "C" fn valid_c() { naked_asm!(""); } #[cfg(target_arch = "x86_64")] #[unsafe(naked)] -pub unsafe extern "C" fn valid_att_syntax() { +pub extern "C" fn valid_att_syntax() { naked_asm!("", options(att_syntax)); } #[unsafe(naked)] -#[unsafe(naked)] -pub unsafe extern "C" fn allow_compile_error(a: u32) -> u32 { +pub extern "C" fn allow_compile_error(a: u32) -> u32 { compile_error!("this is a user specified error") //~^ ERROR this is a user specified error } #[unsafe(naked)] -pub unsafe extern "C" fn allow_compile_error_and_asm(a: u32) -> u32 { +pub extern "C" fn allow_compile_error_and_asm(a: u32) -> u32 { compile_error!("this is a user specified error"); //~^ ERROR this is a user specified error naked_asm!("") } #[unsafe(naked)] -pub unsafe extern "C" fn invalid_asm_syntax(a: u32) -> u32 { +pub extern "C" fn invalid_asm_syntax(a: u32) -> u32 { naked_asm!(invalid_syntax) //~^ ERROR asm template must be a string literal } @@ -174,7 +168,7 @@ pub unsafe extern "C" fn invalid_asm_syntax(a: u32) -> u32 { #[cfg(target_arch = "x86_64")] #[cfg_attr(target_pointer_width = "64", no_mangle)] #[unsafe(naked)] -pub unsafe extern "C" fn compatible_cfg_attributes() { +pub extern "C" fn compatible_cfg_attributes() { naked_asm!("", options(att_syntax)); } @@ -183,20 +177,20 @@ pub unsafe extern "C" fn compatible_cfg_attributes() { #[deny(dead_code)] #[forbid(dead_code)] #[unsafe(naked)] -pub unsafe extern "C" fn compatible_diagnostic_attributes() { +pub extern "C" fn compatible_diagnostic_attributes() { naked_asm!("", options(raw)); } #[deprecated = "test"] #[unsafe(naked)] -pub unsafe extern "C" fn compatible_deprecated_attributes() { +pub extern "C" fn compatible_deprecated_attributes() { naked_asm!("", options(raw)); } #[cfg(target_arch = "x86_64")] #[must_use] #[unsafe(naked)] -pub unsafe extern "C" fn compatible_must_use_attributes() -> u64 { +pub extern "C" fn compatible_must_use_attributes() -> u64 { naked_asm!( " mov rax, 42 @@ -208,13 +202,13 @@ pub unsafe extern "C" fn compatible_must_use_attributes() -> u64 { #[export_name = "exported_function_name"] #[link_section = ".custom_section"] #[unsafe(naked)] -pub unsafe extern "C" fn compatible_ffi_attributes_1() { +pub extern "C" fn compatible_ffi_attributes_1() { naked_asm!("", options(raw)); } #[cold] #[unsafe(naked)] -pub unsafe extern "C" fn compatible_codegen_attributes() { +pub extern "C" fn compatible_codegen_attributes() { naked_asm!("", options(raw)); } @@ -223,12 +217,12 @@ pub unsafe extern "C" fn compatible_codegen_attributes() { // a normal comment #[doc(alias = "ADocAlias")] #[unsafe(naked)] -pub unsafe extern "C" fn compatible_doc_attributes() { +pub extern "C" fn compatible_doc_attributes() { naked_asm!("", options(raw)); } #[linkage = "external"] #[unsafe(naked)] -pub unsafe extern "C" fn compatible_linkage() { +pub extern "C" fn compatible_linkage() { naked_asm!("", options(raw)); } diff --git a/tests/ui/asm/naked-functions.stderr b/tests/ui/asm/naked-functions.stderr index 0a55bb9cd8370..2b67c3aecd73c 100644 --- a/tests/ui/asm/naked-functions.stderr +++ b/tests/ui/asm/naked-functions.stderr @@ -11,70 +11,70 @@ LL | in(reg) a, | ^^ the `in` operand is not meaningful for global-scoped inline assembly, remove it error: the `noreturn` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:88:32 + --> $DIR/naked-functions.rs:88:28 | -LL | naked_asm!("", options(noreturn)); - | ^^^^^^^^ the `noreturn` option is not meaningful for global-scoped inline assembly +LL | naked_asm!("", options(noreturn)); + | ^^^^^^^^ the `noreturn` option is not meaningful for global-scoped inline assembly error: the `nomem` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:106:28 + --> $DIR/naked-functions.rs:105:28 | LL | naked_asm!("", options(nomem, preserves_flags)); | ^^^^^ the `nomem` option is not meaningful for global-scoped inline assembly error: the `preserves_flags` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:106:35 + --> $DIR/naked-functions.rs:105:35 | LL | naked_asm!("", options(nomem, preserves_flags)); | ^^^^^^^^^^^^^^^ the `preserves_flags` option is not meaningful for global-scoped inline assembly error: the `readonly` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:113:28 + --> $DIR/naked-functions.rs:112:28 | LL | naked_asm!("", options(readonly, nostack), options(pure)); | ^^^^^^^^ the `readonly` option is not meaningful for global-scoped inline assembly error: the `nostack` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:113:38 + --> $DIR/naked-functions.rs:112:38 | LL | naked_asm!("", options(readonly, nostack), options(pure)); | ^^^^^^^ the `nostack` option is not meaningful for global-scoped inline assembly error: the `pure` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:113:56 + --> $DIR/naked-functions.rs:112:56 | LL | naked_asm!("", options(readonly, nostack), options(pure)); | ^^^^ the `pure` option is not meaningful for global-scoped inline assembly error: the `may_unwind` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:121:28 + --> $DIR/naked-functions.rs:120:28 | LL | naked_asm!("", options(may_unwind)); | ^^^^^^^^^^ the `may_unwind` option is not meaningful for global-scoped inline assembly error: this is a user specified error - --> $DIR/naked-functions.rs:157:5 + --> $DIR/naked-functions.rs:151:5 | LL | compile_error!("this is a user specified error") | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: this is a user specified error - --> $DIR/naked-functions.rs:163:5 + --> $DIR/naked-functions.rs:157:5 | LL | compile_error!("this is a user specified error"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: asm template must be a string literal - --> $DIR/naked-functions.rs:170:16 + --> $DIR/naked-functions.rs:164:16 | LL | naked_asm!(invalid_syntax) | ^^^^^^^^^^^^^^ error[E0787]: the `asm!` macro is not allowed in naked functions - --> $DIR/naked-functions.rs:13:5 + --> $DIR/naked-functions.rs:13:14 | -LL | asm!("", options(raw)); - | ^^^^^^^^^^^^^^^^^^^^^^ consider using the `naked_asm!` macro instead +LL | unsafe { asm!("", options(raw)) }; + | ^^^^^^^^^^^^^^^^^^^^^^ consider using the `naked_asm!` macro instead error: patterns not allowed in naked function parameters --> $DIR/naked-functions.rs:25:5 @@ -111,8 +111,8 @@ LL | a + 1 error[E0787]: naked functions must contain a single `naked_asm!` invocation --> $DIR/naked-functions.rs:38:1 | -LL | pub unsafe extern "C" fn inc(a: u32) -> u32 { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | pub extern "C" fn inc(a: u32) -> u32 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | LL | a + 1 | ----- not allowed in naked functions @@ -120,8 +120,8 @@ LL | a + 1 error[E0787]: naked functions must contain a single `naked_asm!` invocation --> $DIR/naked-functions.rs:52:1 | -LL | pub unsafe extern "C" fn inc_closure(a: u32) -> u32 { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | pub extern "C" fn inc_closure(a: u32) -> u32 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | LL | (|| a + 1)() | ------------ not allowed in naked functions @@ -129,8 +129,8 @@ LL | (|| a + 1)() error[E0787]: naked functions must contain a single `naked_asm!` invocation --> $DIR/naked-functions.rs:58:1 | -LL | pub unsafe extern "C" fn unsupported_operands() { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | pub extern "C" fn unsupported_operands() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | LL | let mut a = 0usize; | ------------------- not allowed in naked functions @@ -155,11 +155,11 @@ error[E0787]: naked functions must contain a single `naked_asm!` invocation LL | pub extern "C" fn too_many_asm_blocks() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ... -LL | naked_asm!(""); - | -------------- multiple `naked_asm!` invocations are not allowed in naked functions +LL | naked_asm!(""); + | -------------- multiple `naked_asm!` invocations are not allowed in naked functions error: referencing function parameters is not allowed in naked functions - --> $DIR/naked-functions.rs:98:11 + --> $DIR/naked-functions.rs:97:11 | LL | *&y | ^ @@ -167,7 +167,7 @@ LL | *&y = help: follow the calling convention in asm block to use parameters error[E0787]: naked functions must contain a single `naked_asm!` invocation - --> $DIR/naked-functions.rs:96:5 + --> $DIR/naked-functions.rs:95:5 | LL | pub extern "C" fn inner(y: usize) -> usize { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/asm/naked-invalid-attr.rs b/tests/ui/asm/naked-invalid-attr.rs index 4053c58fb5136..6c5fdbe74d82a 100644 --- a/tests/ui/asm/naked-invalid-attr.rs +++ b/tests/ui/asm/naked-invalid-attr.rs @@ -1,17 +1,17 @@ -// Checks that #[naked] attribute can be placed on function definitions only. +// Checks that #[unsafe(naked)] attribute can be placed on function definitions only. // //@ needs-asm-support #![feature(naked_functions)] -#![naked] //~ ERROR should be applied to a function definition +#![unsafe(naked)] //~ ERROR should be applied to a function definition use std::arch::naked_asm; extern "C" { - #[naked] //~ ERROR should be applied to a function definition + #[unsafe(naked)] //~ ERROR should be applied to a function definition fn f(); } -#[naked] //~ ERROR should be applied to a function definition +#[unsafe(naked)] //~ ERROR should be applied to a function definition #[repr(C)] struct S { a: u32, @@ -19,35 +19,35 @@ struct S { } trait Invoke { - #[naked] //~ ERROR should be applied to a function definition + #[unsafe(naked)] //~ ERROR should be applied to a function definition extern "C" fn invoke(&self); } impl Invoke for S { - #[naked] + #[unsafe(naked)] extern "C" fn invoke(&self) { - unsafe { naked_asm!("") } + naked_asm!("") } } -#[naked] +#[unsafe(naked)] extern "C" fn ok() { - unsafe { naked_asm!("") } + naked_asm!("") } impl S { - #[naked] + #[unsafe(naked)] extern "C" fn g() { - unsafe { naked_asm!("") } + naked_asm!("") } - #[naked] + #[unsafe(naked)] extern "C" fn h(&self) { - unsafe { naked_asm!("") } + naked_asm!("") } } fn main() { - #[naked] //~ ERROR should be applied to a function definition + #[unsafe(naked)] //~ ERROR should be applied to a function definition || {}; } diff --git a/tests/ui/asm/naked-invalid-attr.stderr b/tests/ui/asm/naked-invalid-attr.stderr index 640f9d9510d15..6e2746b568437 100644 --- a/tests/ui/asm/naked-invalid-attr.stderr +++ b/tests/ui/asm/naked-invalid-attr.stderr @@ -1,8 +1,8 @@ error: attribute should be applied to a function definition --> $DIR/naked-invalid-attr.rs:14:1 | -LL | #[naked] - | ^^^^^^^^ +LL | #[unsafe(naked)] + | ^^^^^^^^^^^^^^^^ LL | #[repr(C)] LL | / struct S { LL | | a: u32, @@ -13,32 +13,32 @@ LL | | } error: attribute should be applied to a function definition --> $DIR/naked-invalid-attr.rs:51:5 | -LL | #[naked] - | ^^^^^^^^ +LL | #[unsafe(naked)] + | ^^^^^^^^^^^^^^^^ LL | || {}; | ----- not a function definition error: attribute should be applied to a function definition --> $DIR/naked-invalid-attr.rs:22:5 | -LL | #[naked] - | ^^^^^^^^ +LL | #[unsafe(naked)] + | ^^^^^^^^^^^^^^^^ LL | extern "C" fn invoke(&self); | ---------------------------- not a function definition error: attribute should be applied to a function definition --> $DIR/naked-invalid-attr.rs:10:5 | -LL | #[naked] - | ^^^^^^^^ +LL | #[unsafe(naked)] + | ^^^^^^^^^^^^^^^^ LL | fn f(); | ------- not a function definition error: attribute should be applied to a function definition --> $DIR/naked-invalid-attr.rs:5:1 | -LL | #![naked] - | ^^^^^^^^^ cannot be applied to crates +LL | #![unsafe(naked)] + | ^^^^^^^^^^^^^^^^^ cannot be applied to crates error: aborting due to 5 previous errors diff --git a/tests/ui/asm/naked-with-invalid-repr-attr.rs b/tests/ui/asm/naked-with-invalid-repr-attr.rs index 18b9c1014c3fa..c9f335ea9506a 100644 --- a/tests/ui/asm/naked-with-invalid-repr-attr.rs +++ b/tests/ui/asm/naked-with-invalid-repr-attr.rs @@ -6,43 +6,43 @@ use std::arch::naked_asm; #[repr(C)] //~^ ERROR attribute should be applied to a struct, enum, or union [E0517] -#[naked] +#[unsafe(naked)] extern "C" fn example1() { //~^ NOTE not a struct, enum, or union - unsafe { naked_asm!("") } + naked_asm!("") } #[repr(transparent)] //~^ ERROR attribute should be applied to a struct, enum, or union [E0517] -#[naked] +#[unsafe(naked)] extern "C" fn example2() { //~^ NOTE not a struct, enum, or union - unsafe { naked_asm!("") } + naked_asm!("") } #[repr(align(16), C)] //~^ ERROR attribute should be applied to a struct, enum, or union [E0517] -#[naked] +#[unsafe(naked)] extern "C" fn example3() { //~^ NOTE not a struct, enum, or union - unsafe { naked_asm!("") } + naked_asm!("") } // note: two errors because of packed and C #[repr(C, packed)] //~^ ERROR attribute should be applied to a struct or union [E0517] //~| ERROR attribute should be applied to a struct, enum, or union [E0517] -#[naked] +#[unsafe(naked)] extern "C" fn example4() { //~^ NOTE not a struct, enum, or union //~| NOTE not a struct or union - unsafe { naked_asm!("") } + naked_asm!("") } #[repr(u8)] //~^ ERROR attribute should be applied to an enum [E0517] -#[naked] +#[unsafe(naked)] extern "C" fn example5() { //~^ NOTE not an enum - unsafe { naked_asm!("") } + naked_asm!("") } diff --git a/tests/ui/asm/naked-with-invalid-repr-attr.stderr b/tests/ui/asm/naked-with-invalid-repr-attr.stderr index 8248a8c165791..219e32473beaa 100644 --- a/tests/ui/asm/naked-with-invalid-repr-attr.stderr +++ b/tests/ui/asm/naked-with-invalid-repr-attr.stderr @@ -6,7 +6,7 @@ LL | #[repr(C)] ... LL | / extern "C" fn example1() { LL | | -LL | | unsafe { naked_asm!("") } +LL | | naked_asm!("") LL | | } | |_- not a struct, enum, or union @@ -18,7 +18,7 @@ LL | #[repr(transparent)] ... LL | / extern "C" fn example2() { LL | | -LL | | unsafe { naked_asm!("") } +LL | | naked_asm!("") LL | | } | |_- not a struct, enum, or union @@ -30,7 +30,7 @@ LL | #[repr(align(16), C)] ... LL | / extern "C" fn example3() { LL | | -LL | | unsafe { naked_asm!("") } +LL | | naked_asm!("") LL | | } | |_- not a struct, enum, or union @@ -43,7 +43,7 @@ LL | #[repr(C, packed)] LL | / extern "C" fn example4() { LL | | LL | | -LL | | unsafe { naked_asm!("") } +LL | | naked_asm!("") LL | | } | |_- not a struct, enum, or union @@ -56,7 +56,7 @@ LL | #[repr(C, packed)] LL | / extern "C" fn example4() { LL | | LL | | -LL | | unsafe { naked_asm!("") } +LL | | naked_asm!("") LL | | } | |_- not a struct or union @@ -68,7 +68,7 @@ LL | #[repr(u8)] ... LL | / extern "C" fn example5() { LL | | -LL | | unsafe { naked_asm!("") } +LL | | naked_asm!("") LL | | } | |_- not an enum diff --git a/tests/ui/asm/named-asm-labels.rs b/tests/ui/asm/named-asm-labels.rs index 77831e679ed42..d5c194452d75b 100644 --- a/tests/ui/asm/named-asm-labels.rs +++ b/tests/ui/asm/named-asm-labels.rs @@ -175,9 +175,9 @@ fn main() { // Trigger on naked fns too, even though they can't be inlined, reusing a // label or LTO can cause labels to break -#[naked] +#[unsafe(naked)] pub extern "C" fn foo() -> i32 { - unsafe { naked_asm!(".Lfoo: mov rax, {}; ret;", "nop", const 1) } + naked_asm!(".Lfoo: mov rax, {}; ret;", "nop", const 1) //~^ ERROR avoid using named labels } @@ -188,21 +188,21 @@ pub extern "C" fn bar() { //~^ ERROR avoid using named labels } -#[naked] +#[unsafe(naked)] pub extern "C" fn aaa() { fn _local() {} - unsafe { naked_asm!(".Laaa: nop; ret;") } //~ ERROR avoid using named labels + naked_asm!(".Laaa: nop; ret;") //~ ERROR avoid using named labels } pub fn normal() { fn _local1() {} - #[naked] + #[unsafe(naked)] pub extern "C" fn bbb() { fn _very_local() {} - unsafe { naked_asm!(".Lbbb: nop; ret;") } //~ ERROR avoid using named labels + naked_asm!(".Lbbb: nop; ret;") //~ ERROR avoid using named labels } fn _local2() {} @@ -219,8 +219,8 @@ fn closures() { }; || { - #[naked] - unsafe extern "C" fn _nested() { + #[unsafe(naked)] + extern "C" fn _nested() { naked_asm!("ret;"); } diff --git a/tests/ui/asm/named-asm-labels.stderr b/tests/ui/asm/named-asm-labels.stderr index 44ce358c62bdb..0120d4948d51c 100644 --- a/tests/ui/asm/named-asm-labels.stderr +++ b/tests/ui/asm/named-asm-labels.stderr @@ -475,10 +475,10 @@ LL | #[warn(named_asm_labels)] | ^^^^^^^^^^^^^^^^ error: avoid using named labels in inline assembly - --> $DIR/named-asm-labels.rs:180:26 + --> $DIR/named-asm-labels.rs:180:17 | -LL | unsafe { naked_asm!(".Lfoo: mov rax, {}; ret;", "nop", const 1) } - | ^^^^^ +LL | naked_asm!(".Lfoo: mov rax, {}; ret;", "nop", const 1) + | ^^^^^ | = help: only local labels of the form `:` should be used in inline asm = note: see the asm section of Rust By Example for more information @@ -493,19 +493,19 @@ LL | unsafe { asm!(".Lbar: mov rax, {}; ret;", "nop", const 1, options(noret = note: see the asm section of Rust By Example for more information error: avoid using named labels in inline assembly - --> $DIR/named-asm-labels.rs:195:26 + --> $DIR/named-asm-labels.rs:195:17 | -LL | unsafe { naked_asm!(".Laaa: nop; ret;") } - | ^^^^^ +LL | naked_asm!(".Laaa: nop; ret;") + | ^^^^^ | = help: only local labels of the form `:` should be used in inline asm = note: see the asm section of Rust By Example for more information error: avoid using named labels in inline assembly - --> $DIR/named-asm-labels.rs:205:30 + --> $DIR/named-asm-labels.rs:205:21 | -LL | unsafe { naked_asm!(".Lbbb: nop; ret;") } - | ^^^^^ +LL | naked_asm!(".Lbbb: nop; ret;") + | ^^^^^ | = help: only local labels of the form `:` should be used in inline asm = note: see the asm section of Rust By Example for more information diff --git a/tests/ui/feature-gates/feature-gate-naked_functions.rs b/tests/ui/feature-gates/feature-gate-naked_functions.rs index 77a67e0696eb2..d940decd561e9 100644 --- a/tests/ui/feature-gates/feature-gate-naked_functions.rs +++ b/tests/ui/feature-gates/feature-gate-naked_functions.rs @@ -3,20 +3,18 @@ use std::arch::naked_asm; //~^ ERROR use of unstable library feature `naked_functions` -#[naked] +#[naked] //~ ERROR unsafe attribute used without unsafe //~^ ERROR the `#[naked]` attribute is an experimental feature extern "C" fn naked() { naked_asm!("") //~^ ERROR use of unstable library feature `naked_functions` - //~| ERROR: requires unsafe } -#[naked] +#[naked] //~ ERROR unsafe attribute used without unsafe //~^ ERROR the `#[naked]` attribute is an experimental feature extern "C" fn naked_2() -> isize { naked_asm!("") //~^ ERROR use of unstable library feature `naked_functions` - //~| ERROR: requires unsafe } fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-naked_functions.stderr b/tests/ui/feature-gates/feature-gate-naked_functions.stderr index 9bfb9275bb201..ea765db7d946e 100644 --- a/tests/ui/feature-gates/feature-gate-naked_functions.stderr +++ b/tests/ui/feature-gates/feature-gate-naked_functions.stderr @@ -9,7 +9,7 @@ LL | naked_asm!("") = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0658]: use of unstable library feature `naked_functions` - --> $DIR/feature-gate-naked_functions.rs:17:5 + --> $DIR/feature-gate-naked_functions.rs:16:5 | LL | naked_asm!("") | ^^^^^^^^^ @@ -18,6 +18,28 @@ LL | naked_asm!("") = help: add `#![feature(naked_functions)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date +error: unsafe attribute used without unsafe + --> $DIR/feature-gate-naked_functions.rs:6:3 + | +LL | #[naked] + | ^^^^^ usage of unsafe attribute + | +help: wrap the attribute in `unsafe(...)` + | +LL | #[unsafe(naked)] + | +++++++ + + +error: unsafe attribute used without unsafe + --> $DIR/feature-gate-naked_functions.rs:13:3 + | +LL | #[naked] + | ^^^^^ usage of unsafe attribute + | +help: wrap the attribute in `unsafe(...)` + | +LL | #[unsafe(naked)] + | +++++++ + + error[E0658]: the `#[naked]` attribute is an experimental feature --> $DIR/feature-gate-naked_functions.rs:6:1 | @@ -29,7 +51,7 @@ LL | #[naked] = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0658]: the `#[naked]` attribute is an experimental feature - --> $DIR/feature-gate-naked_functions.rs:14:1 + --> $DIR/feature-gate-naked_functions.rs:13:1 | LL | #[naked] | ^^^^^^^^ @@ -48,23 +70,6 @@ LL | use std::arch::naked_asm; = help: add `#![feature(naked_functions)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0133]: use of inline assembly is unsafe and requires unsafe function or block - --> $DIR/feature-gate-naked_functions.rs:9:5 - | -LL | naked_asm!("") - | ^^^^^^^^^^^^^^ use of inline assembly - | - = note: inline assembly is entirely unchecked and can cause undefined behavior - -error[E0133]: use of inline assembly is unsafe and requires unsafe function or block - --> $DIR/feature-gate-naked_functions.rs:17:5 - | -LL | naked_asm!("") - | ^^^^^^^^^^^^^^ use of inline assembly - | - = note: inline assembly is entirely unchecked and can cause undefined behavior - error: aborting due to 7 previous errors -Some errors have detailed explanations: E0133, E0658. -For more information about an error, try `rustc --explain E0133`. +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/feature-gates/feature-gate-naked_functions_rustic_abi.rs b/tests/ui/feature-gates/feature-gate-naked_functions_rustic_abi.rs index c91d833994414..cc5b4f0e88b42 100644 --- a/tests/ui/feature-gates/feature-gate-naked_functions_rustic_abi.rs +++ b/tests/ui/feature-gates/feature-gate-naked_functions_rustic_abi.rs @@ -5,19 +5,19 @@ use std::arch::naked_asm; -#[naked] +#[unsafe(naked)] pub unsafe fn rust_implicit() { //~^ ERROR `#[naked]` is currently unstable on `extern "Rust"` functions naked_asm!("ret"); } -#[naked] +#[unsafe(naked)] pub unsafe extern "Rust" fn rust_explicit() { //~^ ERROR `#[naked]` is currently unstable on `extern "Rust"` functions naked_asm!("ret"); } -#[naked] +#[unsafe(naked)] pub unsafe extern "rust-cold" fn rust_cold() { //~^ ERROR `#[naked]` is currently unstable on `extern "rust-cold"` functions naked_asm!("ret"); diff --git a/tests/ui/feature-gates/feature-gate-naked_functions_target_feature.rs b/tests/ui/feature-gates/feature-gate-naked_functions_target_feature.rs index 0d3af4c5fe0a4..b2e102f1db4b6 100644 --- a/tests/ui/feature-gates/feature-gate-naked_functions_target_feature.rs +++ b/tests/ui/feature-gates/feature-gate-naked_functions_target_feature.rs @@ -5,7 +5,7 @@ use std::arch::naked_asm; -#[naked] +#[unsafe(naked)] #[target_feature(enable = "avx2")] //~^ ERROR: `#[target_feature(/* ... */)]` is currently unstable on `#[naked]` functions extern "C" fn naked() { diff --git a/tests/ui/rfcs/rfc-2091-track-caller/error-with-naked.rs b/tests/ui/rfcs/rfc-2091-track-caller/error-with-naked.rs index 0e85515fd104a..ce6d10bf33cbd 100644 --- a/tests/ui/rfcs/rfc-2091-track-caller/error-with-naked.rs +++ b/tests/ui/rfcs/rfc-2091-track-caller/error-with-naked.rs @@ -5,7 +5,7 @@ use std::arch::naked_asm; #[track_caller] //~ ERROR [E0736] //~^ ERROR `#[track_caller]` requires Rust ABI -#[naked] +#[unsafe(naked)] extern "C" fn f() { unsafe { naked_asm!(""); @@ -17,7 +17,7 @@ struct S; impl S { #[track_caller] //~ ERROR [E0736] //~^ ERROR `#[track_caller]` requires Rust ABI - #[naked] + #[unsafe(naked)] extern "C" fn g() { unsafe { naked_asm!(""); diff --git a/tests/ui/rfcs/rfc-2091-track-caller/error-with-naked.stderr b/tests/ui/rfcs/rfc-2091-track-caller/error-with-naked.stderr index 0625ed1183ba5..f89d94b67d806 100644 --- a/tests/ui/rfcs/rfc-2091-track-caller/error-with-naked.stderr +++ b/tests/ui/rfcs/rfc-2091-track-caller/error-with-naked.stderr @@ -1,20 +1,20 @@ -error[E0736]: attribute incompatible with `#[naked]` +error[E0736]: attribute incompatible with `#[unsafe(naked)]` --> $DIR/error-with-naked.rs:6:1 | LL | #[track_caller] - | ^^^^^^^^^^^^^^^ the `track_caller` attribute is incompatible with `#[naked]` + | ^^^^^^^^^^^^^^^ the `track_caller` attribute is incompatible with `#[unsafe(naked)]` LL | -LL | #[naked] - | -------- function marked with `#[naked]` here +LL | #[unsafe(naked)] + | ---------------- function marked with `#[unsafe(naked)]` here -error[E0736]: attribute incompatible with `#[naked]` +error[E0736]: attribute incompatible with `#[unsafe(naked)]` --> $DIR/error-with-naked.rs:18:5 | LL | #[track_caller] - | ^^^^^^^^^^^^^^^ the `track_caller` attribute is incompatible with `#[naked]` + | ^^^^^^^^^^^^^^^ the `track_caller` attribute is incompatible with `#[unsafe(naked)]` LL | -LL | #[naked] - | -------- function marked with `#[naked]` here +LL | #[unsafe(naked)] + | ---------------- function marked with `#[unsafe(naked)]` here error[E0737]: `#[track_caller]` requires Rust ABI --> $DIR/error-with-naked.rs:6:1 From cc359b8bb6c693086f69adf013430163992b1807 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 18 Apr 2025 23:02:07 +0200 Subject: [PATCH 254/266] Fix import --- compiler/rustc_codegen_gcc/src/abi.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_codegen_gcc/src/abi.rs b/compiler/rustc_codegen_gcc/src/abi.rs index 890a25e6a7ca0..a96b18e01c087 100644 --- a/compiler/rustc_codegen_gcc/src/abi.rs +++ b/compiler/rustc_codegen_gcc/src/abi.rs @@ -10,7 +10,8 @@ use rustc_middle::ty::layout::LayoutOf; #[cfg(feature = "master")] use rustc_session::config; #[cfg(feature = "master")] -use rustc_target::callconv::{ArgAttributes, CastTarget, Conv, FnAbi, PassMode}; +use rustc_target::callconv::Conv; +use rustc_target::callconv::{ArgAttributes, CastTarget, FnAbi, PassMode}; use crate::builder::Builder; use crate::context::CodegenCx; From bd5c43835ab77b30086b818e17c3a566849c2af3 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 18 Apr 2025 23:34:37 +0000 Subject: [PATCH 255/266] Remove early exits from JumpThreading. --- .../rustc_mir_transform/src/jump_threading.rs | 135 +++++++++--------- 1 file changed, 64 insertions(+), 71 deletions(-) diff --git a/compiler/rustc_mir_transform/src/jump_threading.rs b/compiler/rustc_mir_transform/src/jump_threading.rs index 8b4b214a3d450..9732225e48ddd 100644 --- a/compiler/rustc_mir_transform/src/jump_threading.rs +++ b/compiler/rustc_mir_transform/src/jump_threading.rs @@ -90,11 +90,7 @@ impl<'tcx> crate::MirPass<'tcx> for JumpThreading { }; for bb in body.basic_blocks.indices() { - let old_len = finder.opportunities.len(); - // If we have any const-eval errors discard any opportunities found - if finder.start_from_switch(bb).is_none() { - finder.opportunities.truncate(old_len); - } + finder.start_from_switch(bb); } let opportunities = finder.opportunities; @@ -201,28 +197,26 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { /// Recursion entry point to find threading opportunities. #[instrument(level = "trace", skip(self))] - fn start_from_switch(&mut self, bb: BasicBlock) -> Option<()> { + fn start_from_switch(&mut self, bb: BasicBlock) { let bbdata = &self.body[bb]; if bbdata.is_cleanup || self.loop_headers.contains(bb) { - return Some(()); + return; } - let Some((discr, targets)) = bbdata.terminator().kind.as_switch() else { return Some(()) }; - let Some(discr) = discr.place() else { return Some(()) }; + let Some((discr, targets)) = bbdata.terminator().kind.as_switch() else { return }; + let Some(discr) = discr.place() else { return }; debug!(?discr, ?bb); let discr_ty = discr.ty(self.body, self.tcx).ty; - let Ok(discr_layout) = self.ecx.layout_of(discr_ty) else { - return Some(()); - }; + let Ok(discr_layout) = self.ecx.layout_of(discr_ty) else { return }; - let Some(discr) = self.map.find(discr.as_ref()) else { return Some(()) }; + let Some(discr) = self.map.find(discr.as_ref()) else { return }; debug!(?discr); let cost = CostChecker::new(self.tcx, self.typing_env, None, self.body); let mut state = State::new_reachable(); let conds = if let Some((value, then, else_)) = targets.as_static_if() { - let value = ScalarInt::try_from_uint(value, discr_layout.size)?; + let Some(value) = ScalarInt::try_from_uint(value, discr_layout.size) else { return }; self.arena.alloc_from_iter([ Condition { value, polarity: Polarity::Eq, target: then }, Condition { value, polarity: Polarity::Ne, target: else_ }, @@ -248,10 +242,10 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { mut state: State>, mut cost: CostChecker<'_, 'tcx>, depth: usize, - ) -> Option<()> { + ) { // Do not thread through loop headers. if self.loop_headers.contains(bb) { - return Some(()); + return; } debug!(cost = ?cost.cost()); @@ -259,16 +253,16 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { self.body.basic_blocks[bb].statements.iter().enumerate().rev() { if self.is_empty(&state) { - return Some(()); + return; } cost.visit_statement(stmt, Location { block: bb, statement_index }); if cost.cost() > MAX_COST { - return Some(()); + return; } // Attempt to turn the `current_condition` on `lhs` into a condition on another place. - self.process_statement(bb, stmt, &mut state)?; + self.process_statement(bb, stmt, &mut state); // When a statement mutates a place, assignments to that place that happen // above the mutation cannot fulfill a condition. @@ -280,7 +274,7 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { } if self.is_empty(&state) || depth >= MAX_BACKTRACK { - return Some(()); + return; } let last_non_rec = self.opportunities.len(); @@ -293,9 +287,9 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { match term.kind { TerminatorKind::SwitchInt { ref discr, ref targets } => { self.process_switch_int(discr, targets, bb, &mut state); - self.find_opportunity(pred, state, cost, depth + 1)?; + self.find_opportunity(pred, state, cost, depth + 1); } - _ => self.recurse_through_terminator(pred, || state, &cost, depth)?, + _ => self.recurse_through_terminator(pred, || state, &cost, depth), } } else if let &[ref predecessors @ .., last_pred] = &predecessors[..] { for &pred in predecessors { @@ -320,13 +314,12 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { let first = &mut new_tos[0]; *first = ThreadingOpportunity { chain: vec![bb], target: first.target }; self.opportunities.truncate(last_non_rec + 1); - return Some(()); + return; } for op in self.opportunities[last_non_rec..].iter_mut() { op.chain.push(bb); } - Some(()) } /// Extract the mutated place from a statement. @@ -440,23 +433,23 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { lhs: PlaceIndex, rhs: &Operand<'tcx>, state: &mut State>, - ) -> Option<()> { + ) { match rhs { // If we expect `lhs ?= A`, we have an opportunity if we assume `constant == A`. Operand::Constant(constant) => { - let constant = self - .ecx - .eval_mir_constant(&constant.const_, constant.span, None) - .discard_err()?; + let Some(constant) = + self.ecx.eval_mir_constant(&constant.const_, constant.span, None).discard_err() + else { + return; + }; self.process_constant(bb, lhs, constant, state); } // Transfer the conditions on the copied rhs. Operand::Move(rhs) | Operand::Copy(rhs) => { - let Some(rhs) = self.map.find(rhs.as_ref()) else { return Some(()) }; + let Some(rhs) = self.map.find(rhs.as_ref()) else { return }; state.insert_place_idx(rhs, lhs, &self.map); } } - Some(()) } #[instrument(level = "trace", skip(self))] @@ -466,18 +459,14 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { lhs_place: &Place<'tcx>, rhs: &Rvalue<'tcx>, state: &mut State>, - ) -> Option<()> { - let Some(lhs) = self.map.find(lhs_place.as_ref()) else { - return Some(()); - }; + ) { + let Some(lhs) = self.map.find(lhs_place.as_ref()) else { return }; match rhs { - Rvalue::Use(operand) => self.process_operand(bb, lhs, operand, state)?, + Rvalue::Use(operand) => self.process_operand(bb, lhs, operand, state), // Transfer the conditions on the copy rhs. - Rvalue::CopyForDeref(rhs) => { - self.process_operand(bb, lhs, &Operand::Copy(*rhs), state)? - } + Rvalue::CopyForDeref(rhs) => self.process_operand(bb, lhs, &Operand::Copy(*rhs), state), Rvalue::Discriminant(rhs) => { - let Some(rhs) = self.map.find_discr(rhs.as_ref()) else { return Some(()) }; + let Some(rhs) = self.map.find_discr(rhs.as_ref()) else { return }; state.insert_place_idx(rhs, lhs, &self.map); } // If we expect `lhs ?= A`, we have an opportunity if we assume `constant == A`. @@ -485,7 +474,7 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { let agg_ty = lhs_place.ty(self.body, self.tcx).ty; let lhs = match kind { // Do not support unions. - AggregateKind::Adt(.., Some(_)) => return Some(()), + AggregateKind::Adt(.., Some(_)) => return, AggregateKind::Adt(_, variant_index, ..) if agg_ty.is_enum() => { if let Some(discr_target) = self.map.apply(lhs, TrackElem::Discriminant) && let Some(discr_value) = self @@ -498,23 +487,23 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { if let Some(idx) = self.map.apply(lhs, TrackElem::Variant(*variant_index)) { idx } else { - return Some(()); + return; } } _ => lhs, }; for (field_index, operand) in operands.iter_enumerated() { if let Some(field) = self.map.apply(lhs, TrackElem::Field(field_index)) { - self.process_operand(bb, field, operand, state)?; + self.process_operand(bb, field, operand, state); } } } // Transfer the conditions on the copy rhs, after inverting the value of the condition. Rvalue::UnaryOp(UnOp::Not, Operand::Move(place) | Operand::Copy(place)) => { let layout = self.ecx.layout_of(place.ty(self.body, self.tcx).ty).unwrap(); - let Some(conditions) = state.try_get_idx(lhs, &self.map) else { return Some(()) }; - let Some(place) = self.map.find(place.as_ref()) else { return Some(()) }; - let conds = conditions.map(self.arena, |mut cond| { + let Some(conditions) = state.try_get_idx(lhs, &self.map) else { return }; + let Some(place) = self.map.find(place.as_ref()) else { return }; + let Some(conds) = conditions.map(self.arena, |mut cond| { cond.value = self .ecx .unary_op(UnOp::Not, &ImmTy::from_scalar_int(cond.value, layout)) @@ -522,7 +511,9 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { .to_scalar_int() .discard_err()?; Some(cond) - })?; + }) else { + return; + }; state.insert_value_idx(place, conds, &self.map); } // We expect `lhs ?= A`. We found `lhs = Eq(rhs, B)`. @@ -532,34 +523,38 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { box (Operand::Move(place) | Operand::Copy(place), Operand::Constant(value)) | box (Operand::Constant(value), Operand::Move(place) | Operand::Copy(place)), ) => { - let Some(conditions) = state.try_get_idx(lhs, &self.map) else { return Some(()) }; - let Some(place) = self.map.find(place.as_ref()) else { return Some(()) }; + let Some(conditions) = state.try_get_idx(lhs, &self.map) else { return }; + let Some(place) = self.map.find(place.as_ref()) else { return }; let equals = match op { BinOp::Eq => ScalarInt::TRUE, BinOp::Ne => ScalarInt::FALSE, - _ => return Some(()), + _ => return, }; if value.const_.ty().is_floating_point() { // Floating point equality does not follow bit-patterns. // -0.0 and NaN both have special rules for equality, // and therefore we cannot use integer comparisons for them. // Avoid handling them, though this could be extended in the future. - return Some(()); + return; } - let value = value.const_.try_eval_scalar_int(self.tcx, self.typing_env)?; - let conds = conditions.map(self.arena, |c| { + let Some(value) = value.const_.try_eval_scalar_int(self.tcx, self.typing_env) + else { + return; + }; + let Some(conds) = conditions.map(self.arena, |c| { Some(Condition { value, polarity: if c.matches(equals) { Polarity::Eq } else { Polarity::Ne }, ..c }) - })?; + }) else { + return; + }; state.insert_value_idx(place, conds, &self.map); } _ => {} } - Some(()) } #[instrument(level = "trace", skip(self))] @@ -568,7 +563,7 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { bb: BasicBlock, stmt: &Statement<'tcx>, state: &mut State>, - ) -> Option<()> { + ) { let register_opportunity = |c: Condition| { debug!(?bb, ?c.target, "register"); self.opportunities.push(ThreadingOpportunity { chain: vec![bb], target: c.target }) @@ -581,32 +576,30 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { // If we expect `discriminant(place) ?= A`, // we have an opportunity if `variant_index ?= A`. StatementKind::SetDiscriminant { box place, variant_index } => { - let Some(discr_target) = self.map.find_discr(place.as_ref()) else { - return Some(()); - }; + let Some(discr_target) = self.map.find_discr(place.as_ref()) else { return }; let enum_ty = place.ty(self.body, self.tcx).ty; // `SetDiscriminant` guarantees that the discriminant is now `variant_index`. // Even if the discriminant write does nothing due to niches, it is UB to set the // discriminant when the data does not encode the desired discriminant. - let discr = - self.ecx.discriminant_for_variant(enum_ty, *variant_index).discard_err()?; - self.process_immediate(bb, discr_target, discr, state); + let Some(discr) = + self.ecx.discriminant_for_variant(enum_ty, *variant_index).discard_err() + else { + return; + }; + self.process_immediate(bb, discr_target, discr, state) } // If we expect `lhs ?= true`, we have an opportunity if we assume `lhs == true`. StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume( Operand::Copy(place) | Operand::Move(place), )) => { - let Some(conditions) = state.try_get(place.as_ref(), &self.map) else { - return Some(()); - }; - conditions.iter_matches(ScalarInt::TRUE).for_each(register_opportunity); + let Some(conditions) = state.try_get(place.as_ref(), &self.map) else { return }; + conditions.iter_matches(ScalarInt::TRUE).for_each(register_opportunity) } StatementKind::Assign(box (lhs_place, rhs)) => { - self.process_assign(bb, lhs_place, rhs, state)?; + self.process_assign(bb, lhs_place, rhs, state) } _ => {} } - Some(()) } #[instrument(level = "trace", skip(self, state, cost))] @@ -617,7 +610,7 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { state: impl FnOnce() -> State>, cost: &CostChecker<'_, 'tcx>, depth: usize, - ) -> Option<()> { + ) { let term = self.body.basic_blocks[bb].terminator(); let place_to_flood = match term.kind { // We come from a target, so those are not possible. @@ -632,9 +625,9 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> { | TerminatorKind::FalseUnwind { .. } | TerminatorKind::Yield { .. } => bug!("{term:?} invalid"), // Cannot reason about inline asm. - TerminatorKind::InlineAsm { .. } => return Some(()), + TerminatorKind::InlineAsm { .. } => return, // `SwitchInt` is handled specially. - TerminatorKind::SwitchInt { .. } => return Some(()), + TerminatorKind::SwitchInt { .. } => return, // We can recurse, no thing particular to do. TerminatorKind::Goto { .. } => None, // Flood the overwritten place, and progress through. From e0d9244472b50631f07af8a425c1dbed65161d25 Mon Sep 17 00:00:00 2001 From: Thalia Archibald Date: Tue, 15 Apr 2025 05:29:38 -0700 Subject: [PATCH 256/266] Sort Unix env constants alphabetically by target_os They were roughly grouped into Linux, Apple, BSD, and everything else, roughly in alphabetical order. Alphabetically order them to make it easier to maintain and discard the Unix-specific groups to generalize it to all platforms. --- library/std/src/sys/pal/unix/env.rs | 198 ++++++++++++++-------------- 1 file changed, 100 insertions(+), 98 deletions(-) diff --git a/library/std/src/sys/pal/unix/env.rs b/library/std/src/sys/pal/unix/env.rs index c6609298f4b23..1a5e23f06b804 100644 --- a/library/std/src/sys/pal/unix/env.rs +++ b/library/std/src/sys/pal/unix/env.rs @@ -1,73 +1,64 @@ -#[cfg(target_os = "linux")] -pub mod os { - pub const FAMILY: &str = "unix"; - pub const OS: &str = "linux"; - pub const DLL_PREFIX: &str = "lib"; - pub const DLL_SUFFIX: &str = ".so"; - pub const DLL_EXTENSION: &str = "so"; - pub const EXE_SUFFIX: &str = ""; - pub const EXE_EXTENSION: &str = ""; -} +// Keep entries sorted alphabetically. -#[cfg(target_os = "macos")] +#[cfg(target_os = "aix")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "macos"; + pub const OS: &str = "aix"; pub const DLL_PREFIX: &str = "lib"; - pub const DLL_SUFFIX: &str = ".dylib"; - pub const DLL_EXTENSION: &str = "dylib"; + pub const DLL_SUFFIX: &str = ".a"; + pub const DLL_EXTENSION: &str = "a"; pub const EXE_SUFFIX: &str = ""; pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "ios")] +#[cfg(target_os = "android")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "ios"; + pub const OS: &str = "android"; pub const DLL_PREFIX: &str = "lib"; - pub const DLL_SUFFIX: &str = ".dylib"; - pub const DLL_EXTENSION: &str = "dylib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; pub const EXE_SUFFIX: &str = ""; pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "tvos")] +#[cfg(target_os = "cygwin")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "tvos"; - pub const DLL_PREFIX: &str = "lib"; - pub const DLL_SUFFIX: &str = ".dylib"; - pub const DLL_EXTENSION: &str = "dylib"; - pub const EXE_SUFFIX: &str = ""; - pub const EXE_EXTENSION: &str = ""; + pub const OS: &str = "cygwin"; + pub const DLL_PREFIX: &str = ""; + pub const DLL_SUFFIX: &str = ".dll"; + pub const DLL_EXTENSION: &str = "dll"; + pub const EXE_SUFFIX: &str = ".exe"; + pub const EXE_EXTENSION: &str = "exe"; } -#[cfg(target_os = "watchos")] +#[cfg(target_os = "dragonfly")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "watchos"; + pub const OS: &str = "dragonfly"; pub const DLL_PREFIX: &str = "lib"; - pub const DLL_SUFFIX: &str = ".dylib"; - pub const DLL_EXTENSION: &str = "dylib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; pub const EXE_SUFFIX: &str = ""; pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "visionos")] +#[cfg(all(target_os = "emscripten", target_arch = "wasm32"))] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "visionos"; + pub const OS: &str = "emscripten"; pub const DLL_PREFIX: &str = "lib"; - pub const DLL_SUFFIX: &str = ".dylib"; - pub const DLL_EXTENSION: &str = "dylib"; - pub const EXE_SUFFIX: &str = ""; - pub const EXE_EXTENSION: &str = ""; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ".js"; + pub const EXE_EXTENSION: &str = "js"; } -#[cfg(target_os = "freebsd")] +#[cfg(target_os = "espidf")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "freebsd"; + pub const OS: &str = "espidf"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; @@ -75,10 +66,10 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "dragonfly")] +#[cfg(target_os = "freebsd")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "dragonfly"; + pub const OS: &str = "freebsd"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; @@ -86,10 +77,10 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "netbsd")] +#[cfg(target_os = "fuchsia")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "netbsd"; + pub const OS: &str = "fuchsia"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; @@ -97,10 +88,10 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "openbsd")] +#[cfg(target_os = "haiku")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "openbsd"; + pub const OS: &str = "haiku"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; @@ -108,32 +99,21 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "cygwin")] -pub mod os { - pub const FAMILY: &str = "unix"; - pub const OS: &str = "cygwin"; - pub const DLL_PREFIX: &str = ""; - pub const DLL_SUFFIX: &str = ".dll"; - pub const DLL_EXTENSION: &str = "dll"; - pub const EXE_SUFFIX: &str = ".exe"; - pub const EXE_EXTENSION: &str = "exe"; -} - -#[cfg(target_os = "android")] +#[cfg(target_os = "horizon")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "android"; + pub const OS: &str = "horizon"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; - pub const EXE_SUFFIX: &str = ""; - pub const EXE_EXTENSION: &str = ""; + pub const EXE_SUFFIX: &str = ".elf"; + pub const EXE_EXTENSION: &str = "elf"; } -#[cfg(target_os = "solaris")] +#[cfg(target_os = "hurd")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "solaris"; + pub const OS: &str = "hurd"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; @@ -152,32 +132,32 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "haiku")] +#[cfg(target_os = "ios")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "haiku"; + pub const OS: &str = "ios"; pub const DLL_PREFIX: &str = "lib"; - pub const DLL_SUFFIX: &str = ".so"; - pub const DLL_EXTENSION: &str = "so"; + pub const DLL_SUFFIX: &str = ".dylib"; + pub const DLL_EXTENSION: &str = "dylib"; pub const EXE_SUFFIX: &str = ""; pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "horizon")] +#[cfg(target_os = "l4re")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "horizon"; + pub const OS: &str = "l4re"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; - pub const EXE_SUFFIX: &str = ".elf"; - pub const EXE_EXTENSION: &str = "elf"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "hurd")] +#[cfg(target_os = "linux")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "hurd"; + pub const OS: &str = "linux"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; @@ -185,32 +165,32 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "vita")] +#[cfg(target_os = "macos")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "vita"; + pub const OS: &str = "macos"; pub const DLL_PREFIX: &str = "lib"; - pub const DLL_SUFFIX: &str = ".so"; - pub const DLL_EXTENSION: &str = "so"; - pub const EXE_SUFFIX: &str = ".elf"; - pub const EXE_EXTENSION: &str = "elf"; + pub const DLL_SUFFIX: &str = ".dylib"; + pub const DLL_EXTENSION: &str = "dylib"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } -#[cfg(all(target_os = "emscripten", target_arch = "wasm32"))] +#[cfg(target_os = "netbsd")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "emscripten"; + pub const OS: &str = "netbsd"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; - pub const EXE_SUFFIX: &str = ".js"; - pub const EXE_EXTENSION: &str = "js"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "fuchsia")] +#[cfg(target_os = "nto")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "fuchsia"; + pub const OS: &str = "nto"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; @@ -218,10 +198,10 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "l4re")] +#[cfg(target_os = "nuttx")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "l4re"; + pub const OS: &str = "nuttx"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; @@ -229,10 +209,10 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "nto")] +#[cfg(target_os = "openbsd")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "nto"; + pub const OS: &str = "openbsd"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; @@ -262,10 +242,10 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "vxworks")] +#[cfg(target_os = "solaris")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "vxworks"; + pub const OS: &str = "solaris"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; @@ -273,35 +253,57 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "espidf")] +#[cfg(target_os = "tvos")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "espidf"; + pub const OS: &str = "tvos"; pub const DLL_PREFIX: &str = "lib"; - pub const DLL_SUFFIX: &str = ".so"; - pub const DLL_EXTENSION: &str = "so"; + pub const DLL_SUFFIX: &str = ".dylib"; + pub const DLL_EXTENSION: &str = "dylib"; pub const EXE_SUFFIX: &str = ""; pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "aix")] +#[cfg(target_os = "visionos")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "aix"; + pub const OS: &str = "visionos"; pub const DLL_PREFIX: &str = "lib"; - pub const DLL_SUFFIX: &str = ".a"; - pub const DLL_EXTENSION: &str = "a"; + pub const DLL_SUFFIX: &str = ".dylib"; + pub const DLL_EXTENSION: &str = "dylib"; pub const EXE_SUFFIX: &str = ""; pub const EXE_EXTENSION: &str = ""; } -#[cfg(target_os = "nuttx")] +#[cfg(target_os = "vita")] pub mod os { pub const FAMILY: &str = "unix"; - pub const OS: &str = "nuttx"; + pub const OS: &str = "vita"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ".elf"; + pub const EXE_EXTENSION: &str = "elf"; +} + +#[cfg(target_os = "vxworks")] +pub mod os { + pub const FAMILY: &str = "unix"; + pub const OS: &str = "vxworks"; pub const DLL_PREFIX: &str = "lib"; pub const DLL_SUFFIX: &str = ".so"; pub const DLL_EXTENSION: &str = "so"; pub const EXE_SUFFIX: &str = ""; pub const EXE_EXTENSION: &str = ""; } + +#[cfg(target_os = "watchos")] +pub mod os { + pub const FAMILY: &str = "unix"; + pub const OS: &str = "watchos"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".dylib"; + pub const DLL_EXTENSION: &str = "dylib"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; +} From d863f81671459712627e2bf1a106b0b3e6b1bbce Mon Sep 17 00:00:00 2001 From: Sky Date: Fri, 18 Apr 2025 21:40:53 -0400 Subject: [PATCH 257/266] Re-remove `AdtFlags::IS_ANONYMOUS` --- compiler/rustc_middle/src/ty/adt.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index 66517c97a687e..d92b4f9c06beb 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -55,8 +55,6 @@ bitflags::bitflags! { const IS_UNSAFE_CELL = 1 << 9; /// Indicates whether the type is `UnsafePinned`. const IS_UNSAFE_PINNED = 1 << 10; - /// Indicates whether the type is anonymous. - const IS_ANONYMOUS = 1 << 11; } } rustc_data_structures::external_bitflags_debug! { AdtFlags } From 37712cc01604633fec6aac9bc720210207fa4b54 Mon Sep 17 00:00:00 2001 From: Thalia Archibald Date: Tue, 15 Apr 2025 05:48:27 -0700 Subject: [PATCH 258/266] Combine env consts into std::sys::env_consts --- library/std/src/env.rs | 2 +- .../sys/{pal/unix/env.rs => env_consts.rs} | 70 ++++++++++++++++++- library/std/src/sys/mod.rs | 1 + library/std/src/sys/pal/hermit/env.rs | 9 --- library/std/src/sys/pal/hermit/mod.rs | 1 - library/std/src/sys/pal/sgx/env.rs | 9 --- library/std/src/sys/pal/sgx/mod.rs | 1 - library/std/src/sys/pal/solid/env.rs | 9 --- library/std/src/sys/pal/solid/mod.rs | 1 - library/std/src/sys/pal/teeos/mod.rs | 3 - library/std/src/sys/pal/trusty/mod.rs | 2 - library/std/src/sys/pal/uefi/env.rs | 9 --- library/std/src/sys/pal/uefi/mod.rs | 1 - library/std/src/sys/pal/unix/mod.rs | 1 - library/std/src/sys/pal/unsupported/env.rs | 9 --- library/std/src/sys/pal/unsupported/mod.rs | 1 - library/std/src/sys/pal/wasi/env.rs | 11 --- library/std/src/sys/pal/wasi/mod.rs | 1 - library/std/src/sys/pal/wasip2/mod.rs | 2 - library/std/src/sys/pal/wasm/env.rs | 9 --- library/std/src/sys/pal/wasm/mod.rs | 1 - library/std/src/sys/pal/windows/env.rs | 9 --- library/std/src/sys/pal/windows/mod.rs | 1 - library/std/src/sys/pal/xous/mod.rs | 2 - library/std/src/sys/pal/zkvm/mod.rs | 1 - 25 files changed, 71 insertions(+), 95 deletions(-) rename library/std/src/sys/{pal/unix/env.rs => env_consts.rs} (81%) delete mode 100644 library/std/src/sys/pal/hermit/env.rs delete mode 100644 library/std/src/sys/pal/sgx/env.rs delete mode 100644 library/std/src/sys/pal/solid/env.rs delete mode 100644 library/std/src/sys/pal/uefi/env.rs delete mode 100644 library/std/src/sys/pal/unsupported/env.rs delete mode 100644 library/std/src/sys/pal/wasi/env.rs delete mode 100644 library/std/src/sys/pal/wasm/env.rs delete mode 100644 library/std/src/sys/pal/windows/env.rs diff --git a/library/std/src/env.rs b/library/std/src/env.rs index 05bd4345ea8dd..c84a72c4fad02 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -950,7 +950,7 @@ impl fmt::Debug for ArgsOs { /// Constants associated with the current target #[stable(feature = "env", since = "1.0.0")] pub mod consts { - use crate::sys::env::os; + use crate::sys::env_consts::os; /// A string describing the architecture of the CPU that is currently in use. /// An example value may be: `"x86"`, `"arm"` or `"riscv64"`. diff --git a/library/std/src/sys/pal/unix/env.rs b/library/std/src/sys/env_consts.rs similarity index 81% rename from library/std/src/sys/pal/unix/env.rs rename to library/std/src/sys/env_consts.rs index 1a5e23f06b804..f439aa5a905c5 100644 --- a/library/std/src/sys/pal/unix/env.rs +++ b/library/std/src/sys/env_consts.rs @@ -1,3 +1,5 @@ +//! Constants associated with each target. + // Keep entries sorted alphabetically. #[cfg(target_os = "aix")] @@ -44,7 +46,7 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } -#[cfg(all(target_os = "emscripten", target_arch = "wasm32"))] +#[cfg(target_os = "emscripten")] pub mod os { pub const FAMILY: &str = "unix"; pub const OS: &str = "emscripten"; @@ -99,6 +101,17 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } +#[cfg(target_os = "hermit")] +pub mod os { + pub const FAMILY: &str = ""; + pub const OS: &str = "hermit"; + pub const DLL_PREFIX: &str = ""; + pub const DLL_SUFFIX: &str = ""; + pub const DLL_EXTENSION: &str = ""; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; +} + #[cfg(target_os = "horizon")] pub mod os { pub const FAMILY: &str = "unix"; @@ -242,6 +255,17 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } +#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))] +pub mod os { + pub const FAMILY: &str = ""; + pub const OS: &str = ""; + pub const DLL_PREFIX: &str = ""; + pub const DLL_SUFFIX: &str = ".sgxs"; + pub const DLL_EXTENSION: &str = "sgxs"; + pub const EXE_SUFFIX: &str = ".sgxs"; + pub const EXE_EXTENSION: &str = "sgxs"; +} + #[cfg(target_os = "solaris")] pub mod os { pub const FAMILY: &str = "unix"; @@ -253,6 +277,17 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } +#[cfg(target_os = "solid_asp3")] +pub mod os { + pub const FAMILY: &str = "itron"; + pub const OS: &str = "solid"; + pub const DLL_PREFIX: &str = ""; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; +} + #[cfg(target_os = "tvos")] pub mod os { pub const FAMILY: &str = "unix"; @@ -264,6 +299,17 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } +#[cfg(target_os = "uefi")] +pub mod os { + pub const FAMILY: &str = ""; + pub const OS: &str = "uefi"; + pub const DLL_PREFIX: &str = ""; + pub const DLL_SUFFIX: &str = ""; + pub const DLL_EXTENSION: &str = ""; + pub const EXE_SUFFIX: &str = ".efi"; + pub const EXE_EXTENSION: &str = "efi"; +} + #[cfg(target_os = "visionos")] pub mod os { pub const FAMILY: &str = "unix"; @@ -297,6 +343,17 @@ pub mod os { pub const EXE_EXTENSION: &str = ""; } +#[cfg(all(target_family = "wasm", not(any(target_os = "emscripten", target_os = "linux"))))] +pub mod os { + pub const FAMILY: &str = ""; + pub const OS: &str = ""; + pub const DLL_PREFIX: &str = ""; + pub const DLL_SUFFIX: &str = ".wasm"; + pub const DLL_EXTENSION: &str = "wasm"; + pub const EXE_SUFFIX: &str = ".wasm"; + pub const EXE_EXTENSION: &str = "wasm"; +} + #[cfg(target_os = "watchos")] pub mod os { pub const FAMILY: &str = "unix"; @@ -307,3 +364,14 @@ pub mod os { pub const EXE_SUFFIX: &str = ""; pub const EXE_EXTENSION: &str = ""; } + +#[cfg(target_os = "windows")] +pub mod os { + pub const FAMILY: &str = "windows"; + pub const OS: &str = "windows"; + pub const DLL_PREFIX: &str = ""; + pub const DLL_SUFFIX: &str = ".dll"; + pub const DLL_EXTENSION: &str = "dll"; + pub const EXE_SUFFIX: &str = ".exe"; + pub const EXE_EXTENSION: &str = "exe"; +} diff --git a/library/std/src/sys/mod.rs b/library/std/src/sys/mod.rs index bc4bf11cb7405..e7b631999e0da 100644 --- a/library/std/src/sys/mod.rs +++ b/library/std/src/sys/mod.rs @@ -12,6 +12,7 @@ pub mod anonymous_pipe; pub mod args; pub mod backtrace; pub mod cmath; +pub mod env_consts; pub mod exit_guard; pub mod fd; pub mod fs; diff --git a/library/std/src/sys/pal/hermit/env.rs b/library/std/src/sys/pal/hermit/env.rs deleted file mode 100644 index 7a0fcb31ef2e8..0000000000000 --- a/library/std/src/sys/pal/hermit/env.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod os { - pub const FAMILY: &str = ""; - pub const OS: &str = "hermit"; - pub const DLL_PREFIX: &str = ""; - pub const DLL_SUFFIX: &str = ""; - pub const DLL_EXTENSION: &str = ""; - pub const EXE_SUFFIX: &str = ""; - pub const EXE_EXTENSION: &str = ""; -} diff --git a/library/std/src/sys/pal/hermit/mod.rs b/library/std/src/sys/pal/hermit/mod.rs index 821836824e2bc..70636760a83b6 100644 --- a/library/std/src/sys/pal/hermit/mod.rs +++ b/library/std/src/sys/pal/hermit/mod.rs @@ -18,7 +18,6 @@ use crate::os::raw::c_char; -pub mod env; pub mod futex; pub mod os; #[path = "../unsupported/pipe.rs"] diff --git a/library/std/src/sys/pal/sgx/env.rs b/library/std/src/sys/pal/sgx/env.rs deleted file mode 100644 index 8043b7c5213a1..0000000000000 --- a/library/std/src/sys/pal/sgx/env.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod os { - pub const FAMILY: &str = ""; - pub const OS: &str = ""; - pub const DLL_PREFIX: &str = ""; - pub const DLL_SUFFIX: &str = ".sgxs"; - pub const DLL_EXTENSION: &str = "sgxs"; - pub const EXE_SUFFIX: &str = ".sgxs"; - pub const EXE_EXTENSION: &str = "sgxs"; -} diff --git a/library/std/src/sys/pal/sgx/mod.rs b/library/std/src/sys/pal/sgx/mod.rs index 8a87e7a7ae13d..99735947e2cd4 100644 --- a/library/std/src/sys/pal/sgx/mod.rs +++ b/library/std/src/sys/pal/sgx/mod.rs @@ -9,7 +9,6 @@ use crate::io::ErrorKind; use crate::sync::atomic::{AtomicBool, Ordering}; pub mod abi; -pub mod env; mod libunwind_integration; pub mod os; #[path = "../unsupported/pipe.rs"] diff --git a/library/std/src/sys/pal/solid/env.rs b/library/std/src/sys/pal/solid/env.rs deleted file mode 100644 index 6855c113b2893..0000000000000 --- a/library/std/src/sys/pal/solid/env.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod os { - pub const FAMILY: &str = "itron"; - pub const OS: &str = "solid"; - pub const DLL_PREFIX: &str = ""; - pub const DLL_SUFFIX: &str = ".so"; - pub const DLL_EXTENSION: &str = "so"; - pub const EXE_SUFFIX: &str = ""; - pub const EXE_EXTENSION: &str = ""; -} diff --git a/library/std/src/sys/pal/solid/mod.rs b/library/std/src/sys/pal/solid/mod.rs index c41dc848a1b4a..0011cf256df74 100644 --- a/library/std/src/sys/pal/solid/mod.rs +++ b/library/std/src/sys/pal/solid/mod.rs @@ -16,7 +16,6 @@ pub mod itron { use super::unsupported; } -pub mod env; // `error` is `pub(crate)` so that it can be accessed by `itron/error.rs` as // `crate::sys::error` pub(crate) mod error; diff --git a/library/std/src/sys/pal/teeos/mod.rs b/library/std/src/sys/pal/teeos/mod.rs index b8095cec3e978..c7b1777725858 100644 --- a/library/std/src/sys/pal/teeos/mod.rs +++ b/library/std/src/sys/pal/teeos/mod.rs @@ -6,9 +6,6 @@ #![allow(unused_variables)] #![allow(dead_code)] -#[path = "../unsupported/env.rs"] -pub mod env; -//pub mod fd; pub mod os; #[path = "../unsupported/pipe.rs"] pub mod pipe; diff --git a/library/std/src/sys/pal/trusty/mod.rs b/library/std/src/sys/pal/trusty/mod.rs index 04e6b4c818687..275f606246336 100644 --- a/library/std/src/sys/pal/trusty/mod.rs +++ b/library/std/src/sys/pal/trusty/mod.rs @@ -3,8 +3,6 @@ #[path = "../unsupported/common.rs"] #[deny(unsafe_op_in_unsafe_fn)] mod common; -#[path = "../unsupported/env.rs"] -pub mod env; #[path = "../unsupported/os.rs"] pub mod os; #[path = "../unsupported/pipe.rs"] diff --git a/library/std/src/sys/pal/uefi/env.rs b/library/std/src/sys/pal/uefi/env.rs deleted file mode 100644 index c106d5fed3e1d..0000000000000 --- a/library/std/src/sys/pal/uefi/env.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod os { - pub const FAMILY: &str = ""; - pub const OS: &str = "uefi"; - pub const DLL_PREFIX: &str = ""; - pub const DLL_SUFFIX: &str = ""; - pub const DLL_EXTENSION: &str = ""; - pub const EXE_SUFFIX: &str = ".efi"; - pub const EXE_EXTENSION: &str = "efi"; -} diff --git a/library/std/src/sys/pal/uefi/mod.rs b/library/std/src/sys/pal/uefi/mod.rs index cd901f48b76f8..bd6a36021f4cb 100644 --- a/library/std/src/sys/pal/uefi/mod.rs +++ b/library/std/src/sys/pal/uefi/mod.rs @@ -13,7 +13,6 @@ //! [`OsString`]: crate::ffi::OsString #![forbid(unsafe_op_in_unsafe_fn)] -pub mod env; pub mod helpers; pub mod os; #[path = "../unsupported/pipe.rs"] diff --git a/library/std/src/sys/pal/unix/mod.rs b/library/std/src/sys/pal/unix/mod.rs index 3a790d9c868c9..a4702ae1b18d0 100644 --- a/library/std/src/sys/pal/unix/mod.rs +++ b/library/std/src/sys/pal/unix/mod.rs @@ -6,7 +6,6 @@ use crate::io::ErrorKind; #[macro_use] pub mod weak; -pub mod env; #[cfg(target_os = "fuchsia")] pub mod fuchsia; pub mod futex; diff --git a/library/std/src/sys/pal/unsupported/env.rs b/library/std/src/sys/pal/unsupported/env.rs deleted file mode 100644 index d2efec506c56b..0000000000000 --- a/library/std/src/sys/pal/unsupported/env.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod os { - pub const FAMILY: &str = ""; - pub const OS: &str = ""; - pub const DLL_PREFIX: &str = ""; - pub const DLL_SUFFIX: &str = ""; - pub const DLL_EXTENSION: &str = ""; - pub const EXE_SUFFIX: &str = ""; - pub const EXE_EXTENSION: &str = ""; -} diff --git a/library/std/src/sys/pal/unsupported/mod.rs b/library/std/src/sys/pal/unsupported/mod.rs index dea42a95dcc6f..5e3295b1331a3 100644 --- a/library/std/src/sys/pal/unsupported/mod.rs +++ b/library/std/src/sys/pal/unsupported/mod.rs @@ -1,6 +1,5 @@ #![deny(unsafe_op_in_unsafe_fn)] -pub mod env; pub mod os; pub mod pipe; pub mod thread; diff --git a/library/std/src/sys/pal/wasi/env.rs b/library/std/src/sys/pal/wasi/env.rs deleted file mode 100644 index 8d44498267360..0000000000000 --- a/library/std/src/sys/pal/wasi/env.rs +++ /dev/null @@ -1,11 +0,0 @@ -#![forbid(unsafe_op_in_unsafe_fn)] - -pub mod os { - pub const FAMILY: &str = ""; - pub const OS: &str = ""; - pub const DLL_PREFIX: &str = ""; - pub const DLL_SUFFIX: &str = ".wasm"; - pub const DLL_EXTENSION: &str = "wasm"; - pub const EXE_SUFFIX: &str = ".wasm"; - pub const EXE_EXTENSION: &str = "wasm"; -} diff --git a/library/std/src/sys/pal/wasi/mod.rs b/library/std/src/sys/pal/wasi/mod.rs index 4ea42b1082b1d..61dd1c3f98b10 100644 --- a/library/std/src/sys/pal/wasi/mod.rs +++ b/library/std/src/sys/pal/wasi/mod.rs @@ -13,7 +13,6 @@ //! compiling for wasm. That way it's a compile time error for something that's //! guaranteed to be a runtime error! -pub mod env; #[allow(unused)] #[path = "../wasm/atomics/futex.rs"] pub mod futex; diff --git a/library/std/src/sys/pal/wasip2/mod.rs b/library/std/src/sys/pal/wasip2/mod.rs index 6445bf2cc0d2c..47fe3221c9093 100644 --- a/library/std/src/sys/pal/wasip2/mod.rs +++ b/library/std/src/sys/pal/wasip2/mod.rs @@ -6,8 +6,6 @@ //! To begin with, this target mirrors the wasi target 1 to 1, but over //! time this will change significantly. -#[path = "../wasi/env.rs"] -pub mod env; #[allow(unused)] #[path = "../wasm/atomics/futex.rs"] pub mod futex; diff --git a/library/std/src/sys/pal/wasm/env.rs b/library/std/src/sys/pal/wasm/env.rs deleted file mode 100644 index 730e356d7fe95..0000000000000 --- a/library/std/src/sys/pal/wasm/env.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod os { - pub const FAMILY: &str = ""; - pub const OS: &str = ""; - pub const DLL_PREFIX: &str = ""; - pub const DLL_SUFFIX: &str = ".wasm"; - pub const DLL_EXTENSION: &str = "wasm"; - pub const EXE_SUFFIX: &str = ".wasm"; - pub const EXE_EXTENSION: &str = "wasm"; -} diff --git a/library/std/src/sys/pal/wasm/mod.rs b/library/std/src/sys/pal/wasm/mod.rs index af370020d96ab..37cb46a8f6b3f 100644 --- a/library/std/src/sys/pal/wasm/mod.rs +++ b/library/std/src/sys/pal/wasm/mod.rs @@ -16,7 +16,6 @@ #![deny(unsafe_op_in_unsafe_fn)] -pub mod env; #[path = "../unsupported/os.rs"] pub mod os; #[path = "../unsupported/pipe.rs"] diff --git a/library/std/src/sys/pal/windows/env.rs b/library/std/src/sys/pal/windows/env.rs deleted file mode 100644 index f0a99d6200cac..0000000000000 --- a/library/std/src/sys/pal/windows/env.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod os { - pub const FAMILY: &str = "windows"; - pub const OS: &str = "windows"; - pub const DLL_PREFIX: &str = ""; - pub const DLL_SUFFIX: &str = ".dll"; - pub const DLL_EXTENSION: &str = "dll"; - pub const EXE_SUFFIX: &str = ".exe"; - pub const EXE_EXTENSION: &str = "exe"; -} diff --git a/library/std/src/sys/pal/windows/mod.rs b/library/std/src/sys/pal/windows/mod.rs index 3c0a5c2de2636..4f18c4009ab6c 100644 --- a/library/std/src/sys/pal/windows/mod.rs +++ b/library/std/src/sys/pal/windows/mod.rs @@ -15,7 +15,6 @@ pub mod compat; pub mod api; pub mod c; -pub mod env; #[cfg(not(target_vendor = "win7"))] pub mod futex; pub mod handle; diff --git a/library/std/src/sys/pal/xous/mod.rs b/library/std/src/sys/pal/xous/mod.rs index 4f652d3f130de..383d031ed4353 100644 --- a/library/std/src/sys/pal/xous/mod.rs +++ b/library/std/src/sys/pal/xous/mod.rs @@ -1,7 +1,5 @@ #![forbid(unsafe_op_in_unsafe_fn)] -#[path = "../unsupported/env.rs"] -pub mod env; pub mod os; #[path = "../unsupported/pipe.rs"] pub mod pipe; diff --git a/library/std/src/sys/pal/zkvm/mod.rs b/library/std/src/sys/pal/zkvm/mod.rs index ebd7b03677988..e1efa2406858f 100644 --- a/library/std/src/sys/pal/zkvm/mod.rs +++ b/library/std/src/sys/pal/zkvm/mod.rs @@ -11,7 +11,6 @@ pub const WORD_SIZE: usize = size_of::(); pub mod abi; -pub mod env; pub mod os; #[path = "../unsupported/pipe.rs"] pub mod pipe; From 670ff84d1c70146a2556b41650d3e417143c6c60 Mon Sep 17 00:00:00 2001 From: Thalia Archibald Date: Tue, 15 Apr 2025 06:42:39 -0700 Subject: [PATCH 259/266] Handle unsupported fallback --- library/std/src/sys/env_consts.rs | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/library/std/src/sys/env_consts.rs b/library/std/src/sys/env_consts.rs index f439aa5a905c5..018d7954db26a 100644 --- a/library/std/src/sys/env_consts.rs +++ b/library/std/src/sys/env_consts.rs @@ -1,6 +1,19 @@ //! Constants associated with each target. -// Keep entries sorted alphabetically. +// Replaces the #[else] gate with #[cfg(not(any(…)))] of all the other gates. +// This ensures that they must be mutually exclusive and do not have precedence +// like cfg_if!. +macro cfg_unordered( + $(#[cfg($cfg:meta)] $os:item)* + #[else] $fallback:item +) { + $(#[cfg($cfg)] $os)* + #[cfg(not(any($($cfg),*)))] $fallback +} + +// Keep entries sorted alphabetically and mutually exclusive. + +cfg_unordered! { #[cfg(target_os = "aix")] pub mod os { @@ -375,3 +388,17 @@ pub mod os { pub const EXE_SUFFIX: &str = ".exe"; pub const EXE_EXTENSION: &str = "exe"; } + +// The fallback when none of the other gates match. +#[else] +pub mod os { + pub const FAMILY: &str = ""; + pub const OS: &str = ""; + pub const DLL_PREFIX: &str = ""; + pub const DLL_SUFFIX: &str = ""; + pub const DLL_EXTENSION: &str = ""; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; +} + +} From 93fa96cfba126d542ebd33624e5f774d397dbf3f Mon Sep 17 00:00:00 2001 From: Thalia Archibald Date: Fri, 18 Apr 2025 16:45:26 -0700 Subject: [PATCH 260/266] Use struct update syntax for some TargetOptions --- compiler/rustc_target/src/spec/base/linux_musl.rs | 15 +++++++-------- compiler/rustc_target/src/spec/base/linux_ohos.rs | 15 +++++++-------- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_target/src/spec/base/linux_musl.rs b/compiler/rustc_target/src/spec/base/linux_musl.rs index 1a854fe362d50..1bef602404e56 100644 --- a/compiler/rustc_target/src/spec/base/linux_musl.rs +++ b/compiler/rustc_target/src/spec/base/linux_musl.rs @@ -1,12 +1,11 @@ use crate::spec::{LinkSelfContainedDefault, TargetOptions, base, crt_objects}; pub(crate) fn opts() -> TargetOptions { - let mut base = base::linux::opts(); - - base.env = "musl".into(); - base.pre_link_objects_self_contained = crt_objects::pre_musl_self_contained(); - base.post_link_objects_self_contained = crt_objects::post_musl_self_contained(); - base.link_self_contained = LinkSelfContainedDefault::InferredForMusl; - - base + TargetOptions { + env: "musl".into(), + pre_link_objects_self_contained: crt_objects::pre_musl_self_contained(), + post_link_objects_self_contained: crt_objects::post_musl_self_contained(), + link_self_contained: LinkSelfContainedDefault::InferredForMusl, + ..base::linux::opts() + } } diff --git a/compiler/rustc_target/src/spec/base/linux_ohos.rs b/compiler/rustc_target/src/spec/base/linux_ohos.rs index 6f4d69a996c34..1b7f1e196664f 100644 --- a/compiler/rustc_target/src/spec/base/linux_ohos.rs +++ b/compiler/rustc_target/src/spec/base/linux_ohos.rs @@ -1,12 +1,11 @@ use crate::spec::{TargetOptions, TlsModel, base}; pub(crate) fn opts() -> TargetOptions { - let mut base = base::linux::opts(); - - base.env = "ohos".into(); - base.crt_static_default = false; - base.tls_model = TlsModel::Emulated; - base.has_thread_local = false; - - base + TargetOptions { + env: "ohos".into(), + crt_static_default: false, + tls_model: TlsModel::Emulated, + has_thread_local: false, + ..base::linux::opts() + } } From 3eaa4b93684f10765ce9b8004fac461008ae678a Mon Sep 17 00:00:00 2001 From: Spencer Date: Tue, 15 Apr 2025 21:06:27 -0600 Subject: [PATCH 261/266] Cleaned up 4 tests in `tests/ui/issues` --- src/tools/tidy/src/issues.txt | 5 -- src/tools/tidy/src/ui_tests.rs | 2 +- tests/ui/argument-suggestions/exotic-calls.rs | 10 +++ .../argument-suggestions/exotic-calls.stderr | 35 ++++++++--- .../ref-dyn-trait-in-structs-and-enums.rs | 54 ++++++++++++++++ tests/ui/issues/auxiliary/issue-14421.rs | 25 -------- tests/ui/issues/issue-14421.rs | 15 ----- tests/ui/issues/issue-16939.rs | 8 --- tests/ui/issues/issue-16939.stderr | 20 ------ tests/ui/issues/issue-23808.rs | 59 ------------------ tests/ui/issues/issue-9719.rs | 40 ------------ ...ead-code-reexported-types-across-crates.rs | 33 ++++++++++ .../no-dead-code-for-static-trait-impl.rs | 61 +++++++++++++++++++ ...ead-code-reexported-types-across-crates.rs | 17 ++++++ 14 files changed, 202 insertions(+), 182 deletions(-) create mode 100644 tests/ui/codegen/ref-dyn-trait-in-structs-and-enums.rs delete mode 100644 tests/ui/issues/auxiliary/issue-14421.rs delete mode 100644 tests/ui/issues/issue-14421.rs delete mode 100644 tests/ui/issues/issue-16939.rs delete mode 100644 tests/ui/issues/issue-16939.stderr delete mode 100644 tests/ui/issues/issue-23808.rs delete mode 100644 tests/ui/issues/issue-9719.rs create mode 100644 tests/ui/lint/dead-code/auxiliary/no-dead-code-reexported-types-across-crates.rs create mode 100644 tests/ui/lint/dead-code/no-dead-code-for-static-trait-impl.rs create mode 100644 tests/ui/lint/dead-code/no-dead-code-reexported-types-across-crates.rs diff --git a/src/tools/tidy/src/issues.txt b/src/tools/tidy/src/issues.txt index d2ae9b1f6ef89..1df95e9159403 100644 --- a/src/tools/tidy/src/issues.txt +++ b/src/tools/tidy/src/issues.txt @@ -1397,7 +1397,6 @@ ui/issues/auxiliary/issue-13620-1.rs ui/issues/auxiliary/issue-13620-2.rs ui/issues/auxiliary/issue-14344-1.rs ui/issues/auxiliary/issue-14344-2.rs -ui/issues/auxiliary/issue-14421.rs ui/issues/auxiliary/issue-14422.rs ui/issues/auxiliary/issue-15562.rs ui/issues/auxiliary/issue-16643.rs @@ -1564,7 +1563,6 @@ ui/issues/issue-14366.rs ui/issues/issue-14382.rs ui/issues/issue-14393.rs ui/issues/issue-14399.rs -ui/issues/issue-14421.rs ui/issues/issue-14422.rs ui/issues/issue-14541.rs ui/issues/issue-14721.rs @@ -1629,7 +1627,6 @@ ui/issues/issue-16774.rs ui/issues/issue-16783.rs ui/issues/issue-16819.rs ui/issues/issue-16922-rpass.rs -ui/issues/issue-16939.rs ui/issues/issue-16966.rs ui/issues/issue-16994.rs ui/issues/issue-17001.rs @@ -1867,7 +1864,6 @@ ui/issues/issue-23550.rs ui/issues/issue-23589.rs ui/issues/issue-23699.rs ui/issues/issue-2380-b.rs -ui/issues/issue-23808.rs ui/issues/issue-2383.rs ui/issues/issue-23891.rs ui/issues/issue-23898.rs @@ -2607,7 +2603,6 @@ ui/issues/issue-9249.rs ui/issues/issue-9259.rs ui/issues/issue-92741.rs ui/issues/issue-9446.rs -ui/issues/issue-9719.rs ui/issues/issue-9725.rs ui/issues/issue-9737.rs ui/issues/issue-9814.rs diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index 61728d0553fde..2e069af23d653 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -17,7 +17,7 @@ use ignore::Walk; const ENTRY_LIMIT: u32 = 901; // FIXME: The following limits should be reduced eventually. -const ISSUES_ENTRY_LIMIT: u32 = 1631; +const ISSUES_ENTRY_LIMIT: u32 = 1626; const EXPECTED_TEST_FILE_EXTENSIONS: &[&str] = &[ "rs", // test source files diff --git a/tests/ui/argument-suggestions/exotic-calls.rs b/tests/ui/argument-suggestions/exotic-calls.rs index 569a39a2b450d..765b4bc536c3a 100644 --- a/tests/ui/argument-suggestions/exotic-calls.rs +++ b/tests/ui/argument-suggestions/exotic-calls.rs @@ -1,8 +1,18 @@ +//! Checks variations of E0057, which is the incorrect number of agruments passed into a closure + +//@ check-fail + fn foo(t: T) { t(1i32); //~^ ERROR function takes 0 arguments but 1 argument was supplied } +/// Regression test for +fn foo2(f: T) { + |t| f(t); + //~^ ERROR function takes 0 arguments but 1 argument was supplied +} + fn bar(t: impl Fn()) { t(1i32); //~^ ERROR function takes 0 arguments but 1 argument was supplied diff --git a/tests/ui/argument-suggestions/exotic-calls.stderr b/tests/ui/argument-suggestions/exotic-calls.stderr index aca3b8a343343..e78871c19cb97 100644 --- a/tests/ui/argument-suggestions/exotic-calls.stderr +++ b/tests/ui/argument-suggestions/exotic-calls.stderr @@ -1,11 +1,11 @@ error[E0057]: this function takes 0 arguments but 1 argument was supplied - --> $DIR/exotic-calls.rs:2:5 + --> $DIR/exotic-calls.rs:6:5 | LL | t(1i32); | ^ ---- unexpected argument of type `i32` | note: callable defined here - --> $DIR/exotic-calls.rs:1:11 + --> $DIR/exotic-calls.rs:5:11 | LL | fn foo(t: T) { | ^^^^ @@ -16,13 +16,30 @@ LL + t(); | error[E0057]: this function takes 0 arguments but 1 argument was supplied - --> $DIR/exotic-calls.rs:7:5 + --> $DIR/exotic-calls.rs:12:9 + | +LL | |t| f(t); + | ^ - unexpected argument + | +note: callable defined here + --> $DIR/exotic-calls.rs:11:12 + | +LL | fn foo2(f: T) { + | ^^^^ +help: remove the extra argument + | +LL - |t| f(t); +LL + |t| f(); + | + +error[E0057]: this function takes 0 arguments but 1 argument was supplied + --> $DIR/exotic-calls.rs:17:5 | LL | t(1i32); | ^ ---- unexpected argument of type `i32` | note: type parameter defined here - --> $DIR/exotic-calls.rs:6:11 + --> $DIR/exotic-calls.rs:16:11 | LL | fn bar(t: impl Fn()) { | ^^^^^^^^^ @@ -33,13 +50,13 @@ LL + t(); | error[E0057]: this function takes 0 arguments but 1 argument was supplied - --> $DIR/exotic-calls.rs:16:5 + --> $DIR/exotic-calls.rs:26:5 | LL | baz()(1i32) | ^^^^^ ---- unexpected argument of type `i32` | note: opaque type defined here - --> $DIR/exotic-calls.rs:11:13 + --> $DIR/exotic-calls.rs:21:13 | LL | fn baz() -> impl Fn() { | ^^^^^^^^^ @@ -50,13 +67,13 @@ LL + baz()() | error[E0057]: this function takes 0 arguments but 1 argument was supplied - --> $DIR/exotic-calls.rs:22:5 + --> $DIR/exotic-calls.rs:32:5 | LL | x(1i32); | ^ ---- unexpected argument of type `i32` | note: closure defined here - --> $DIR/exotic-calls.rs:21:13 + --> $DIR/exotic-calls.rs:31:13 | LL | let x = || {}; | ^^ @@ -66,6 +83,6 @@ LL - x(1i32); LL + x(); | -error: aborting due to 4 previous errors +error: aborting due to 5 previous errors For more information about this error, try `rustc --explain E0057`. diff --git a/tests/ui/codegen/ref-dyn-trait-in-structs-and-enums.rs b/tests/ui/codegen/ref-dyn-trait-in-structs-and-enums.rs new file mode 100644 index 0000000000000..04548817773e3 --- /dev/null +++ b/tests/ui/codegen/ref-dyn-trait-in-structs-and-enums.rs @@ -0,0 +1,54 @@ +//! Regression test for an LLVM assertion that used to be hit when: +//! +//! - There's a generic enum contained within a tuple struct +//! - When the tuple struct is parameterized by some lifetime `'a` +//! - The enum is concretized with its type argument being a reference to a trait object (of +//! lifetime `'a`) +//! +//! Issue: + +//@ build-pass + +// Dummy trait implemented for `isize` to use in the test cases +pub trait MyTrait { + fn dummy(&self) {} +} +impl MyTrait for isize {} + +// `&dyn MyTrait` contained in enum variant +pub struct EnumRefDynTrait<'a>(Enum<&'a (dyn MyTrait + 'a)>); +pub enum Enum { + Variant(T), +} + +fn enum_dyn_trait() { + let x: isize = 42; + let y = EnumRefDynTrait(Enum::Variant(&x as &dyn MyTrait)); + let _ = y; +} + +// `&dyn MyTrait` contained behind `Option` in named field of struct +struct RefDynTraitNamed<'a> { + x: Option<&'a (dyn MyTrait + 'a)>, +} + +fn named_option_dyn_trait() { + let x: isize = 42; + let y = RefDynTraitNamed { x: Some(&x as &dyn MyTrait) }; + let _ = y; +} + +// `&dyn MyTrait` contained behind `Option` in unnamed field of struct +pub struct RefDynTraitUnnamed<'a>(Option<&'a (dyn MyTrait + 'a)>); + +fn unnamed_option_dyn_trait() { + let x: isize = 42; + let y = RefDynTraitUnnamed(Some(&x as &dyn MyTrait)); + let _ = y; +} + +pub fn main() { + enum_dyn_trait(); + named_option_dyn_trait(); + unnamed_option_dyn_trait(); +} diff --git a/tests/ui/issues/auxiliary/issue-14421.rs b/tests/ui/issues/auxiliary/issue-14421.rs deleted file mode 100644 index 5fe4b24cf1708..0000000000000 --- a/tests/ui/issues/auxiliary/issue-14421.rs +++ /dev/null @@ -1,25 +0,0 @@ -#![crate_type="lib"] -#![deny(warnings)] -#![allow(dead_code)] - -pub use src::aliases::B; -pub use src::hidden_core::make; - -mod src { - pub mod aliases { - use super::hidden_core::A; - pub type B = A; - } - - pub mod hidden_core { - use super::aliases::B; - - pub struct A { t: T } - - pub fn make() -> B { A { t: 1.0 } } - - impl A { - pub fn foo(&mut self) { println!("called foo"); } - } - } -} diff --git a/tests/ui/issues/issue-14421.rs b/tests/ui/issues/issue-14421.rs deleted file mode 100644 index b7038584fcea6..0000000000000 --- a/tests/ui/issues/issue-14421.rs +++ /dev/null @@ -1,15 +0,0 @@ -//@ run-pass -#![allow(non_snake_case)] - -//@ aux-build:issue-14421.rs - - -extern crate issue_14421 as bug_lib; - -use bug_lib::B; -use bug_lib::make; - -pub fn main() { - let mut an_A: B = make(); - an_A.foo(); -} diff --git a/tests/ui/issues/issue-16939.rs b/tests/ui/issues/issue-16939.rs deleted file mode 100644 index ad7248343918d..0000000000000 --- a/tests/ui/issues/issue-16939.rs +++ /dev/null @@ -1,8 +0,0 @@ -// Make sure we don't ICE when making an overloaded call with the -// wrong arity. - -fn _foo (f: F) { - |t| f(t); //~ ERROR E0057 -} - -fn main() {} diff --git a/tests/ui/issues/issue-16939.stderr b/tests/ui/issues/issue-16939.stderr deleted file mode 100644 index 6e0889b89635b..0000000000000 --- a/tests/ui/issues/issue-16939.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error[E0057]: this function takes 0 arguments but 1 argument was supplied - --> $DIR/issue-16939.rs:5:9 - | -LL | |t| f(t); - | ^ - unexpected argument - | -note: callable defined here - --> $DIR/issue-16939.rs:4:12 - | -LL | fn _foo (f: F) { - | ^^^^ -help: remove the extra argument - | -LL - |t| f(t); -LL + |t| f(); - | - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0057`. diff --git a/tests/ui/issues/issue-23808.rs b/tests/ui/issues/issue-23808.rs deleted file mode 100644 index 6af0bd422e3a5..0000000000000 --- a/tests/ui/issues/issue-23808.rs +++ /dev/null @@ -1,59 +0,0 @@ -//@ run-pass - -#![deny(dead_code)] - -// use different types / traits to test all combinations - -trait Const { - const C: (); -} - -trait StaticFn { - fn sfn(); -} - -struct ConstStruct; -struct StaticFnStruct; - -enum ConstEnum {} -enum StaticFnEnum {} - -struct AliasedConstStruct; -struct AliasedStaticFnStruct; - -enum AliasedConstEnum {} -enum AliasedStaticFnEnum {} - -type AliasConstStruct = AliasedConstStruct; -type AliasStaticFnStruct = AliasedStaticFnStruct; -type AliasConstEnum = AliasedConstEnum; -type AliasStaticFnEnum = AliasedStaticFnEnum; - -macro_rules! impl_Const {($($T:ident),*) => {$( - impl Const for $T { - const C: () = (); - } -)*}} - -macro_rules! impl_StaticFn {($($T:ident),*) => {$( - impl StaticFn for $T { - fn sfn() {} - } -)*}} - -impl_Const!(ConstStruct, ConstEnum, AliasedConstStruct, AliasedConstEnum); -impl_StaticFn!(StaticFnStruct, StaticFnEnum, AliasedStaticFnStruct, AliasedStaticFnEnum); - -fn main() { - let () = ConstStruct::C; - let () = ConstEnum::C; - - StaticFnStruct::sfn(); - StaticFnEnum::sfn(); - - let () = AliasConstStruct::C; - let () = AliasConstEnum::C; - - AliasStaticFnStruct::sfn(); - AliasStaticFnEnum::sfn(); -} diff --git a/tests/ui/issues/issue-9719.rs b/tests/ui/issues/issue-9719.rs deleted file mode 100644 index 904768c934144..0000000000000 --- a/tests/ui/issues/issue-9719.rs +++ /dev/null @@ -1,40 +0,0 @@ -//@ build-pass -#![allow(dead_code)] - -mod a { - pub enum Enum { - A(T), - } - - pub trait X { - fn dummy(&self) { } - } - impl X for isize {} - - pub struct Z<'a>(Enum<&'a (dyn X + 'a)>); - fn foo() { let x: isize = 42; let z = Z(Enum::A(&x as &dyn X)); let _ = z; } -} - -mod b { - trait X { - fn dummy(&self) { } - } - impl X for isize {} - struct Y<'a>{ - x:Option<&'a (dyn X + 'a)>, - } - - fn bar() { - let x: isize = 42; - let _y = Y { x: Some(&x as &dyn X) }; - } -} - -mod c { - pub trait X { fn f(&self); } - impl X for isize { fn f(&self) {} } - pub struct Z<'a>(Option<&'a (dyn X + 'a)>); - fn main() { let x: isize = 42; let z = Z(Some(&x as &dyn X)); let _ = z; } -} - -pub fn main() {} diff --git a/tests/ui/lint/dead-code/auxiliary/no-dead-code-reexported-types-across-crates.rs b/tests/ui/lint/dead-code/auxiliary/no-dead-code-reexported-types-across-crates.rs new file mode 100644 index 0000000000000..5f328d1abf6ab --- /dev/null +++ b/tests/ui/lint/dead-code/auxiliary/no-dead-code-reexported-types-across-crates.rs @@ -0,0 +1,33 @@ +//! Auxilary file for testing `dead_code` lint. This crate is compiled as a library and exposes +//! aliased types. When used externally, there should not be warnings of `dead_code` +//! +//! Issue: + +// Expose internal types to be used in external test +pub use src::aliases::ExposedType; +pub use src::hidden_core::new; + +mod src { + pub mod aliases { + use super::hidden_core::InternalStruct; + pub type ExposedType = InternalStruct; + } + + pub mod hidden_core { + use super::aliases::ExposedType; + + pub struct InternalStruct { + _x: T, + } + + pub fn new() -> ExposedType { + InternalStruct { _x: 1.0 } + } + + impl InternalStruct { + pub fn foo(&mut self) { + println!("called foo"); + } + } + } +} diff --git a/tests/ui/lint/dead-code/no-dead-code-for-static-trait-impl.rs b/tests/ui/lint/dead-code/no-dead-code-for-static-trait-impl.rs new file mode 100644 index 0000000000000..8d54eda6bcaae --- /dev/null +++ b/tests/ui/lint/dead-code/no-dead-code-for-static-trait-impl.rs @@ -0,0 +1,61 @@ +//! Regression test to ensure false positive `dead_code` diagnostic warnings are not triggered for +//! structs and enums that implement static trait functions or use associated constants. +//! +//! Aliased versions of all cases are also tested +//! +//! Issue: + +//@ check-pass +#![deny(dead_code)] + +trait Const { + const C: (); +} + +trait StaticFn { + fn sfn(); +} + +macro_rules! impl_const {($($T:ident),*) => {$( + impl Const for $T { + const C: () = (); + } +)*}} + +macro_rules! impl_static_fn {($($T:ident),*) => {$( + impl StaticFn for $T { + fn sfn() {} + } +)*}} + +struct ConstStruct; +enum ConstEnum {} +struct AliasedConstStruct; +type AliasConstStruct = AliasedConstStruct; +enum AliasedConstEnum {} +type AliasConstEnum = AliasedConstEnum; + +impl_const!(ConstStruct, ConstEnum, AliasedConstStruct, AliasedConstEnum); + +struct StaticFnStruct; +enum StaticFnEnum {} +struct AliasedStaticFnStruct; +type AliasStaticFnStruct = AliasedStaticFnStruct; +enum AliasedStaticFnEnum {} +type AliasStaticFnEnum = AliasedStaticFnEnum; + +impl_static_fn!(StaticFnStruct, StaticFnEnum, AliasedStaticFnStruct, AliasedStaticFnEnum); + +fn main() { + // Use the associated constant for all the types, they should be considered "used" + let () = ConstStruct::C; + let () = ConstEnum::C; + let () = AliasConstStruct::C; + let () = AliasConstEnum::C; + + // Use the associated static function for all the types, they should be considered "used" + StaticFnStruct::sfn(); + StaticFnEnum::sfn(); + AliasStaticFnStruct::sfn(); + AliasStaticFnEnum::sfn(); +} diff --git a/tests/ui/lint/dead-code/no-dead-code-reexported-types-across-crates.rs b/tests/ui/lint/dead-code/no-dead-code-reexported-types-across-crates.rs new file mode 100644 index 0000000000000..11082f772ff61 --- /dev/null +++ b/tests/ui/lint/dead-code/no-dead-code-reexported-types-across-crates.rs @@ -0,0 +1,17 @@ +//! Regression test to ensure that `dead_code` warning does not get triggered when using re-exported +//! types that are exposed from a different crate +//! +//! Issue: + +//@ check-pass +//@ aux-build:no-dead-code-reexported-types-across-crates.rs + +extern crate no_dead_code_reexported_types_across_crates as bug_lib; + +use bug_lib::ExposedType; +use bug_lib::new; + +pub fn main() { + let mut x: ExposedType = new(); + x.foo(); +} From 1f491dccba0d593ba6ba87ae830a59e571b9309f Mon Sep 17 00:00:00 2001 From: Jonathan Gruner Date: Tue, 8 Apr 2025 17:17:21 +0200 Subject: [PATCH 262/266] add next_index to Enumerate --- library/core/src/iter/adapters/enumerate.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/library/core/src/iter/adapters/enumerate.rs b/library/core/src/iter/adapters/enumerate.rs index bd093e279c38e..1f2cf3244b357 100644 --- a/library/core/src/iter/adapters/enumerate.rs +++ b/library/core/src/iter/adapters/enumerate.rs @@ -23,6 +23,18 @@ impl Enumerate { pub(in crate::iter) fn new(iter: I) -> Enumerate { Enumerate { iter, count: 0 } } + + /// Retrieve the current position of the iterator. + /// + /// If the iterator has not advanced, the position returned will be 0. + /// + /// The position may also exceed the bounds of the iterator to allow for calculating + /// the displacement of the iterator from following calls to [`Iterator::next`]. + #[inline] + #[unstable(feature = "next_index", issue = "130711")] + pub fn next_index(&self) -> usize { + self.count + } } #[stable(feature = "rust1", since = "1.0.0")] From 5a71fabe297ab172eb873a03ab5e057ca55f78db Mon Sep 17 00:00:00 2001 From: Jonathan Gruner Date: Sat, 19 Apr 2025 12:06:30 +0200 Subject: [PATCH 263/266] added doctest for Enumerate::next_index --- library/core/src/iter/adapters/enumerate.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/library/core/src/iter/adapters/enumerate.rs b/library/core/src/iter/adapters/enumerate.rs index 1f2cf3244b357..f7b9f0b7a5e9d 100644 --- a/library/core/src/iter/adapters/enumerate.rs +++ b/library/core/src/iter/adapters/enumerate.rs @@ -30,6 +30,27 @@ impl Enumerate { /// /// The position may also exceed the bounds of the iterator to allow for calculating /// the displacement of the iterator from following calls to [`Iterator::next`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(next_index)] + /// + /// let arr = ['a', 'b']; + /// + /// let mut iter = arr.iter().enumerate(); + /// + /// assert_eq!(iter.next_index(), 0); + /// assert_eq!(iter.next(), Some((0, &'a'))); + /// + /// assert_eq!(iter.next_index(), 1); + /// assert_eq!(iter.next_index(), 1); + /// assert_eq!(iter.next(), Some((1, &'b'))); + /// + /// assert_eq!(iter.next_index(), 2); + /// assert_eq!(iter.next(), None); + /// assert_eq!(iter.next_index(), 2); + /// ``` #[inline] #[unstable(feature = "next_index", issue = "130711")] pub fn next_index(&self) -> usize { From f121c7c3605d195a05a9802735994e3576be9d62 Mon Sep 17 00:00:00 2001 From: Jonathan Gruner Date: Sat, 19 Apr 2025 12:26:57 +0200 Subject: [PATCH 264/266] added test for Enumerate::next_index on empty iterator --- library/coretests/tests/iter/adapters/enumerate.rs | 10 ++++++++++ library/coretests/tests/lib.rs | 1 + 2 files changed, 11 insertions(+) diff --git a/library/coretests/tests/iter/adapters/enumerate.rs b/library/coretests/tests/iter/adapters/enumerate.rs index b57d51c077e9b..2294f856b58d6 100644 --- a/library/coretests/tests/iter/adapters/enumerate.rs +++ b/library/coretests/tests/iter/adapters/enumerate.rs @@ -120,3 +120,13 @@ fn test_double_ended_enumerate() { assert_eq!(it.next_back(), Some((2, 3))); assert_eq!(it.next(), None); } + +#[test] +fn test_empty_iterator_enumerate_next_index() { + let mut it = empty::().enumerate(); + assert_eq!(it.next_index(), 0); + assert_eq!(it.next_index(), 0); + assert_eq!(it.next(), None); + assert_eq!(it.next_index(), 0); + assert_eq!(it.next_index(), 0); +} diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index 1c43bfe0ed4a9..ac11157593832 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -63,6 +63,7 @@ #![feature(maybe_uninit_write_slice)] #![feature(min_specialization)] #![feature(never_type)] +#![feature(next_index)] #![feature(numfmt)] #![feature(pattern)] #![feature(pointer_is_aligned_to)] From 1d87d14cdbbcff685569509ab2b9b06cb605c759 Mon Sep 17 00:00:00 2001 From: apiraino Date: Sat, 19 Apr 2025 14:42:02 +0200 Subject: [PATCH 265/266] Add option for stable backport poll skip-checks: true --- triagebot.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/triagebot.toml b/triagebot.toml index 226f024c156b7..0f17d022fbb84 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -659,6 +659,7 @@ message_on_add = [ """\ /poll Approve stable backport of #{number}? approve +approve (but does not justify new dot release on its own) decline don't know """, From 73c500a7d905c9fe8e06e73b9fb703ec051dfb05 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Sun, 20 Apr 2025 18:49:26 +0530 Subject: [PATCH 266/266] download bootstrap binary from ci --- src/bootstrap/bootstrap.py | 179 +++++++++++++++++++++++++++++++------ 1 file changed, 154 insertions(+), 25 deletions(-) diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index 42ad14a81d029..f440b1dfaf70d 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -48,12 +48,11 @@ def eprint(*args, **kwargs): print(*args, **kwargs) -def get(base, url, path, checksums, verbose=False): +def get(base, url, path, checksums, verbose=False, verify_checksum=True): with tempfile.NamedTemporaryFile(delete=False) as temp_file: temp_path = temp_file.name - try: - if url not in checksums: + if url not in checksums and verify_checksum: raise RuntimeError( ( "src/stage0 doesn't contain a checksum for {}. " @@ -62,30 +61,32 @@ def get(base, url, path, checksums, verbose=False): "/rustc/platform-support.html for more information." ).format(url) ) - sha256 = checksums[url] - if os.path.exists(path): - if verify(path, sha256, False): - if verbose: - eprint("using already-download file", path) - return - else: - if verbose: - eprint( - "ignoring already-download file", - path, - "due to failed verification", - ) - os.unlink(path) + if verify_checksum: + sha256 = checksums[url] + if os.path.exists(path): + if verify(path, sha256, False): + if verbose: + print("using already-download file", path, file=sys.stderr) + return + else: + if verbose: + print( + "ignoring already-download file", + path, + "due to failed verification", + file=sys.stderr, + ) + os.unlink(path) download(temp_path, "{}/{}".format(base, url), True, verbose) - if not verify(temp_path, sha256, verbose): + if verify_checksum and not verify(temp_path, checksums[url], verbose): raise RuntimeError("failed verification") if verbose: - eprint("moving {} to {}".format(temp_path, path)) + print("moving {} to {}".format(temp_path, path), file=sys.stderr) shutil.move(temp_path, path) finally: if os.path.isfile(temp_path): if verbose: - eprint("removing", temp_path) + print("removing", temp_path, file=sys.stderr) os.unlink(temp_path) @@ -267,6 +268,12 @@ def require(cmd, exit=True, exception=False): return None +def output_cmd(cmd): + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True) + output = p.communicate()[0].strip('"').strip() + return output + + def format_build_time(duration): """Return a nicer format for build time @@ -531,6 +538,7 @@ class FakeArgs: """Used for unit tests to avoid updating all call sites""" def __init__(self): + self.is_precompiled_bootstrap = False self.build = "" self.build_dir = "" self.clean = False @@ -558,6 +566,7 @@ def __init__(self, config_toml="", args=None): self.verbose = args.verbose self.color = args.color self.warnings = args.warnings + self.is_precompiled_bootstrap = False config_verbose_count = self.get_toml("verbose", "build") if config_verbose_count is not None: @@ -724,6 +733,119 @@ def download_toolchain(self): with output(self.rustc_stamp()) as rust_stamp: rust_stamp.write(key) + def is_bootstrap_modified(self): + cmd = ["git", "status", "--porcelain", "src/bootstrap"] + try: + output = output_cmd(cmd) + return bool(output) + except subprocess.CalledProcessError: + return False + + def download_or_build_bootstrap(self): + try: + if self.is_bootstrap_modified(): + self.is_precompiled_bootstrap = False + self.build_bootstrap() + return + last_commit = self.last_bootstrap_commit() + if last_commit is None: + self.build_bootstrap() + return + if self.bootstrap_out_of_date(last_commit): + success = self.download_bootstrap(last_commit) + if success: + stamp = os.path.join( + self.build_dir, "bootstrap", ".bootstrap-stamp" + ) + os.makedirs(os.path.dirname(stamp), exist_ok=True) + with open(stamp, "w") as f: + f.write(last_commit) + self.is_precompiled_bootstrap = True + + except Exception: + return + + if not self.is_precompiled_bootstrap: + self.build_bootstrap() + + def download_bootstrap(self, commit_hash): + filename = f"bootstrap-nightly-{self.build_triple()}.tar.xz" + tarball_suffix = ".tar.xz" + key = commit_hash + pattern = "bootstrap" + + bootstrap_path = os.path.join( + self.bin_root(), + f"nightly-{self.build_triple()}", + "bootstrap", + "bootstrap", + "bin", + "bootstrap", + ) + + if os.path.exists(bootstrap_path): + return True + + cache_dir = os.path.join(self.build_dir, "cache") + tarball_path = os.path.join(cache_dir, filename) + base_url = self.stage0_data.get("artifacts_server") + download_url = f"{key}/{filename}" + + if not os.path.exists(tarball_path): + try: + get( + base_url, + download_url, + tarball_path, + self.stage0_data, + verbose=self.verbose, + verify_checksum=False, + ) + except Exception: + return False + + try: + unpack( + tarball_path, + tarball_suffix, + self.bin_root(), + match=pattern, + verbose=self.verbose, + ) + except Exception: + return False + + return True + + def last_bootstrap_commit(self): + merge_email = self.stage0_data.get("git_merge_commit_email") + if not merge_email: + return None + + cmd = [ + "git", + "log", + "-1", + f"--author={merge_email}", + "--pretty=format:%H", + "src/bootstrap", + ] + + try: + commit_hash = output_cmd(cmd) + except subprocess.CalledProcessError: + return None + + return commit_hash.strip() if commit_hash else None + + def bootstrap_out_of_date(self, commit: str): + stamp_path = os.path.join(self.bin_root(), "bootstrap", ".bootstrap-stamp") + if not os.path.exists(stamp_path): + return True + with open(stamp_path, "r") as f: + stamp_commit = f.read().strip() + return stamp_commit != commit + def should_fix_bins_and_dylibs(self): """Whether or not `fix_bin_or_dylib` needs to be run; can only be True on NixOS or if bootstrap.toml has `build.patch-binaries-for-nix` set. @@ -995,7 +1117,11 @@ def bootstrap_binary(self): ... "debug", "bootstrap") True """ - return os.path.join(self.bootstrap_out(), "debug", "bootstrap") + if self.is_precompiled_bootstrap: + root = self.bin_root() + return os.path.join(root, "bootstrap", "bin", "bootstrap") + else: + return os.path.join(self.bootstrap_out(), "debug", "bootstrap") def build_bootstrap(self): """Build bootstrap""" @@ -1330,13 +1456,16 @@ def bootstrap(args): build = RustBuild(config_toml, args) build.check_vendored_status() + build_dir = args.build_dir or build.get_toml("build_dir", "build") or "build" + build.build_dir = os.path.abspath(build_dir) + if not os.path.exists(build.build_dir): os.makedirs(os.path.realpath(build.build_dir)) - # Fetch/build the bootstrap build.download_toolchain() sys.stdout.flush() - build.build_bootstrap() + + build.download_or_build_bootstrap() sys.stdout.flush() # Run the bootstrap @@ -1362,8 +1491,8 @@ def main(): # process has to happen before anything is printed out. if help_triggered: eprint( - "INFO: Downloading and building bootstrap before processing --help command.\n" - " See src/bootstrap/README.md for help with common commands." + "INFO: Checking if bootstrap needs to be downloaded or built before processing" + "--help command.\n See src/bootstrap/README.md for help with common commands." ) exit_code = 0