From 0d17d52c80326938bd664cd0fe2c154e56348c6d Mon Sep 17 00:00:00 2001 From: Hardik Kumar Date: Wed, 11 Nov 2026 19:47:24 +0530 Subject: [PATCH 1/9] diag: Fix source location for macro diagnostic message Use `source_callsite()` to point to the exact source location where the macro is used and emit a more precise diagnostic message. Signed-off-by: Hardik Kumar --- compiler/rustc_lint/src/let_underscore.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_lint/src/let_underscore.rs b/compiler/rustc_lint/src/let_underscore.rs index 07c2bf6f0ca13..ebf57a334ed18 100644 --- a/compiler/rustc_lint/src/let_underscore.rs +++ b/compiler/rustc_lint/src/let_underscore.rs @@ -184,13 +184,13 @@ impl<'tcx> LateLintPass<'tcx> for LetUnderscore { }; let is_drop_guard = matches!(ty.kind(), ty::Adt(adt, _) if cx.tcx.is_diagnostic_item(sym::DropGuard, adt.did())); - let can_use_init = is_top_level.then_some(local.init).flatten(); + let can_use_init = is_top_level.then_some(local.init).flatten().map(|init| init.span.source_callsite()); let sub = NonBindingLetSub { suggestion: pat.span, // We can't suggest `drop()` when we're on the top level. drop_fn_start_end: can_use_init - .map(|init| (local.span.until(init.span), init.span.shrink_to_hi())), + .map(|span| (local.span.until(span), span.shrink_to_hi())), is_assign_desugar: matches!(local.source, rustc_hir::LocalSource::AssignDesugar), }; if is_sync_lock { From c7cf5aac23374e07dba07debe554a07b8df4e906 Mon Sep 17 00:00:00 2001 From: Hardik Kumar Date: Wed, 11 Nov 2026 19:55:13 +0530 Subject: [PATCH 2/9] Add ui test for let_underscore macro diagnostic message Signed-off-by: Hardik Kumar --- .../let_underscore_lock_macro.rs | 8 ++++++++ .../let_underscore_lock_macro.stderr | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 tests/ui/lint/let_underscore/let_underscore_lock_macro.rs create mode 100644 tests/ui/lint/let_underscore/let_underscore_lock_macro.stderr diff --git a/tests/ui/lint/let_underscore/let_underscore_lock_macro.rs b/tests/ui/lint/let_underscore/let_underscore_lock_macro.rs new file mode 100644 index 0000000000000..8a99915910af9 --- /dev/null +++ b/tests/ui/lint/let_underscore/let_underscore_lock_macro.rs @@ -0,0 +1,8 @@ +//@ check-fail + +use std::sync::Mutex; + +fn main() { + let m = Mutex::new(String::from("rusty")); + let _ = dbg!(m.lock().unwrap()); //~ ERROR: non-binding let on a synchronization lock [let_underscore_lock] +} diff --git a/tests/ui/lint/let_underscore/let_underscore_lock_macro.stderr b/tests/ui/lint/let_underscore/let_underscore_lock_macro.stderr new file mode 100644 index 0000000000000..6c0b5346cc3d9 --- /dev/null +++ b/tests/ui/lint/let_underscore/let_underscore_lock_macro.stderr @@ -0,0 +1,19 @@ +error: non-binding let on a synchronization lock + --> $DIR/let_underscore_lock_macro.rs:7:9 + | +LL | let _ = dbg!(m.lock().unwrap()); + | ^ this lock is not assigned to a binding and is immediately dropped + | + = note: `#[deny(let_underscore_lock)]` (part of `#[deny(let_underscore)]`) on by default +help: consider binding to an unused variable to avoid immediately dropping the value + | +LL | let _unused = dbg!(m.lock().unwrap()); + | ++++++ +help: consider immediately dropping the value + | +LL - let _ = dbg!(m.lock().unwrap()); +LL + drop(dbg!(m.lock().unwrap())); + | + +error: aborting due to 1 previous error + From 043c3841da6a9891e2082f81fc7e11ec803b4ba1 Mon Sep 17 00:00:00 2001 From: Adwin White Date: Thu, 12 Nov 2026 11:28:52 +0800 Subject: [PATCH 3/9] make the fields of `And/Or` private --- .../rustc_hir_analysis/src/check/wfcheck.rs | 19 +++--- .../src/infer/outlives/obligations.rs | 5 +- .../rustc_type_ir/src/region_constraint.rs | 61 ++++++++++++++++++- 3 files changed, 70 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 75c98764443ba..8f29fb1185936 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -2478,7 +2478,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { let mut r = Ok(()); let mut validate_and = |and: &And, _>| { - for c in and.0.iter() { + for c in and.iter() { match c { LeafRegionConstraint::Ambiguity(_) | LeafRegionConstraint::RegionOutlives(..) @@ -2503,7 +2503,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { }; validate_and(&constraint.and_constraint); - for and in constraint.or_constraint.0.iter() { + for and in constraint.or_constraint.iter() { validate_and(and); } @@ -2607,12 +2607,11 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { expected: &SolverRegionConstraint<'tcx>, actual: &SolverRegionConstraint<'tcx>, ) { - let span_of_and = |c: &And<_, _>| { - c.0.iter().map(|leaf| leaf.span()).reduce(|span: Span, acc| acc.to(span)) - }; + let span_of_and = + |c: &And<_, _>| c.iter().map(|leaf| leaf.span()).reduce(|span: Span, acc| acc.to(span)); let span_of_or = |c: &Or<_, _>| { - c.0.iter().flat_map(|and| span_of_and(and)).reduce(|span, acc| acc.to(span)) + c.iter().flat_map(|and| span_of_and(and)).reduce(|span, acc| acc.to(span)) }; let check_leaf_constraint = @@ -2638,10 +2637,10 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { }; let check_and_constraint = |expected: &And<_, _>, actual: &And<_, _>| { - if expected.0.len() != actual.0.len() { + if expected.len() != actual.len() { Err((span_of_and(expected), span_of_and(actual))) } else { - for (expected, actual) in expected.0.iter().zip(&actual.0) { + for (expected, actual) in expected.iter().zip(actual) { check_leaf_constraint(expected, actual)?; } Ok(()) @@ -2649,10 +2648,10 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { }; let check_or_constraint = |expected: &Or<_, _>, actual: &Or<_, _>| { - if expected.0.len() != actual.0.len() { + if expected.len() != actual.len() { Err((span_of_or(expected), span_of_or(actual))) } else { - for (expected, actual) in expected.0.iter().zip(&actual.0) { + for (expected, actual) in expected.iter().zip(actual) { check_and_constraint(expected, actual)?; } Ok(()) diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index 17b005e4d9ce5..784f9042ff528 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -303,12 +303,11 @@ impl<'tcx> InferCtxt<'tcx> { } // FIXME(-Zassumptions-on-binders): actually implement OR as an OR - for c in constraint.and_constraint.0.into_iter().chain( + for c in constraint.and_constraint.into_iter().chain( constraint .or_constraint - .0 .into_iter() - .flat_map(|and_constraint| and_constraint.0.into_iter()), + .flat_map(|and_constraint| and_constraint.into_iter()), ) { match c { Ambiguity(span) => { diff --git a/compiler/rustc_type_ir/src/region_constraint.rs b/compiler/rustc_type_ir/src/region_constraint.rs index 4d2561dcf36aa..a73dc9dc072a3 100644 --- a/compiler/rustc_type_ir/src/region_constraint.rs +++ b/compiler/rustc_type_ir/src/region_constraint.rs @@ -1,4 +1,5 @@ //! The bulk of the logic for implementing `-Zassumptions-on-binders` +use std::ops::Deref; use derive_where::derive_where; use indexmap::IndexSet; @@ -288,7 +289,9 @@ impl LeafRegionConstraint { /// - No AND is a superset of another AND /// - All ANDs are in canonical form /// - If any AND is empty, i.e. trivially true, it is the only AND -pub struct Or(pub SmallVec<[And; 1]>); +// FIXME(-Zassumptions-on-binders): move to a separate module to avoid accidental +// mutation in this module? +pub struct Or(SmallVec<[And; 1]>); impl Or { pub fn with_spans(self, span: S) -> Or { Or(self.0.into_iter().map(|and| and.with_spans(span.clone())).collect()) @@ -417,14 +420,42 @@ impl std::fmt::Debug for Or { } } +impl IntoIterator for Or { + type Item = And; + type IntoIter = ; 1]> as IntoIterator>::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a, I: Interner, S: Clone + std::fmt::Debug> IntoIterator for &'a Or { + type Item = &'a And; + type IntoIter = <&'a SmallVec<[And; 1]> as IntoIterator>::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + (&self.0).into_iter() + } +} + +impl Deref for Or { + type Target = SmallVec<[And; 1]>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + #[derive_where(Clone, Hash, PartialEq, Eq; I: Interner, S)] #[derive(TypeVisitable_Generic, GenericTypeVisitable, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(StableHash_NoContext))] /// An AND of leaf constraints. Always in "canonical form", meaning: /// - No leaf constraints are present twice in this AND /// - No leaf constraint is trivially true, i.e. a reflexive `'a: 'a` +// FIXME(-Zassumptions-on-binders): move to a separate module to avoid accidental +// mutation in this module? pub struct And( - pub SmallVec<[LeafRegionConstraint; 1]>, + SmallVec<[LeafRegionConstraint; 1]>, ); impl And { pub fn with_spans(self, span: S) -> And { @@ -501,6 +532,32 @@ impl std::fmt::Debug for And { } } +impl IntoIterator for And { + type Item = LeafRegionConstraint; + type IntoIter = ; 1]> as IntoIterator>::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a, I: Interner, S: Clone + std::fmt::Debug> IntoIterator for &'a And { + type Item = &'a LeafRegionConstraint; + type IntoIter = <&'a SmallVec<[LeafRegionConstraint; 1]> as IntoIterator>::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + (&self.0).into_iter() + } +} + +impl Deref for And { + type Target = SmallVec<[LeafRegionConstraint; 1]>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + #[derive_where(Clone, Hash, PartialEq; I: Interner, S)] #[derive(TypeVisitable_Generic, GenericTypeVisitable, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(StableHash_NoContext))] From d66840a44c386976e0077e10e26e3ee1990e0985 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Thu, 19 Nov 2026 16:21:07 +0000 Subject: [PATCH 4/9] remove optionally_braced_mac_call --- compiler/rustc_ast/src/ast.rs | 27 --------------------------- 1 file changed, 27 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index a8a18a0742fde..8867d139396fc 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -1441,33 +1441,6 @@ impl Expr { } } - /// Determines whether this expression is a macro call optionally wrapped in braces . If - /// `already_stripped_block` is set then we do not attempt to peel off a layer of braces. - /// - /// Returns the [`NodeId`] of the macro call and whether a layer of braces has been peeled - /// either before, or part of, this function. - pub fn optionally_braced_mac_call( - &self, - already_stripped_block: bool, - ) -> Option<(bool, NodeId)> { - match &self.kind { - ExprKind::Block(block, None) - if let [stmt] = &*block.stmts - && !already_stripped_block => - { - match &stmt.kind { - StmtKind::MacCall(_) => Some((true, stmt.id)), - StmtKind::Expr(expr) if let ExprKind::MacCall(_) = &expr.kind => { - Some((true, expr.id)) - } - _ => None, - } - } - ExprKind::MacCall(_) => Some((already_stripped_block, self.id)), - _ => None, - } - } - pub fn to_bound(&self) -> Option { match &self.kind { ExprKind::Path(None, path) => Some(GenericBound::Trait(PolyTraitRef::new( From a241b256688502ce63d86ce88bc83a8427699d62 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Fri, 20 Nov 2026 13:47:06 +1100 Subject: [PATCH 5/9] Allow `#[derive(StableHash)]` for enums with >256 variants We currently don't derive StableHash for any enums that large, but LangItem currently has 236 variants so it will probably exceed 256 someday. --- compiler/rustc_macros/src/stable_hash.rs | 53 ++++++----- .../derive-stable-hash-enum-257.rs | 93 +++++++++++++++++++ 2 files changed, 123 insertions(+), 23 deletions(-) create mode 100644 tests/ui-fulldeps/derive-stable-hash-enum-257.rs diff --git a/compiler/rustc_macros/src/stable_hash.rs b/compiler/rustc_macros/src/stable_hash.rs index ba570dd008e77..1bbd9994df81f 100644 --- a/compiler/rustc_macros/src/stable_hash.rs +++ b/compiler/rustc_macros/src/stable_hash.rs @@ -102,35 +102,42 @@ fn stable_hash_discriminant(s: &mut synstructure::Structure<'_>) -> proc_macro2: // This helps to keep stable hashes consistent between stage1 and stage2. let n_variants = s.variants().len(); - // If this enum has no variants (and is therefore uninhabited), - // matching on `self` will cause the compiler to realise that all - // subsequent code is unreachable, triggering unhelpful warnings. - if n_variants == 0 { - return quote! {}; - } - let mut match_arms = proc_macro2::TokenStream::new(); - // Use a u8 discriminant, as it's measurably faster than usize. - // If support for larger enums is needed, take care to still use u8 - // when possible, to avoid regressions. - assert!( - n_variants <= 256, - "deriving StableHash for an enum with more than 256 variants is unsupported \ - (was: {n_variants})" - ); - for (discriminant, variant) in (0u8..).zip(s.variants()) { - let pat = variant.pat(); + match n_variants { + 0 => {} - quote! { - #pat => #discriminant.stable_hash(__hcx, __hasher), + // Use the smallest discriminant possible, as it's measurably faster than usize. + 1..=256 => { + for (discriminant, variant) in (0u8..).zip(s.variants()) { + let pat = variant.pat(); + quote! { #pat => #discriminant.stable_hash(__hcx, __hasher), } + .to_tokens(&mut match_arms); + } + } + 257..=65536 => { + for (discriminant, variant) in (0u16..).zip(s.variants()) { + let pat = variant.pat(); + quote! { #pat => #discriminant.stable_hash(__hcx, __hasher), } + .to_tokens(&mut match_arms); + } } - .to_tokens(&mut match_arms); + + 65537.. => panic!( + "deriving StableHash for an enum with more than 65536 variants is unsupported (was: {n_variants})" + ), } - quote! { - match *self { - #match_arms + // If this enum has no variants (and is therefore uninhabited), + // matching on `self` will cause the compiler to realise that all + // subsequent code is unreachable, triggering unhelpful warnings. + if n_variants == 0 { + quote! {} + } else { + quote! { + match *self { + #match_arms + } } } } diff --git a/tests/ui-fulldeps/derive-stable-hash-enum-257.rs b/tests/ui-fulldeps/derive-stable-hash-enum-257.rs new file mode 100644 index 0000000000000..13c96fd8a9d40 --- /dev/null +++ b/tests/ui-fulldeps/derive-stable-hash-enum-257.rs @@ -0,0 +1,93 @@ +#![feature(rustc_private)] +//@ edition: 2024 +//@ run-pass + +// Test that `#[derive(StableHash)]` supports enums with more than 256 variants. + +use std::collections::HashMap; + +use rustc_data_structures::stable_hash::{DummyStableHashCtxt, StableHash, StableHasher}; +use rustc_hashes::Hash128; +use rustc_macros::StableHash; + +extern crate rustc_data_structures; +#[expect( + unused_extern_crates, + reason = "Necessary to pull in object code, as other rustc crates are only shipped as rmeta" +)] +extern crate rustc_driver; +extern crate rustc_hashes; +extern crate rustc_macros; + +macro_rules! enum_with_all_variants { + ( + $( #[$meta:meta] )* + enum $Enum:ident { + $( $Variant:ident ),* $(,)? + } + ) => { + $( #[$meta] )* + enum $Enum { + $( $Variant, )* + } + + impl $Enum { + const ALL_VARIANTS: &[Self] = &[ + $( Self::$Variant, )* + ]; + } + } +} + +enum_with_all_variants! { + #[derive(Clone, Copy, Debug, StableHash)] + enum Enum257 { + V000, V001, V002, V003, V004, V005, V006, V007, V008, V009, + V010, V011, V012, V013, V014, V015, V016, V017, V018, V019, + V020, V021, V022, V023, V024, V025, V026, V027, V028, V029, + V030, V031, V032, V033, V034, V035, V036, V037, V038, V039, + V040, V041, V042, V043, V044, V045, V046, V047, V048, V049, + V050, V051, V052, V053, V054, V055, V056, V057, V058, V059, + V060, V061, V062, V063, V064, V065, V066, V067, V068, V069, + V070, V071, V072, V073, V074, V075, V076, V077, V078, V079, + V080, V081, V082, V083, V084, V085, V086, V087, V088, V089, + V090, V091, V092, V093, V094, V095, V096, V097, V098, V099, + + V100, V101, V102, V103, V104, V105, V106, V107, V108, V109, + V110, V111, V112, V113, V114, V115, V116, V117, V118, V119, + V120, V121, V122, V123, V124, V125, V126, V127, V128, V129, + V130, V131, V132, V133, V134, V135, V136, V137, V138, V139, + V140, V141, V142, V143, V144, V145, V146, V147, V148, V149, + V150, V151, V152, V153, V154, V155, V156, V157, V158, V159, + V160, V161, V162, V163, V164, V165, V166, V167, V168, V169, + V170, V171, V172, V173, V174, V175, V176, V177, V178, V179, + V180, V181, V182, V183, V184, V185, V186, V187, V188, V189, + V190, V191, V192, V193, V194, V195, V196, V197, V198, V199, + + V200, V201, V202, V203, V204, V205, V206, V207, V208, V209, + V210, V211, V212, V213, V214, V215, V216, V217, V218, V219, + V220, V221, V222, V223, V224, V225, V226, V227, V228, V229, + V230, V231, V232, V233, V234, V235, V236, V237, V238, V239, + V240, V241, V242, V243, V244, V245, V246, V247, V248, V249, + V250, V251, V252, V253, V254, V255, V256, + } +} + +fn main() { + assert_eq!(Enum257::ALL_VARIANTS.len(), 257); + + let mut hashes = HashMap::::with_capacity(257); + + for &variant in Enum257::ALL_VARIANTS { + let hcx = &mut DummyStableHashCtxt; + let mut hasher = StableHasher::new(); + variant.stable_hash(hcx, &mut hasher); + let hash = hasher.finish(); + + if let Some(old) = hashes.insert(hash, variant) { + panic!("StableHash collision between {old:?} and {variant:?}: {hash:?}"); + } + } + + assert_eq!(hashes.len(), 257); +} From 88fc66e39fc38d12359c037d830547dfbf676f8b Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 20 Nov 2026 06:06:58 +0000 Subject: [PATCH 6/9] Add crash test for 166128, which uses const param ty unchecked which says ice me --- tests/crashes/166128.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 tests/crashes/166128.rs diff --git a/tests/crashes/166128.rs b/tests/crashes/166128.rs new file mode 100644 index 0000000000000..1d55510e8cb6b --- /dev/null +++ b/tests/crashes/166128.rs @@ -0,0 +1,23 @@ +//@ known-bug: #166128 +//@ compile-flags: -Znext-solver=globally + +// const_param_ty_unchecked is internal-only and skips the ConstParamTy_ check that would +// otherwise reject fn() here (#161131), so the function pointer reaches valtree conversion, +// which fails without any error having been reported. + +#![feature(gca_min_const_items)] +#![feature(adt_const_params)] +#![feature(gca_const_items)] +#![feature(const_param_ty_unchecked)] + +trait Trait { + const F: fn(); +} + +fn take() +where + T: Trait, +{ +} + +fn main() {} From 5496de65c0a84488f8d9c6abdeeb930816c82762 Mon Sep 17 00:00:00 2001 From: Hardik Kumar Date: Fri, 20 Nov 2026 12:24:19 +0530 Subject: [PATCH 7/9] Use `find_ancestor_inside()` to find the span inside nested expressions And update the test to cover the case of a nested macro. Signed-off-by: Hardik Kumar --- compiler/rustc_lint/src/let_underscore.rs | 4 +- .../let_underscore_lock_macro.rs | 19 +++++++--- .../let_underscore_lock_macro.stderr | 37 +++++++++++++++---- 3 files changed, 45 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_lint/src/let_underscore.rs b/compiler/rustc_lint/src/let_underscore.rs index ebf57a334ed18..ec33f2755c8de 100644 --- a/compiler/rustc_lint/src/let_underscore.rs +++ b/compiler/rustc_lint/src/let_underscore.rs @@ -184,13 +184,13 @@ impl<'tcx> LateLintPass<'tcx> for LetUnderscore { }; let is_drop_guard = matches!(ty.kind(), ty::Adt(adt, _) if cx.tcx.is_diagnostic_item(sym::DropGuard, adt.did())); - let can_use_init = is_top_level.then_some(local.init).flatten().map(|init| init.span.source_callsite()); + let can_use_init = is_top_level.then_some(local.init).flatten().and_then(|init| init.span.find_ancestor_inside(local.span)); let sub = NonBindingLetSub { suggestion: pat.span, // We can't suggest `drop()` when we're on the top level. drop_fn_start_end: can_use_init - .map(|span| (local.span.until(span), span.shrink_to_hi())), + .map(|init_span| (local.span.until(init_span), init_span.shrink_to_hi())), is_assign_desugar: matches!(local.source, rustc_hir::LocalSource::AssignDesugar), }; if is_sync_lock { diff --git a/tests/ui/lint/let_underscore/let_underscore_lock_macro.rs b/tests/ui/lint/let_underscore/let_underscore_lock_macro.rs index 8a99915910af9..86e9878007359 100644 --- a/tests/ui/lint/let_underscore/let_underscore_lock_macro.rs +++ b/tests/ui/lint/let_underscore/let_underscore_lock_macro.rs @@ -1,8 +1,17 @@ //@ check-fail -use std::sync::Mutex; + use std::sync::Mutex; -fn main() { - let m = Mutex::new(String::from("rusty")); - let _ = dbg!(m.lock().unwrap()); //~ ERROR: non-binding let on a synchronization lock [let_underscore_lock] -} + macro_rules! foo { + () => { + let m = Mutex::new(String::from("rusty")); + let _ = dbg!(m.lock().unwrap()); //~ ERROR: non-binding let on a synchronization lock [let_underscore_lock] + }; + } + + fn main() { + let m = Mutex::new(String::from("rusty")); + let _ = dbg!(m.lock().unwrap()); //~ ERROR: non-binding let on a synchronization lock [let_underscore_lock] + + foo!(); + } diff --git a/tests/ui/lint/let_underscore/let_underscore_lock_macro.stderr b/tests/ui/lint/let_underscore/let_underscore_lock_macro.stderr index 6c0b5346cc3d9..25c0e5b6f64a2 100644 --- a/tests/ui/lint/let_underscore/let_underscore_lock_macro.stderr +++ b/tests/ui/lint/let_underscore/let_underscore_lock_macro.stderr @@ -1,19 +1,40 @@ error: non-binding let on a synchronization lock - --> $DIR/let_underscore_lock_macro.rs:7:9 + --> $DIR/let_underscore_lock_macro.rs:14:10 | -LL | let _ = dbg!(m.lock().unwrap()); - | ^ this lock is not assigned to a binding and is immediately dropped +LL | let _ = dbg!(m.lock().unwrap()); + | ^ this lock is not assigned to a binding and is immediately dropped | = note: `#[deny(let_underscore_lock)]` (part of `#[deny(let_underscore)]`) on by default help: consider binding to an unused variable to avoid immediately dropping the value | -LL | let _unused = dbg!(m.lock().unwrap()); - | ++++++ +LL | let _unused = dbg!(m.lock().unwrap()); + | ++++++ help: consider immediately dropping the value | -LL - let _ = dbg!(m.lock().unwrap()); -LL + drop(dbg!(m.lock().unwrap())); +LL - let _ = dbg!(m.lock().unwrap()); +LL + drop(dbg!(m.lock().unwrap())); | -error: aborting due to 1 previous error +error: non-binding let on a synchronization lock + --> $DIR/let_underscore_lock_macro.rs:8:14 + | +LL | macro_rules! foo { +... +LL | let _ = dbg!(m.lock().unwrap()); + | ^ this lock is not assigned to a binding and is immediately dropped +... +LL | foo!(); + | ------ in this macro invocation + | +help: consider binding to an unused variable to avoid immediately dropping the value + | +LL | let _unused = dbg!(m.lock().unwrap()); + | ++++++ +help: consider immediately dropping the value + | +LL - let _ = dbg!(m.lock().unwrap()); +LL + drop(dbg!(m.lock().unwrap())); + | + +error: aborting due to 2 previous errors From d37505229dd3b5ff5c9b0d42e5ea3bc1e0cbad73 Mon Sep 17 00:00:00 2001 From: Tess4552 Date: Tue, 17 Nov 2026 13:35:53 +0100 Subject: [PATCH 8/9] reflection: flatten Type --- compiler/rustc_attr_ir/src/lang_items.rs | 5 +- .../src/const_eval/machine.rs | 88 +++---- .../src/const_eval/type_info.rs | 227 ++++-------------- .../src/const_eval/type_info/adt.rs | 29 +-- .../src/interpret/intrinsics.rs | 19 ++ .../rustc_hir_analysis/src/check/intrinsic.rs | 15 +- compiler/rustc_span/src/symbol.rs | 2 + library/core/src/any.rs | 2 +- library/core/src/field.rs | 4 +- library/core/src/intrinsics/reflection.rs | 10 +- library/core/src/mem/type_info.rs | 119 +++++---- library/coretests/tests/mem/fn_ptr.rs | 17 +- library/coretests/tests/mem/type_info.rs | 41 ++-- tests/ui/reflection/feature_gate.rs | 4 +- tests/ui/reflection/feature_gate.stderr | 12 +- .../resolve/resolve-assoc-suggestions.stderr | 9 +- tests/ui/traits/ignore-err-impls.stderr | 9 +- 17 files changed, 263 insertions(+), 349 deletions(-) diff --git a/compiler/rustc_attr_ir/src/lang_items.rs b/compiler/rustc_attr_ir/src/lang_items.rs index fd46b0a59983f..cee591e8c0240 100644 --- a/compiler/rustc_attr_ir/src/lang_items.rs +++ b/compiler/rustc_attr_ir/src/lang_items.rs @@ -288,8 +288,8 @@ language_item_table! { CVoid, sym::c_void, c_void, Target::Enum, GenericRequirement::None; F16B, sym::f16b, f16b, Target::Struct, GenericRequirement::Exact(0); - Type, sym::type_info, type_struct, Target::Struct, GenericRequirement::None; - TypeGeneric, sym::type_info_generic, type_generic, Target::Enum, GenericRequirement::None; + TypeKind, sym::type_kind, type_kind, Target::Enum, GenericRequirement::None; + TypeGeneric, sym::type_info_generic, type_generic, Target::Enum, GenericRequirement::None; TypeId, sym::type_id, type_id, Target::Struct, GenericRequirement::None; // A number of panic-related lang items. The `panic` item corresponds to divide-by-zero and @@ -474,6 +474,7 @@ language_item_table! { // Experimental lang item for `Reflection and comptime`(https://goals.rust-lang.org/2025h2/reflection-and-comptime.html) FnPtr, sym::FnPtr, fn_ptr, Target::Struct, GenericRequirement::None; + DynTrait, sym::DynTrait, dyn_trait, Target::Struct, GenericRequirement::None; } /// The requirement imposed on the generics of a lang item diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 11e463727d838..fa9424f1d4dc1 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -636,7 +636,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { sym::type_id_type_of => { let ty = ecx.read_type_id(&args[0])?; - ecx.write_type_info(ty, dest)?; + ecx.write_type_kind(ty, dest)?; } sym::type_id_is_signed => { @@ -656,32 +656,26 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { sym::type_id_size_of => { let ty = ecx.read_type_id(&args[0])?; let layout = ecx.layout_of(ty)?; - let variant_index = if layout.is_sized() { - let (variant, variant_place) = ecx.project_downcast_named(dest, sym::Some)?; - let size_field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?; + + ecx.write_option(layout.is_sized().then(|| ()), dest, |ecx, field, _| { ecx.write_scalar( ScalarInt::try_from_target_usize(layout.size.bytes(), ecx.tcx.tcx).unwrap(), - &size_field_place, - )?; - variant - } else { - ecx.project_downcast_named(dest, sym::None)?.0 - }; - ecx.write_discriminant(variant_index, dest)?; + &field, + ) + })? } sym::type_id_element_ty => { let ty = ecx.read_type_id(&args[0])?; - let variant_index = if let ty::Array(ty, _) | ty::Slice(ty) = ty.kind() { - let (variant_idx, variant_place) = - ecx.project_downcast_named(dest, sym::Some)?; - let type_id_field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?; - ecx.write_type_id(*ty, &type_id_field_place)?; - variant_idx - } else { - ecx.project_downcast_named(dest, sym::None)?.0 - }; - ecx.write_discriminant(variant_index, dest)?; + + ecx.write_option( + match ty.kind() { + ty::Array(ty, _) | ty::Slice(ty) => Some(ty), + _ => None, + }, + dest, + |ecx, place, ty| ecx.write_type_id(*ty, &place), + )? } sym::type_id_array_len => { @@ -758,30 +752,40 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { } sym::type_id_function_ptr => { let ty = ecx.read_type_id(&args[0])?; - let variant_index = if let ty::FnPtr(sig, fn_header) = ty.kind() { - let (variant, variant_place) = ecx.project_downcast_named(dest, sym::Some)?; - let field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?; - let sig = sig.skip_binder(); // FIXME: handle lifetime bounds - ecx.write_fn_ptr_type_info(field_place, &sig, fn_header)?; - variant - } else { - ecx.project_downcast_named(dest, sym::None)?.0 - }; - ecx.write_discriminant(variant_index, dest)?; + + ecx.write_option( + match ty.kind() { + ty::FnPtr(sig, fn_header) => Some((sig, fn_header)), + _ => None, + }, + dest, + |ecx, place, (sig, fn_header)| { + let sig = sig.skip_binder(); // FIXME: handle lifetime bounds + ecx.write_fn_ptr_type_info(place, &sig, fn_header) + }, + )? + } + sym::type_id_dyn_trait => { + let ty: Ty<'tcx> = ecx.read_type_id(&args[0])?; + ecx.write_option( + match ty.kind() { + ty::Dynamic(p, r) => Some((p, r)), + _ => None, + }, + dest, + |ecx, place, (p, r)| ecx.write_dyn_trait_type_info(place, *p, *r), + )? } sym::type_id_points_to => { let ty = ecx.read_type_id(&args[0])?; - let variant_index = if let ty::RawPtr(pointee_ty, _) | ty::Ref(_, pointee_ty, _) = - ty.kind() - { - let (variant, variant_place) = ecx.project_downcast_named(dest, sym::Some)?; - let field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?; - ecx.write_type_id(*pointee_ty, &field_place)?; - variant - } else { - ecx.project_downcast_named(dest, sym::None)?.0 - }; - ecx.write_discriminant(variant_index, dest)?; + ecx.write_option( + match ty.kind() { + ty::RawPtr(pointee_ty, _) | ty::Ref(_, pointee_ty, _) => Some(pointee_ty), + _ => None, + }, + dest, + |ecx, place, pointee_ty| ecx.write_type_id(*pointee_ty, &place), + )? } sym::type_id_variants => { diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index f1700e57e6585..32c089cdb16c6 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -1,15 +1,13 @@ mod adt; -use std::borrow::Cow; - use rustc_abi::{ExternAbi, FieldIdx}; use rustc_attr_ir::Attribute::Tool; use rustc_attr_ir::lang_items::LangItem; use rustc_attr_ir::{AttrItem, Attribute, AttributeKind, HasAttrs}; use rustc_hir::intravisit::HirTyCtxt; use rustc_lint_defs::{Reflectiveness, ToolOptions}; -use rustc_middle::ty::layout::{HasTyCtxt, TyAndLayout}; -use rustc_middle::ty::{self, FnHeader, FnSigKind, FnSigTys, ScalarInt, Ty, TyCtxt}; +use rustc_middle::ty::layout::HasTyCtxt; +use rustc_middle::ty::{self, AdtKind, FnHeader, FnSigKind, FnSigTys, Ty, TyCtxt}; use rustc_span::def_id::DefId; use rustc_span::{Symbol, span_bug, sym}; @@ -51,191 +49,60 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { self.write_immediate(ptr, slice_place) } - /// Writes a `core::mem::type_info::TypeInfo` for a given type, `ty` to the given place. - pub(crate) fn write_type_info( + /// Writes a `core::mem::type_info::TypeKind` for a given type, `ty` to the given place. + pub(crate) fn write_type_kind( &mut self, ty: Ty<'tcx>, dest: &impl Writeable<'tcx, CtfeProvenance>, ) -> InterpResult<'tcx> { - let ty_struct = self.tcx.require_lang_item(LangItem::Type, self.tcx.span); - let ty_struct = self.tcx.type_of(ty_struct).no_bound_vars().unwrap(); - assert_eq!(ty_struct, dest.layout().ty); - let ty_struct = ty_struct.ty_adt_def().unwrap().non_enum_variant(); - // Fill all fields of the `TypeInfo` struct. - for (idx, field) in ty_struct.fields.iter_enumerated() { - let field_dest = self.project_field(dest, idx)?; - match field.name { - sym::kind => { - let variant_index = match ty.kind() { - ty::Tuple(fields) => { - let (variant, variant_place) = - self.project_downcast_named(&field_dest, sym::Tuple)?; - // project to the single tuple variant field of `type_info::Tuple` struct type - let tuple_place = self.project_field(&variant_place, FieldIdx::ZERO)?; - assert_eq!( - 1, - tuple_place - .layout() - .ty - .ty_adt_def() - .unwrap() - .non_enum_variant() - .fields - .len() - ); - self.write_tuple_type_info(tuple_place, fields, ty)?; - variant - } - ty::Array(_, _) => { - let (variant, _variant_place) = - self.project_downcast_named(&field_dest, sym::Array)?; - variant - } - ty::Slice(_) => { - let (variant, _variant_place) = - self.project_downcast_named(&field_dest, sym::Slice)?; - variant - } - ty::Adt(adt_def, _) => self.write_adt_type_info(&field_dest, *adt_def)?, - ty::Bool => { - let (variant, _variant_place) = - self.project_downcast_named(&field_dest, sym::Bool)?; - variant - } - ty::Char => { - let (variant, _variant_place) = - self.project_downcast_named(&field_dest, sym::Char)?; - variant - } - ty::Int(_) => { - let (variant, _variant_place) = - self.project_downcast_named(&field_dest, sym::Int)?; - variant - } - ty::Uint(_) => { - let (variant, _variant_place) = - self.project_downcast_named(&field_dest, sym::Int)?; - variant - } - ty::Float(_) => { - let (variant, _variant_place) = - self.project_downcast_named(&field_dest, sym::Float)?; - variant - } - ty::Str => { - let (variant, _variant_place) = - self.project_downcast_named(&field_dest, sym::Str)?; - variant - } - ty::Ref(_, _, _) => { - let (variant, _) = - self.project_downcast_named(&field_dest, sym::Reference)?; - variant - } - ty::RawPtr(_, _) => { - let (variant, _variant_place) = - self.project_downcast_named(&field_dest, sym::Pointer)?; - variant - } - ty::Dynamic(predicates, region) => { - let (variant, variant_place) = - self.project_downcast_named(&field_dest, sym::DynTrait)?; - let dyn_place = self.project_field(&variant_place, FieldIdx::ZERO)?; - self.write_dyn_trait_type_info(dyn_place, *predicates, *region)?; - variant - } - ty::FnPtr(_, _) => { - let (variant, _) = - self.project_downcast_named(&field_dest, sym::FnPtr)?; - variant - } - ty::Foreign(_) - | ty::Pat(_, _) - | ty::FnDef(..) - | ty::UnsafeBinder(..) - | ty::Closure(..) - | ty::CoroutineClosure(..) - | ty::Coroutine(..) - | ty::CoroutineWitness(..) - | ty::Never - | ty::Alias(..) - | ty::Param(_) - | ty::Bound(..) - | ty::Placeholder(_) - | ty::Infer(..) - | ty::Error(_) => self.project_downcast_named(&field_dest, sym::Other)?.0, + let ty_enum = self.tcx.require_lang_item(LangItem::TypeKind, self.tcx.span); + let ty_enum = self.tcx.type_of(ty_enum).no_bound_vars().unwrap(); + assert_eq!(ty_enum, dest.layout().ty); - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), - }; - self.write_discriminant(variant_index, &field_dest)? - } - other => span_bug!(self.tcx.span, "unknown `Type` field {other}"), - } - } - - interp_ok(()) - } + let (variant_index, _) = self.project_downcast_named( + dest, + match ty.kind() { + ty::Adt(def, _) => match def.adt_kind() { + AdtKind::Struct => sym::Struct, + AdtKind::Union => sym::Union, + AdtKind::Enum => sym::Enum, + }, + ty::Tuple(_) => sym::Tuple, + ty::Array(_, _) => sym::Array, + ty::Slice(_) => sym::Slice, + ty::Bool => sym::Bool, + ty::Char => sym::Char, + ty::Int(_) => sym::Int, + ty::Uint(_) => sym::Int, + ty::Float(_) => sym::Float, + ty::Str => sym::Str, + ty::Ref(_, _, _) => sym::Reference, + ty::RawPtr(_, _) => sym::Pointer, + ty::Dynamic(_, _) => sym::DynTrait, + ty::FnPtr(_, _) => sym::FnPtr, + ty::Foreign(_) + | ty::Pat(_, _) + | ty::FnDef(..) + | ty::UnsafeBinder(..) + | ty::Closure(..) + | ty::CoroutineClosure(..) + | ty::Coroutine(..) + | ty::CoroutineWitness(..) + | ty::Never + | ty::Alias(..) + | ty::Param(_) + | ty::Bound(..) + | ty::Placeholder(_) + | ty::Infer(..) + | ty::Error(_) => sym::Other, + ty::View(..) => unimplemented!(), // FIXME(scrabsha) + }, + )?; + self.write_discriminant(variant_index, dest)?; - fn write_field( - &mut self, - field_ty: Ty<'tcx>, - place: MPlaceTy<'tcx>, - layout: TyAndLayout<'tcx>, - name: Option, - idx: u64, - ) -> InterpResult<'tcx> { - for (field_idx, field_ty_field) in - place.layout.ty.ty_adt_def().unwrap().non_enum_variant().fields.iter_enumerated() - { - let field_place = self.project_field(&place, field_idx)?; - match field_ty_field.name { - sym::name => { - let name = match name.as_ref() { - Some(name) => Cow::Borrowed(name.as_str()), - None => Cow::Owned(idx.to_string()), // For tuples - }; - let name_place = self.allocate_str_dedup(&name)?; - let ptr = self.mplace_to_imm_ptr(&name_place, None)?; - self.write_immediate(*ptr, &field_place)? - } - sym::ty => { - let field_ty = self.tcx.erase_and_anonymize_regions(field_ty); - self.write_type_id(field_ty, &field_place)? - } - sym::offset => { - let offset = layout.fields.offset(idx as usize); - self.write_scalar( - ScalarInt::try_from_target_usize(offset.bytes(), self.tcx.tcx).unwrap(), - &field_place, - )?; - } - other => { - span_bug!(self.tcx.def_span(field_ty_field.did), "unimplemented field {other}") - } - } - } interp_ok(()) } - pub(crate) fn write_tuple_type_info( - &mut self, - tuple_place: impl Writeable<'tcx, CtfeProvenance>, - fields: &[Ty<'tcx>], - tuple_ty: Ty<'tcx>, - ) -> InterpResult<'tcx> { - let tuple_layout = self.layout_of(tuple_ty)?; - let fields_slice_place = self.project_field(&tuple_place, FieldIdx::ZERO)?; - self.allocate_fill_and_write_slice_ptr( - &fields_slice_place, - fields.len() as u64, - |this, i, place| { - let field_ty = fields[i as usize]; - this.write_field(field_ty, place, tuple_layout, None, i) - }, - ) - } - pub(crate) fn write_type_id_generics( &mut self, place: &impl Writeable<'tcx, CtfeProvenance>, diff --git a/compiler/rustc_const_eval/src/const_eval/type_info/adt.rs b/compiler/rustc_const_eval/src/const_eval/type_info/adt.rs index ec24dda8b46d3..0bd9b58050c79 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info/adt.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info/adt.rs @@ -1,7 +1,5 @@ -use rustc_abi::{FieldIdx, VariantIdx}; -use rustc_middle::ty::{ - AdtDef, AdtKind, Const, ConstKind, GenericArgKind, GenericArgs, Region, Ty, -}; +use rustc_abi::FieldIdx; +use rustc_middle::ty::{Const, ConstKind, GenericArgKind, GenericArgs, Region, Ty}; use rustc_span::{bug, span_bug, sym}; use crate::const_eval::CompileTimeMachine; @@ -10,29 +8,6 @@ use crate::interpret::{ }; impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { - // FIXME(type_info): No semver considerations for now - pub(crate) fn write_adt_type_info( - &mut self, - place: &impl Writeable<'tcx, CtfeProvenance>, - adt_def: AdtDef<'tcx>, - ) -> InterpResult<'tcx, VariantIdx> { - let variant_idx = match adt_def.adt_kind() { - AdtKind::Struct => { - let (variant, _) = self.project_downcast_named(place, sym::Struct)?; - variant - } - AdtKind::Union => { - let (variant, _) = self.project_downcast_named(place, sym::Union)?; - variant - } - AdtKind::Enum => { - let (variant, _) = self.project_downcast_named(place, sym::Enum)?; - variant - } - }; - interp_ok(variant_idx) - } - pub(super) fn write_generics( &mut self, place: &impl Writeable<'tcx, CtfeProvenance>, diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 2c7da64def4ce..974ea816c3b97 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -119,6 +119,25 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { interp_ok(()) } + /// Writes an option into dest, uses `write_some` to write to the field if val is some. + pub(crate) fn write_option( + &mut self, + val: Option, + dest: &PlaceTy<'tcx, M::Provenance>, + write_some: impl FnOnce(&mut Self, PlaceTy<'tcx, M::Provenance>, T) -> InterpResult<'tcx>, + ) -> InterpResult<'tcx> { + let variant_idx = match val { + Some(val) => { + let (variant_idx, some_place) = self.project_downcast_named(dest, sym::Some)?; + let payload_place = self.project_field(&some_place, FieldIdx::ZERO)?; + write_some(self, payload_place, val)?; + variant_idx + } + None => self.project_downcast_named(dest, sym::None)?.0, + }; + self.write_discriminant(variant_idx, dest) + } + /// Read a value of type `TypeId`, returning the type it represents. pub(crate) fn read_type_id( &self, diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index f15febe2c1633..9813cabe5b741 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -157,6 +157,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::type_id | sym::type_id_array_len | sym::type_id_docs + | sym::type_id_dyn_trait | sym::type_id_element_ty | sym::type_id_eq | sym::type_id_field_representing_type @@ -293,6 +294,18 @@ pub(crate) fn check_intrinsic_type( sym::type_id_array_len => (0, 0, vec![type_id_ty()], tcx.types.usize), sym::type_id_element_ty => (0, 0, vec![type_id_ty()], Ty::new_option(tcx, type_id_ty())), sym::type_id_eq => (0, 0, vec![type_id_ty(), type_id_ty()], tcx.types.bool), + sym::type_id_dyn_trait => { + let dyn_trait = tcx.require_lang_item(LangItem::DynTrait, span); + ( + 0, + 0, + vec![type_id_ty()], + Ty::new_option( + tcx, + Ty::new_adt(tcx, tcx.adt_def(dyn_trait), ty::GenericArgs::empty()), + ), + ) + } sym::type_id_field_representing_type => { (0, 0, vec![type_id_ty(), tcx.types.usize, tcx.types.usize], type_id_ty()) } @@ -366,7 +379,7 @@ pub(crate) fn check_intrinsic_type( 0, 0, vec![type_id_ty()], - tcx.type_of(tcx.lang_items().type_struct().unwrap()).no_bound_vars().unwrap(), + tcx.type_of(tcx.lang_items().type_kind().unwrap()).no_bound_vars().unwrap(), ), sym::field_representing_type_actual_type_id => (0, 0, vec![type_id_ty()], type_id_ty()), sym::field_representing_type_name => (0, 0, vec![type_id_ty()], Ty::new_static_str(tcx)), diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 70adbf6d7fee5..47b250157a5aa 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -2211,6 +2211,7 @@ symbols! { type_id, type_id_array_len, type_id_docs, + type_id_dyn_trait, type_id_element_ty, type_id_eq, type_id_field_representing_type, @@ -2236,6 +2237,7 @@ symbols! { type_ir_infer_ctxt_like, type_ir_inherent, type_ir_interner, + type_kind, type_length_limit, type_macros, type_name, diff --git a/library/core/src/any.rs b/library/core/src/any.rs index c6cb5b0f50c56..88364538146c2 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -819,7 +819,7 @@ impl TypeId { return None; } - if matches!(trait_represented_by_type_id.info().kind, TypeKind::DynTrait(_)) + if matches!(trait_represented_by_type_id.info(), TypeKind::DynTrait) && let Some(vtable) = type_id_vtable(self, trait_represented_by_type_id) { Some(TraitImpl { vtable }) diff --git a/library/core/src/field.rs b/library/core/src/field.rs index b17a78846ce2a..295a1a1db14d8 100644 --- a/library/core/src/field.rs +++ b/library/core/src/field.rs @@ -32,9 +32,9 @@ impl fmt::Debug } } let (variant, field) = const { - use crate::mem::type_info::{self, Type, TypeKind}; + use crate::mem::type_info::{self, TypeKind}; let type_id = type_info::of::(); - match Type::of::().kind { + match TypeKind::of::() { TypeKind::Struct => (None, Member::Name(type_id.field(0, FIELD as usize).name())), TypeKind::Tuple => (None, Member::Index(FIELD)), TypeKind::Enum => { diff --git a/library/core/src/intrinsics/reflection.rs b/library/core/src/intrinsics/reflection.rs index 700bb1f307dcc..0e071b2df3faa 100644 --- a/library/core/src/intrinsics/reflection.rs +++ b/library/core/src/intrinsics/reflection.rs @@ -25,7 +25,7 @@ pub fn type_id() -> crate::any::TypeId; /// not implement it. #[rustc_intrinsic] #[rustc_comptime] -pub fn type_id_type_of(_id: crate::any::TypeId) -> crate::mem::type_info::Type; +pub fn type_id_type_of(_id: crate::any::TypeId) -> crate::mem::type_info::TypeKind; /// Tests (at compile-time) if two [`crate::any::TypeId`] instances identify the /// same type. This is necessary because at const-eval time the actual discriminating @@ -189,6 +189,14 @@ pub fn type_id_points_to(_id: crate::any::TypeId) -> Option; #[rustc_comptime] pub fn type_id_points_mutably(_id: crate::any::TypeId) -> bool; +/// Given a `TypeId` that represents a dyn trait returns an [`core::mem::type_info::DynTrait`]. When called on +/// something else this returns `None`. +/// +/// The more user-friendly version of this intrinsic is [`core::any::TypeId::dyn_trait`]. +#[rustc_intrinsic] +#[rustc_comptime] +pub fn type_id_dyn_trait(_type_id: crate::any::TypeId) -> Option; + /// Given a `TypeId` that represents a function pointer returns an [`core::mem::type_info::FnPtr`]. /// When called on something else this returns `None`. /// diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index a4374ce5e70eb..7ef05604672b6 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -9,11 +9,43 @@ use crate::{fmt, intrinsics}; /// Compile-time type information. #[derive(Debug)] #[non_exhaustive] -#[lang = "type_info"] +#[lang = "type_kind"] #[unstable(feature = "type_info", issue = "146922")] -pub struct Type { - /// Per-type information - pub kind: TypeKind, +pub enum TypeKind { + /// Tuples. + Tuple, + /// Arrays. + Array, + /// Slices. + Slice, + /// Dynamic Traits. + DynTrait, + /// Structs. + Struct, + /// Enums. + Enum, + /// Unions. + Union, + /// Primitive boolean type. + Bool, + /// Primitive character type. + Char, + /// Primitive signed and unsigned integer type. + Int, + /// Primitive floating-point type. + Float, + /// String slice type. + Str, + /// References. + Reference, + /// Pointers. + Pointer, + /// Function pointers. + FnPtr, + /// FIXME(#146922): add all the common types + /// non exhaustive list: + /// - Never + Other, } /// Info of a trait implementation, you can retrieve the vtable with [Self::get_vtable] @@ -36,12 +68,12 @@ impl TypeId { #[unstable(feature = "type_info", issue = "146922")] #[rustc_const_unstable(feature = "type_info", issue = "146922")] #[rustc_comptime] - pub fn info(self) -> Type { + pub fn info(self) -> TypeKind { intrinsics::reflection::type_id_type_of(self) } } -impl Type { +impl TypeKind { /// Returns the type information of the generic type parameter. /// /// Note: Unlike `TypeId`s obtained via `TypeId::of`, the `Type` @@ -69,51 +101,11 @@ pub const fn of() -> TypeId { const { intrinsics::reflection::type_id::() } } -/// Compile-time type information. -#[derive(Debug)] -#[non_exhaustive] -#[unstable(feature = "type_info", issue = "146922")] -pub enum TypeKind { - /// Tuples. - Tuple, - /// Arrays. - Array, - /// Slices. - Slice, - /// Dynamic Traits. - DynTrait(DynTrait), - /// Structs. - Struct, - /// Enums. - Enum, - /// Unions. - Union, - /// Primitive boolean type. - Bool, - /// Primitive character type. - Char, - /// Primitive signed and unsigned integer type. - Int, - /// Primitive floating-point type. - Float, - /// String slice type. - Str(Str), - /// References. - Reference, - /// Pointers. - Pointer, - /// Function pointers. - FnPtr, - /// FIXME(#146922): add all the common types - /// non exhaustive list: - /// - Never - Other, -} - /// Compile-time type information about dynamic traits. /// FIXME(#146922): Add super traits and generics #[derive(Debug)] #[non_exhaustive] +#[lang = "DynTrait"] #[unstable(feature = "type_info", issue = "146922")] pub struct DynTrait { /// The predicates of a dynamic trait. @@ -293,6 +285,39 @@ impl TypeId { intrinsics::reflection::type_id_element_ty(self) } + /// Given a `TypeId` that represents a dyn trait returns an + /// [`DynTrait`]. When called on something else this returns `None`. + /// + /// # Examples + /// + /// + /// ``` + /// #![feature(type_info)] + /// use std::any::TypeId; + /// use std::fmt::Debug; + /// + /// #[derive(Debug)] + /// struct A; + /// + /// const { + /// let dyn_id = TypeId::of::(); + /// let predicates = dyn_id.dyn_trait().unwrap().predicates; + /// + /// let debug_ty = predicates[0].trait_ty.ty; + /// let send_ty = predicates[1].trait_ty.ty; + /// + /// let type_id = TypeId::of::(); + /// + /// assert!(type_id.trait_info_of_trait_type_id(debug_ty).is_some()); + /// assert!(type_id.trait_info_of_trait_type_id(send_ty).is_none()); + /// } + /// ``` + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn dyn_trait(self) -> Option { + intrinsics::reflection::type_id_dyn_trait(self) + } + /// When called on a `TypeId` representing an array this returns the length of the array in /// all other cases this returns zero. /// diff --git a/library/coretests/tests/mem/fn_ptr.rs b/library/coretests/tests/mem/fn_ptr.rs index 862048e4090d4..a4313ac744e43 100644 --- a/library/coretests/tests/mem/fn_ptr.rs +++ b/library/coretests/tests/mem/fn_ptr.rs @@ -1,5 +1,5 @@ use std::any::TypeId; -use std::mem::type_info::{Abi, FnPtr, Type, TypeKind}; +use std::mem::type_info::{Abi, FnPtr, TypeKind}; const STRING_TY: TypeId = const { TypeId::of::() }; const U8_TY: TypeId = const { TypeId::of::() }; @@ -18,15 +18,12 @@ fn test_fn_ptrs() { } #[test] -fn test_typekind() { - assert!(matches!(const { Type::of::().kind }, TypeKind::FnPtr)); - assert!(matches!(const { Type::of::().kind }, TypeKind::FnPtr)); - assert!(matches!(const { Type::of::().kind }, TypeKind::FnPtr)); - assert!(matches!(const { Type::of::().kind }, TypeKind::FnPtr)); - assert!(matches!( - const { Type::of::().kind }, - TypeKind::FnPtr - )); +fn test_type() { + assert!(matches!(const { TypeKind::of::() }, TypeKind::FnPtr)); + assert!(matches!(const { TypeKind::of::() }, TypeKind::FnPtr)); + assert!(matches!(const { TypeKind::of::() }, TypeKind::FnPtr)); + assert!(matches!(const { TypeKind::of::() }, TypeKind::FnPtr)); + assert!(matches!(const { TypeKind::of::() }, TypeKind::FnPtr)); } #[test] diff --git a/library/coretests/tests/mem/type_info.rs b/library/coretests/tests/mem/type_info.rs index c8f547a20d1af..8482ce8b38072 100644 --- a/library/coretests/tests/mem/type_info.rs +++ b/library/coretests/tests/mem/type_info.rs @@ -2,12 +2,12 @@ use std::any::{Any, TypeId}; use std::mem::offset_of; -use std::mem::type_info::{Const, Generic, GenericType, Type, TypeKind}; +use std::mem::type_info::{Const, Generic, GenericType, TypeKind}; #[test] fn test_arrays() { // Normal array. - assert!(matches!(Type::of::<[u16; 4]>().kind, TypeKind::Array)); + assert!(matches!(TypeKind::of::<[u16; 4]>(), TypeKind::Array)); const { let ty_id = TypeId::of::<[u16; 4]>(); assert!(ty_id.element_ty() == Some(TypeId::of::())); @@ -15,7 +15,7 @@ fn test_arrays() { } // Zero-length array. - assert!(matches!(Type::of::<[bool; 0]>().kind, TypeKind::Array)); + assert!(matches!(TypeKind::of::<[bool; 0]>(), TypeKind::Array)); const { let ty_id = TypeId::of::<[bool; 0]>(); assert!(ty_id.element_ty() == Some(TypeId::of::())); @@ -25,7 +25,7 @@ fn test_arrays() { #[test] fn test_slices() { - assert!(matches!(Type::of::<[usize]>().kind, TypeKind::Slice)); + assert!(matches!(TypeKind::of::<[usize]>(), TypeKind::Slice)); const { assert!(TypeId::of::<[usize]>().element_ty() == Some(TypeId::of::())); } @@ -282,21 +282,21 @@ fn test_primitives() { use TypeKind::*; const { - let Type { kind: Bool, .. } = (const { Type::of::() }) else { panic!() }; + let Bool = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Char, .. } = (const { Type::of::() }) else { panic!() }; + let Char = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; + let Int = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); @@ -304,7 +304,7 @@ fn test_primitives() { assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; + let Int = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); @@ -312,7 +312,7 @@ fn test_primitives() { assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; + let Int = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(!ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); @@ -320,7 +320,7 @@ fn test_primitives() { assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; + let Int = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(!ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); @@ -328,14 +328,14 @@ fn test_primitives() { assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Float, .. } = (const { Type::of::() }) else { panic!() }; + let Float = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Str(_ty), .. } = (const { Type::of::() }) else { panic!() }; + let Str = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == None); assert!(ty_id.reflected_attrs() == &[""; 0]); @@ -349,7 +349,7 @@ fn test_references() { use TypeKind::Reference; // Immutable reference. - let Type { kind: Reference, .. } = Type::of::<&u8>() else { panic!() }; + let Reference = TypeKind::of::<&u8>() else { panic!() }; const { let ty = TypeId::of::<&u8>(); assert!(ty.points_to() == Some(TypeId::of::())); @@ -357,7 +357,7 @@ fn test_references() { } // Mutable references. - let Type { kind: Reference, .. } = Type::of::<&mut u64>() else { panic!() }; + let Reference = TypeKind::of::<&mut u64>() else { panic!() }; const { let ty = TypeId::of::<&mut u64>(); assert!(ty.points_to() == Some(TypeId::of::())); @@ -365,7 +365,7 @@ fn test_references() { } // Wide references. - let Type { kind: Reference, .. } = Type::of::<&dyn Any>() else { panic!() }; + let Reference = TypeKind::of::<&dyn Any>() else { panic!() }; const { let ty = TypeId::of::<&dyn Any>(); assert!(ty.points_to() == Some(TypeId::of::())); @@ -378,7 +378,7 @@ fn test_pointers() { use TypeKind::Pointer; // Immutable pointer. - let Type { kind: Pointer, .. } = Type::of::<*const u8>() else { panic!() }; + let Pointer = TypeKind::of::<*const u8>() else { panic!() }; const { let ty = TypeId::of::<*const u8>(); assert!(ty.points_to() == Some(TypeId::of::())); @@ -386,7 +386,7 @@ fn test_pointers() { } // Mutable pointer. - let Type { kind: Pointer, .. } = Type::of::<*mut u64>() else { panic!() }; + let Pointer = TypeKind::of::<*mut u64>() else { panic!() }; const { let ty = TypeId::of::<*mut u64>(); assert!(ty.points_to() == Some(TypeId::of::())); @@ -394,7 +394,7 @@ fn test_pointers() { } // Wide pointer. - let Type { kind: Pointer, .. } = Type::of::<*const dyn Any>() else { panic!() }; + let Pointer = TypeKind::of::<*const dyn Any>() else { panic!() }; const { let ty = TypeId::of::<*const dyn Any>(); assert!(ty.points_to() == Some(TypeId::of::())); @@ -417,10 +417,7 @@ fn test_dynamic_traits() { trait ProjectorTrait<'a, 'b> {} fn preds_of() -> &'static [DynTraitPredicate] { - match const { Type::of::() }.kind { - TypeKind::DynTrait(d) => d.predicates, - _ => unreachable!(), - } + const { TypeId::of::().dyn_trait() }.unwrap().predicates } fn pred<'a>(preds: &'a [DynTraitPredicate], want: TypeId) -> &'a DynTraitPredicate { diff --git a/tests/ui/reflection/feature_gate.rs b/tests/ui/reflection/feature_gate.rs index 2dde268097930..7e12db8828028 100644 --- a/tests/ui/reflection/feature_gate.rs +++ b/tests/ui/reflection/feature_gate.rs @@ -1,8 +1,8 @@ -use std::mem::type_info::Type; +use std::mem::type_info::TypeKind; //~^ ERROR: use of unstable library feature `type_info` fn main() { - let ty = std::mem::type_info::Type::of::<()>(); + let ty = std::mem::type_info::TypeKind::of::<()>(); //~^ ERROR: use of unstable library feature `type_info` //~| ERROR: use of unstable library feature `type_info` } diff --git a/tests/ui/reflection/feature_gate.stderr b/tests/ui/reflection/feature_gate.stderr index 76ad18ffb0ba0..a68f821edeb21 100644 --- a/tests/ui/reflection/feature_gate.stderr +++ b/tests/ui/reflection/feature_gate.stderr @@ -1,8 +1,8 @@ error[E0658]: use of unstable library feature `type_info` --> $DIR/feature_gate.rs:1:5 | -LL | use std::mem::type_info::Type; - | ^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | use std::mem::type_info::TypeKind; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: see issue #146922 for more information = help: add `#![feature(type_info)]` to the crate attributes to enable @@ -11,8 +11,8 @@ LL | use std::mem::type_info::Type; error[E0658]: use of unstable library feature `type_info` --> $DIR/feature_gate.rs:5:14 | -LL | let ty = std::mem::type_info::Type::of::<()>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | let ty = std::mem::type_info::TypeKind::of::<()>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: see issue #146922 for more information = help: add `#![feature(type_info)]` to the crate attributes to enable @@ -21,8 +21,8 @@ LL | let ty = std::mem::type_info::Type::of::<()>(); error[E0658]: use of unstable library feature `type_info` --> $DIR/feature_gate.rs:5:14 | -LL | let ty = std::mem::type_info::Type::of::<()>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | let ty = std::mem::type_info::TypeKind::of::<()>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: see issue #146922 for more information = help: add `#![feature(type_info)]` to the crate attributes to enable diff --git a/tests/ui/resolve/resolve-assoc-suggestions.stderr b/tests/ui/resolve/resolve-assoc-suggestions.stderr index e6311962884f1..c12b95bc7c4c7 100644 --- a/tests/ui/resolve/resolve-assoc-suggestions.stderr +++ b/tests/ui/resolve/resolve-assoc-suggestions.stderr @@ -27,14 +27,15 @@ error[E0425]: cannot find type `Type` in this scope LL | let _: Type; | ^^^^ | +help: there is an enum variant `std::mem::type_info::Generic::Type`; try using the variant's enum + | +LL - let _: Type; +LL + let _: std::mem::type_info::Generic; + | help: you might have meant to use the associated type | LL | let _: Self::Type; | ++++++ -help: consider importing this struct - | -LL + use std::mem::type_info::Type; - | error[E0531]: cannot find tuple struct or tuple variant `Type` in this scope --> $DIR/resolve-assoc-suggestions.rs:25:13 diff --git a/tests/ui/traits/ignore-err-impls.stderr b/tests/ui/traits/ignore-err-impls.stderr index 46a2a7d55a2e5..561a7414f72e7 100644 --- a/tests/ui/traits/ignore-err-impls.stderr +++ b/tests/ui/traits/ignore-err-impls.stderr @@ -4,10 +4,15 @@ error[E0425]: cannot find type `Type` in this scope LL | impl Generic for S {} | ^^^^ not found in this scope | -help: consider importing this struct +help: there is an enum variant `std::mem::type_info::Generic::Type`; try using the variant's enum | -LL + use std::mem::type_info::Type; +LL - impl Generic for S {} +LL + impl Generic for S {} | +help: you might be missing a type parameter + | +LL | impl Generic for S {} + | ++++++ error: aborting due to 1 previous error From dac20be20f1837e2f0ef93106c534ec64bb97ae3 Mon Sep 17 00:00:00 2001 From: Tess4552 Date: Tue, 17 Nov 2026 16:20:47 +0100 Subject: [PATCH 9/9] reflection: add Never to Type --- compiler/rustc_const_eval/src/const_eval/type_info.rs | 2 +- compiler/rustc_span/src/symbol.rs | 1 + library/core/src/mem/type_info.rs | 5 +++-- library/coretests/tests/mem/type_info.rs | 5 +++++ 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index 32c089cdb16c6..fc2f7f3c5ac5c 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -80,6 +80,7 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { ty::RawPtr(_, _) => sym::Pointer, ty::Dynamic(_, _) => sym::DynTrait, ty::FnPtr(_, _) => sym::FnPtr, + ty::Never => sym::Never, ty::Foreign(_) | ty::Pat(_, _) | ty::FnDef(..) @@ -88,7 +89,6 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { | ty::CoroutineClosure(..) | ty::Coroutine(..) | ty::CoroutineWitness(..) - | ty::Never | ty::Alias(..) | ty::Param(_) | ty::Bound(..) diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 47b250157a5aa..a128abd07b460 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -275,6 +275,7 @@ symbols! { Mutex, MutexGuard, Named, + Never, NonZero, None, Normal, diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index 7ef05604672b6..9082128990a04 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -42,9 +42,10 @@ pub enum TypeKind { Pointer, /// Function pointers. FnPtr, + /// Never type. + Never, /// FIXME(#146922): add all the common types - /// non exhaustive list: - /// - Never + /// non exhaustive list Other, } diff --git a/library/coretests/tests/mem/type_info.rs b/library/coretests/tests/mem/type_info.rs index 8482ce8b38072..f119b0c97a9d7 100644 --- a/library/coretests/tests/mem/type_info.rs +++ b/library/coretests/tests/mem/type_info.rs @@ -31,6 +31,11 @@ fn test_slices() { } } +#[test] +fn test_never() { + assert!(matches!(TypeKind::of::(), TypeKind::Never)); +} + #[test] fn test_tuples() { const {